Go Methods on Pointer Types: Calling Methods with Receiver T for Pointer Type *T
Question:
The Go specification states that the method set of a pointer type T includes the method set of its corresponding type T. Does this mean that we can call methods with receiver T on variables of type T?
Answer:
While the specification suggests this, it is important to note that you cannot directly call methods of *T on T. Instead, the compiler automatically dereferences the variable to &T and invokes the method, effectively executing (&T).m().
This behavior is explicitly defined in the Go specification:
"Calls: 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(). "
Demonstration:
The following example illustrates this behavior:
package main import ( "fmt" "reflect" ) type User struct{} func (this *User) SayWat() { fmt.Println(reflect.TypeOf(this)) fmt.Println("WAT\n") } func main() { var user = User{} fmt.Println(reflect.TypeOf(user)) user.SayWat() }
Despite declaring the SayWat method with a receiver of *User, we can invoke it on user, which is of type User. The compiler automatically handles the dereferencing and calls (&user).SayWat().
Exception:
However, this only applies to addressable variables. If you attempt to call a pointer method on a non-addressable value, you will encounter an error. For instance:
func aUser() User { return User{} } ... aUser().SayWat() // Error: cannot call pointer method on aUser()
The above is the detailed content of Can Go Methods with Receiver Type `T` Be Called on Variables of Type `*T`?. For more information, please follow other related articles on the PHP Chinese website!