简体   繁体   中英

Golang: Why Is Catching Certain Function Return Values Optional?

Why does go sometimes allow you to call functions without catching both return values? Such as:

func TestGolang() {
    myMap := make(map[string]string)
    test := myMap["value"]
    // or
    test, success := myMap["value"]
}

While at other times, you are required to catch all the return results and use a blank identifier if you do not want to use the value?

test := os.Stat("test") // fails
test, _ := os.Stat("test") // only way to make it work

I thought golang does not support different method signatures for a single function. How does the first example work? Can I implement my own functions that optionally return an error or a status flag but does not error out if the 2nd return value is not caught?

In fact, golang doesn't support function overloading, so you can't define different signatures for a function. But some operations from the language definition (like the channel receiver or obtaining data from a map) are 'blessed' with overloading-like behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM