Implicit Addressing and Implicit Dereference in Method Calls

An interesting sample Go program was discussed in Google group:

package main
import "fmt"
type Foo struct {
	X float64
}
func (v *Foo) Neg() float64 {
	return -v.X
}
func main() {
	var v0 Foo = Foo{3}
	var v1 *Foo = & v0
	var v2 **Foo = & v1
	var v3 ***Foo = & v2

	fmt.Println(
			v0.Neg(), //OK, due to Rule 2.
			v1.Neg(), //OK, the normal case.
			v2.Neg(), //OK, due to Rule 3.
			v3.Neg()) //v3.Neg undefined (type ***Foo has no field or method Neg)
}

Rule 1:
Methods can be defined for any named type that is not a pointer or an interface.

Rule 2: (implicit addressing)
If x is addressable and &x’s method set contains m, x.m() is shorthand for (&x).m().

Rule 3: (implicit dereference)
x.m() might be a shorthand for (*x).m(), because Go has only “.” but not “->”.

There would be no way to call a method using a reciever type like ***Foo, because we cannot attach a method to a pointer type (Rule 1), so even implicit dereference (Rule 3) can reach reciever type like **Foo at most.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 31 other followers

%d bloggers like this: