Home > Backend Development > Golang > Why Can Pointer Methods Be Called on Non-Pointer Values in Go?

Why Can Pointer Methods Be Called on Non-Pointer Values in Go?

Patricia Arquette
Release: 2024-12-27 11:49:11
Original
777 people have browsed it

Why Can Pointer Methods Be Called on Non-Pointer Values in Go?

Pointer Methods on Non-Pointer Types Explained

In Go, the convention states that value methods can be invoked on both pointers and values, while pointer methods are restricted to pointers. However, an apparent exception to this rule is the ability to execute pointer methods on non-pointer values.

Consider the following code snippet:

package main

import "fmt"

type car struct {
    wheels int
}

func (c *car) fourWheels() {
    c.wheels = 4
}

func main() {

    var c = car{}
    fmt.Println("Wheels:", c.wheels)
    c.fourWheels()
    // Here, a pointer method is invoked on a non-pointer value
    fmt.Println("Wheels:", c.wheels)
}
Copy after login

The code successfully executes the pointer method fourWheels on the non-pointer value c. This might seem contradictory to the established rule.

In actuality, when invoking the fourWheels method on the non-pointer value c, you are using a shorthand notation. The expression c.fourWheels() is equivalent to (&c).fourWheels().

The Go specification states: "If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()."

In other words, Go implicitly dereferences the non-pointer value c to obtain a pointer to it, which is then used as the receiver for the pointer method.

To clarify the rule about pointer methods, it should be interpreted as follows:

  • Value methods can be invoked on both values and pointers.
  • Pointer methods can be invoked on pointers and, in certain cases, on non-pointer values, but only if the non-pointer value can be indirectly accessed through a pointer.

The above is the detailed content of Why Can Pointer Methods Be Called on Non-Pointer Values in Go?. 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