GO-方法重新声明错误

Rule is, methods can be defined only on named type and pointer to named type.


For the below code,

package main

type Cat struct {
}

func (c Cat) foo() {
   // do stuff_
}

func (c *Cat) foo() {
  // do stuff_
}

func main() {

}

compiler gives error:

main.go:10: method redeclared: Cat.foo
    method(Cat) func()
    method(*Cat) func()

Above code defines,

method foo() for named type(Cat) and

method foo() for pointer to named type(*Cat).

Question:

For GO compiler, Why methods defined for different type is considered same?

In Go, receivers are a kind of syntactic sugar. The actual, runtime signature of function (c Cat) foo() is foo(c Cat). The receiver is moved to a first parameer.

Go does not support name overloading. There can be only one function of with name foo in a package.

Having said the statements above, you see that there would be two functions named foo with different signatures. This language does not support it.

You cannot do that in Go. The rule of thumb is to write a method for a pointer receiver and Go will use it whenever you have a pointer or value.

If you still need two variants, you need name the methods differently.

For example, you can model some feline behavior like this:

package main

import (
    "fmt"
)

type Growler interface{
    Growl() bool
}

type Cat struct{
    Name string
    Age int
} 

// *Cat is good for both objects and "object references" (pointers to objects)
func (c *Cat) Speak() bool{
    fmt.Println("Meow!")
    return true
}

func (c *Cat) Growl() bool{
    fmt.Println("Grrr!")
    return true
}


func main() {
    var felix Cat // is not a pointer
    felix.Speak() // works :-)
    felix.Growl() // works :-)

    var ginger *Cat = new(Cat) 
    ginger.Speak() // works :-)
    ginger.Growl() // works :-)
}