1

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?

PressingOnAlways
  • 11,948
  • 6
  • 32
  • 59
  • 5
    It's not optional, it's a take-all-or-nothing. Possible duplicate of [Return map like 'ok' in Golang on normal functions](http://stackoverflow.com/questions/28487036/return-map-like-ok-in-golang-on-normal-functions/28487270#28487270) – icza Nov 29 '16 at 19:56
  • 2
    Too bad that Go has its own weird tricks the user can't even reproduce. It often feels like Go is "cheating". – mpm Nov 30 '16 at 01:21

1 Answers1

7

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.

  • For more detailed info, you can check out this answer: http://stackoverflow.com/questions/6986944/does-the-go-language-have-function-method-overloading – Juan Carlos Garcia Nov 29 '16 at 20:04
  • 3
    This is correct. A number of operations in the language definition (notably, type assertions, map value retrieval, and channel receives, though there may be others I'm forgetting) have both one and two value "versions", with the second (optional) value indicating the "status" of the operation (and in the case of a type assertion, also preventing a panic if it fails). Note, however, that any function can be called with *all* return values implicitly ignored by omission: https://play.golang.org/p/qdbcw5JtVK – Kaedys Nov 29 '16 at 21:36