pointers - 为什么带有指针和非指针接收器的方法在 Go 中不能具有相同的名称?

标签 pointers methods go types

我的理解是 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

最佳答案

Spec: Method sets:

The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

因此,如果您有一个以 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/

相关文章:

c++ - 垃圾内存?

c++ - C++ 中的 void(*) 有什么意义吗?

c++ - 标识符 "customerMenu"未定义

python - 当模块分配给变量时如何使用模块中的方法

database - 使用或仅处理多种用户类型的Go继承

go - 如何返回第一个http响应以回答

Golang - Visual Studio Code 中的本地导入警告

c - 我想知道这段代码内部发生了什么?

C 将 void * 转换为 type_t

java - 从 ArrayList 中删除对象