Home >Backend Development >Golang >Why Does Go's Method with a Pointer Receiver Seem to Modify Non-Pointer Values?
Method with Pointer Receiver
In the Tour of Go, Exercise 51 explores method receivers. The provided explanation states that the Scale method, which operates on a pointer to a Vertex, has no effect when it receives a Vertex value directly. However, modifying the main function to pass a non-pointer Vertex contradicts this assertion.
Why the Discrepancy?
Despite the code receiving a non-pointer value, Scale successfully modifies the variable. This behavior can be attributed to Go's strong typing system. When a pointer to T is expected in a certain context, only a pointer to T (*T) can satisfy that requirement.
The compiler employs a behind-the-scenes transformation to enable this behavior:
"A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m():"
In essence, the compiler rewrites the code to pass a pointer to the non-pointer value when the receiving variable has a pointer receiver type. This enables the Scale method to modify the original variable.
The above is the detailed content of Why Does Go's Method with a Pointer Receiver Seem to Modify Non-Pointer Values?. For more information, please follow other related articles on the PHP Chinese website!