为什么带有指针和非指针接收器的方法在Go中不能具有相同的名称?
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
我的理解是 Comiler响应: p>
重新声明了方法:Cat.GetName p>
blockquote>
div> Cat code>和
* Cat code>不同 输入Go。 那么为什么他们的名字冲突呢? p>
类型动物界面{
GetName()字符串
SetName(字符串)
}
type猫结构{
名称字符串
}
\ nfunc(c * Cat)GetName()字符串{
返回c.Name
}
func(c Cat)GetName()字符串{
返回c.Name
}
func(c * Cat )SetName(s字符串){
c.Name = s
}
code> pre>
The method set of any other type
T
consists of all methods declared with receiver typeT
. The method set of the corresponding pointer type*T
is the set of all methods declared with receiver*T
orT
(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?