Reputation: 1884
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.
Upvotes: 4
Views: 967
Reputation: 8444
The example you are given are not method overloading.
1st Example: Show whether key exist in map or not.
m := make(map[int]int)
elem, ok := m[1]
elem = m[1]
elem
will receive either the value of "1" from the map or a "zero value" and ok will receive a bool that will be set to true if "foo" was actually present in the map.
Officially Site: Go not support overloading of methods and operators?
Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.
Golang supports variadic functions and methods. That is a another way you can (more or less) do function and method overloading in Golang.
A variadic function or method is a function or method that accepts a variable number of parameters.
o1 := Overload(1, 2, 3)
o2 := Overload(153, 196883, 1729, 1634, 5, 36)
o3 := Overload(1, -2)
For more details you can look to this post: Function and Method Overloading in Golang.
Upvotes: 0
Reputation: 30087
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.)
Upvotes: 7
Reputation: 81
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.
Upvotes: 1