Go - Addressable

Can I call this method on this variable?

The problem

I’ve encountered the below circumstance.

Why the value of type T can call the method declared with the *T type receiver even though the method is not in the method set of type T?

type circle struct {
	radius float64
}

func (c *circle) area() float64 {
	return math.Pi * c.radius * c.radius
}

func main() {
	c1 := circle{1}
	fmt.Println(c1.area())
}

Let’s figure it out!

Method Set

Go spec gives an intuitive description.

The method set of a type determines the methods that can be called on an operand of that type.

So why can we use a value of circle to call a method declared with *circle receiver instead of a pointer to that type?

Addressable

The reason is that the type T is addressable, which means you can get the address from it.

Go transfers the function call to (&T).method() implicitly if the type T is addressable. Below is the spec

As with method calls, a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value: t.Mp is equivalent to (&t).Mp.

Summary

Go transfers the function call T.method() to (&T).method() implicitly if the type T is addressable.

comments

comments powered by Disqus