-1

I am a new to Go and the behavior below confuses me:

package main

type Contractor struct{}

func (Contractor) doSomething() {}

type Puller interface {
    doSomething()
}

func process(p Puller) {
    //some code
}

func main() {
    t := Contractor{}
    process(&t) //why this line of code doesn't generate error
}

In Go some type and pointer to this time conform to the interface? So in my example t and &t are both Pullers?

1 Answers1

6

From the Go spec:

A type may have a method set associated with it. The method set of an interface type is its interface. 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).

In your case the method set of &t (which is of type *Contractor) is the set of all methods declared with receiver *Contractor or Contractor, so it contains the method doSomething().


This is also discussed in the Go FAQ, and in Go code review comments. Finally, this is covered by many past Stack Overflow questions like this one or that one.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412