简体   繁体   中英

Why can't methods with pointer and non-pointer receivers have the same name in 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

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 ).

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM