Method Calls with Object Versus Pointer Receivers
In Go, methods can be defined for types with value receivers (non-pointers) or pointer receivers (pointers). When calling a method with a pointer receiver by an object, Go automatically interprets the call as if it were made on a pointer to the object.
For example, consider the following code:
package main import ( "fmt" "math" ) type Vertex struct { X, Y float64 } func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func (v *Vertex) Scale(f float64) { v.X = v.X * f v.Y = v.Y * f } func main() { v := Vertex{3, 4} v.Scale(10) // Calling a method with a pointer receiver using an object fmt.Println(v.Abs()) }
Here, we have a Vertex type with both value and pointer receiver methods. In the main function, we create a Vertex object v and then call the Scale method on it. Normally, the Scale method expects a pointer receiver, but in this case, we are using an object.
The compiler notices that v is addressable and that its method set includes Scale. According to the Go specification:
"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()."
Therefore, the call v.Scale(10) is interpreted as (&v).Scale(10), which effectively passes a pointer to the v object to the Scale method. This allows the method to modify the object's X and Y fields as expected.
The above is the detailed content of How Does Go Handle Method Calls with Object Receivers When the Method Has a Pointer Receiver?. For more information, please follow other related articles on the PHP Chinese website!