Confusion in Go Receiver Methods Calling Syntax
The documentation in Effective Go claims that pointer methods can only be invoked on pointers, not values. However, a recent experiment challenges this notion.
When invoking vAge.Set(10) on a value type, the code compiles successfully. This appears to contradict the documentation. It poses the question: Is the code incorrect, or is there a misunderstanding in the documentation?
The answer lies in addressability. The Go language specification clarifies that a method call on a value is valid if the method is defined in the type of the value and the arguments can be assigned to the method's parameters.
If the value is addressable, it can be dereferenced to obtain a pointer to the underlying type. In this case, vAge is addressable because it is a value of a type (age) that supports the pointer operator (&).
Therefore, vAge.Set(10) is equivalent to (&vAge).Set(10), which is valid because (&vAge) is a pointer to the type age. The pointer method Set can be invoked on this pointer, allowing for the modification of the receiver.
This subtlety in the language allows value types in Go to behave in ways that may not be immediately apparent from the documentation. It highlights the importance of understanding the language specifications to avoid potential misconceptions.
The above is the detailed content of **Can Go Value Types Invoke Pointer Methods? A Look at Addressability and Method Calls**. For more information, please follow other related articles on the PHP Chinese website!