In the Tour of Go, it is mentioned that pointers are used to implement methods on values. However, what happens if we declare a method with a non-pointer receiver but attempt to use it on a pointer value, or vice versa?
The answer lies in two fundamental rules of the Go language:
Method Derivation:
Go allows methods to be derived from existing methods. In your example, the method func (v Vertex) Abs() float64 is derived from the method func (v *Vertex) Abs() float64. This means that when you declare the former method, a new implementation is automatically generated, which essentially calls the original method with a pointer to the receiver:
func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X+v.Y*v.Y) } func (v Vertex) Abs() float64 { return Vertex.Abs(*v) } // Automatically generated
Therefore, regardless of whether you declare func (v *Vertex) Abs() or func (v Vertex) Abs(), in both cases, the generated method is called.
Automatic Address Taking:
Go can automatically generate a pointer to a variable. In the following case, the expression v.Abs() resolves to the code:
vp := &v vp.Abs()
This means that when you pass a value to a method that expects a pointer and Go cannot automatically derive the method from an existing one, the compiler will generate a pointer to the value and then call the method on the pointer.
In summary, Go follows these rules to handle pointers and methods:
The above is the detailed content of How does Go handle methods and pointers when the receiver type and the value type don't match?. For more information, please follow other related articles on the PHP Chinese website!