Home > Backend Development > Golang > Can Go Methods with Receiver Type `T` Be Called on Variables of Type `*T`?

Can Go Methods with Receiver Type `T` Be Called on Variables of Type `*T`?

Mary-Kate Olsen
Release: 2024-11-17 18:27:02
Original
654 people have browsed it

Can Go Methods with Receiver Type `T` Be Called on Variables of Type `*T`?

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()
}
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template