我的理解是 Cat
和 *Cat
在 Go 中是不同的类型。那么为什么他们的名字会冲突呢?
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
}
编译器响应:
method redeclared: Cat.GetName
最佳答案
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
).
因此,如果您有一个以 Cat
作为接收者类型的方法,那么该方法也是 *Cat
方法集的一部分。所以 *Cat
将已经有了该方法,尝试声明“另一个”具有相同名称和 *Cat
的方法,因为接收者类型将是重复的。
验证一下,看这个例子:
type Cat struct{ Name string }
func (c Cat) GetName() string { return c.Name }
我们只用非指针接收器声明一个方法。如果我们检查/打印相应 *Cat
类型的方法:
func main() {
var cp *Cat = &Cat{} // Pointer
t := reflect.TypeOf(cp)
for i := 0; i < t.NumMethod(); i++ {
fmt.Println(t.Method(i).Name)
}
}
输出(在 Go Playground 上尝试):
GetName
类型*Cat
已经有一个GetName
方法。添加另一个带有 *Cat
接收器的接收器会与上面的接收器发生冲突。
官方FAQ的相关问题:Why does Go not support overloading of methods and operators?
关于pointers - 为什么带有指针和非指针接收器的方法在 Go 中不能具有相同的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758543/