Home >Backend Development >Golang >Why Can I Call a Go Method with a Pointer Receiver Using an Object Instead of a Pointer?
Calling a Method Intended for Pointers with an Object
In Go, it is possible to call a method intended for a pointer receiver using an object instead of a pointer to it. This may seem unusual, but it is permitted according to the Go specification.
Consider the following code:
package main import "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) // v is not a pointer to a Vertex object fmt.Println(v.Abs()) }
In this example, v is an object of type Vertex, and Scale is a method intended for a pointer to Vertex. However, instead of passing a pointer to v, we directly call v.Scale(10).
Why is this not an error? The answer lies in a rule defined in the Go specification for method calls:
If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().
This rule states that if the value being called is addressable (i.e., it is a local variable or a pointer), then calling a method on it is equivalent to calling the method on its address. In this case, v is a local variable, so v.Scale(10) is interpreted as if we had written (&v).Scale(10) instead.
This convenience allows us to write cleaner and more concise code without having to explicitly create a pointer to the object before calling the method. However, it is important to note that this only works for methods with pointer receivers. For methods with value receivers, passing a pointer to the object is not allowed.
The above is the detailed content of Why Can I Call a Go Method with a Pointer Receiver Using an Object Instead of a Pointer?. For more information, please follow other related articles on the PHP Chinese website!