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

Why Can I Call Pointer Methods on Non-Pointer Values in Go?

Mary-Kate Olsen
Release: 2024-12-30 13:00:18
Original
976 people have browsed it

Why Can I Call Pointer Methods on Non-Pointer Values in Go?

Pointer Method Invocation on Non-Pointer Values

In Go, it is possible to invoke pointer methods on non-pointer values, despite the general rule that pointer methods can only be invoked on pointers. This seemingly contradictory behavior can be explained by the concept of automatic pointer dereferencing.

In the given 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()
    fmt.Println("Wheels:", c.wheels)
}
Copy after login

The expression c.fourWheels() is a shorthand for (&c).fourWheels(). This is because the receiver of fourWheels is a pointer, and c is a non-pointer value. Since c is addressable, the compiler automatically dereferences it to obtain a pointer to the car value, which is then used as the receiver.

This behavior is explicitly stated in the Go specification:

If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().

Therefore, while the general rule about pointer methods remains valid, automatic pointer dereferencing allows for the convenient invocation of pointer methods on non-pointer values in certain situations. It is important to note that this behavior only applies to methods with pointer receivers.

The above is the detailed content of Why Can I Call Pointer Methods 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