My understanding is that Cat and *Cat are different types in Go. So why do their names conflict?
type Animal interface {
GetName() string
SetName(string)
}
type Cat struct {
Name string
}
func (c *Cat) GetName() string {
return c.Name
}
func (c Cat) GetName() string {
return c.Name
}
func (c *Cat) SetName(s string) {
c.Name = s
}
Comiler response:
method redeclared: Cat.GetName
Spec: Method sets:
The method set of any other type
Tconsists of all methods declared with receiver typeT. The method set of the corresponding pointer type*Tis the set of all methods declared with receiver*TorT(that is, it also contains the method set ofT).
So if you have a method with Cat as the receiver type, that method is also part of the method set of *Cat. So *Cat will already have that method, attempting to declare "another" one with the same name and *Cat as the receiver type will be a duplicate.
To verify it, see this example:
type Cat struct{ Name string }
func (c Cat) GetName() string { return c.Name }
We only declare one method with non-pointer receiver. If we check / print the methods of the corresponding *Cat type:
func main() {
var cp *Cat = &Cat{} // Pointer
t := reflect.TypeOf(cp)
for i := 0; i < t.NumMethod(); i++ {
fmt.Println(t.Method(i).Name)
}
}
Output (try it on the Go Playground):
GetName
The type *Cat already has a GetName method. Adding another one with *Cat receiver would collide with the one above.
Related question from the official FAQ: Why does Go not support overloading of methods and operators?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With