Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Golang multiple return overloading unique to the map type?

These both work:

m := make(map[int]int)
elem, ok := m[1]
elem = m[1]

Yet, this not allowed:

func overload() (int, int) {
    return 1, 1
}

func overload() int {
    return 1
}

func main() {
    x := overload()
    x, y := overload()
}

Also, is there a list of built-in syntax that doesn't generalize? I keep getting confused on what is a special syntax, i.e. map[string]int, make([]int, 10) and what is part of the language.

like image 900
dpington Avatar asked Oct 18 '25 12:10

dpington


2 Answers

It's special syntax. Besides the map key check, at least type assertion and channel receive have one- and two-element versions. In all those cases, the second element is a bool called ok in the doc examples; for type assertions it says whether the assertion succeeded and for channel receives it says whether the communication succeeded (false if the channel is closed and empty).

for...range has its own, different one- and two-element versions, though maybe range is more-obviously special.

There is a list of built-in functions. If you really want to know all of the corner cases, go over the spec--it is pretty short, not bogged down in the sorts of details some standards documents are, and worth the time once you've played with the language a bit. (Effective Go and the FAQ are also in this category.)

like image 74
twotwotwo Avatar answered Oct 21 '25 12:10

twotwotwo


Go doesn't support overloading even if the two functions have different arity in parameters or return values or even if the parameters have different parameter or return types.

http://golang.org/doc/faq#overloading

There is no list of special identifiers or special rules that the built-ins get away with as far as I know. However, they seem to be few and far in-between.

like image 38
CrazyWearsPJs Avatar answered Oct 21 '25 13:10

CrazyWearsPJs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!