Pointer methods can be called even if the variable is itself not a pointer.
According to the Go Spec,
. . . 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.
You can see this in this example:
https://codeeval.dev/gist/1da06f458ae88e108d654b3a89aeedb3
Similarly to pointer methods, value methods can be called even if the variable is itself not a value.
According to the Go Spec,
. . . a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer: pt.Mv is equivalent to (*pt).Mv.
You can see this in this example:
https://codeeval.dev/gist/ac2ff33cb0d9d006ee9aacdf2f5b537d
To learn more about pointer and value methods, visit the Go Spec section on Method Values, or see the Effective Go section about Pointers v. Values.
Note 1: The parenthesis (()
) around *p
and &f
before selectors like .Bar
are there for grouping purposes, and must be kept.
Note 2: Although pointers can be converted to values (and vice-versa) when they are the receivers for a method, they are not automatically converted to each other when they are arguments inside of a function.