Pointer Methods on Non-Pointer Types Explained
In Go, the convention states that value methods can be invoked on both pointers and values, while pointer methods are restricted to pointers. However, an apparent exception to this rule is the ability to execute pointer methods on non-pointer values.
Consider the following code snippet:
package main import "fmt" type car struct { wheels int } func (c *car) fourWheels() { c.wheels = 4 } func main() { var c = car{} fmt.Println("Wheels:", c.wheels) c.fourWheels() // Here, a pointer method is invoked on a non-pointer value fmt.Println("Wheels:", c.wheels) }
The code successfully executes the pointer method fourWheels on the non-pointer value c. This might seem contradictory to the established rule.
In actuality, when invoking the fourWheels method on the non-pointer value c, you are using a shorthand notation. The expression c.fourWheels() is equivalent to (&c).fourWheels().
The Go specification states: "If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()."
In other words, Go implicitly dereferences the non-pointer value c to obtain a pointer to it, which is then used as the receiver for the pointer method.
To clarify the rule about pointer methods, it should be interpreted as follows:
The above is the detailed content of Why Can Pointer Methods Be Called on Non-Pointer Values in Go?. For more information, please follow other related articles on the PHP Chinese website!