Pointer Method Invocation on Non-Pointer Values
In Go, it is possible to invoke pointer methods on non-pointer values, despite the general rule that pointer methods can only be invoked on pointers. This seemingly contradictory behavior can be explained by the concept of automatic pointer dereferencing.
In the given 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() fmt.Println("Wheels:", c.wheels) }
The expression c.fourWheels() is a shorthand for (&c).fourWheels(). This is because the receiver of fourWheels is a pointer, and c is a non-pointer value. Since c is addressable, the compiler automatically dereferences it to obtain a pointer to the car value, which is then used as the receiver.
This behavior is explicitly stated in the Go specification:
If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().
Therefore, while the general rule about pointer methods remains valid, automatic pointer dereferencing allows for the convenient invocation of pointer methods on non-pointer values in certain situations. It is important to note that this behavior only applies to methods with pointer receivers.
The above is the detailed content of Why Can I Call Pointer Methods on Non-Pointer Values in Go?. For more information, please follow other related articles on the PHP Chinese website!