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()
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3