Home >Backend Development >Golang >Why Can a Go Method with a Pointer Receiver Modify a Value Argument?
In Exercise 51 of the Tour of Go, it is stated that a method with a pointer receiver will have no effect on the value being passed into it. However, this behavior is not observed when assigning a value to a variable that is passed to the method.
To understand this discrepancy, it's important to recognize that in Go, 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. Crucially, if x is addressable and &x's method set contains m, then x.m() is effectively shorthand for (&x).m().
When a method with a pointer receiver is called on a value, the compiler automatically creates a temporary pointer to the value and passes that pointer to the method. This is done because the method actually operates on the pointer to the variable, not the variable itself. Therefore, even if the variable passed to the method is a value, the method still receives a pointer and can modify the value accordingly.
This "magic" is a result of Go's type system and method sets, which allow for concise and efficient code while maintaining strong typing.
The above is the detailed content of Why Can a Go Method with a Pointer Receiver Modify a Value Argument?. For more information, please follow other related articles on the PHP Chinese website!