overexchange
overexchange

Reputation: 1

GO - How does an implicit method work?

In GO, I learnt that,

1)

Programmer can only define methods on named types(X) or pointer(*X) to named types

2)

An explicit method definition for type X implicitly defines the same method for type *X and vice versa, so, my understanding is, If I declare,

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

and declare,

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

then GO compiler gives,

Compile error: method re-declared

which indicates that, pointer method is implicitly defined and vice versa


With the given named type(Cat),

type Cat struct{
  Name string
  Age int
  Children []Cat
  Mother *Cat
} 

Scenario 1

Method(foo) defined on a named type(Cat), by programmer,

func (c Cat) foo(){
   // do stuff....
}

that implicitly defines method(foo) on pointer(*Cat) to named type, by GO compiler, that looks like,

func (c *Cat) foo(){
   // do stuff....
}

On creating variables of named type(Cat)

var c Cat
var p *Cat = &c

c.foo() has the method defined by programmer.

Question 1:

On invoking p.foo(), does implicit pointer method receive the pointer(p)?


Scenario 2

Method(foo) defined on a pointer(*Cat) to named type, by the programmer,

func (c *Cat) foo(){
   // do stuff....
  }

that implicitly defines method(foo) on named type(Cat), by the GO compiler, that looks like,

func (c Cat) foo(){
   // do stuff....
  }

On creating variables of named type(Cat)

var c Cat
var p *Cat = &c

p.foo() has method defined by programmer(above).

Question 2:

On invoking c.foo(), does the implicit non-pointer method receive the value c?

Upvotes: 0

Views: 435

Answers (1)

dev.bmax
dev.bmax

Reputation: 10601

  1. An explicit method definition for type X implicitly defines the same method for type *X and vice versa.

This is not correct. Methods are not defined implicitly. The only thing that a compiler does for you is implicitly replacing c.foo() with (*c).foo() or c.foo() with (&c).foo() for convenience. See the tour of Go

  1. The receiver of the method is either of type T or of type *T, based on your explicit declaration.

Upvotes: 5

Related Questions