Home > Backend Development > Golang > Can Go\'s Pointer Receiver Methods Be Called on Non-Pointer Variables?

Can Go\'s Pointer Receiver Methods Be Called on Non-Pointer Variables?

Barbara Streisand
Release: 2024-11-27 21:49:16
Original
961 people have browsed it

Can Go's Pointer Receiver Methods Be Called on Non-Pointer Variables?

Calling Methods for Pointer Type *T with Receiver T

The Go programming language specification states that the method set of any type T consists of all methods with receiver type T. However, the method set of the corresponding pointer type T is the set of all methods with receiver T or T (including the method set of T).

This means that we can call methods with a receiver of type *T on a variable of type T, as the compiler implicitly dereferences the variable to call the method.

To verify this concept, consider the following code:

package main

import (
    "fmt"
    "reflect"
)

type User struct{}

func (self *User) SayWat() {
    fmt.Println(self)
    fmt.Println(reflect.TypeOf(self))
    fmt.Println("WAT\n")
}

func main() {
    var user User = User{}

    fmt.Println(reflect.TypeOf(user), "\n")

    user.SayWat()
}
Copy after login

When we run this code, we observe that the SayWat() method can be called on the user variable, even though the method is defined with a pointer receiver. This is because the compiler automatically dereferences the variable for us.

However, it is important to note that we cannot call methods of *T on T directly. For example, the following code will fail with a compiler error:

func main() {
    var user User = User{}

    (&user).SayWat()
}
Copy after login

In this case, the compiler cannot implicitly dereference the variable because the SayWat() method is defined with a pointer receiver. To call the method, we must explicitly dereference the variable with the & operator.

Therefore, although we can call methods with a receiver of type T on a variable of type T, we cannot call methods of T on T directly.

The above is the detailed content of Can Go\'s Pointer Receiver Methods Be Called on Non-Pointer Variables?. 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