Home >Backend Development >Golang >## Why Can I Call a Pointer Receiver Method on a Value in Go?

## Why Can I Call a Pointer Receiver Method on a Value in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 18:39:17664browse

## Why Can I Call a Pointer Receiver Method on a Value in Go?

Go Receiver Methods Calling Syntax Confusion

The Go programming language provides two types of receiver methods: value receivers and pointer receivers. Value receivers operate directly on a value of a type, while pointer receivers operate on a pointer to a value of a type.

The documentation for Go states that value methods can be invoked on both pointers and values, but pointer methods can only be invoked on pointers. This is because pointer methods can modify the receiver, and invoking them on a copy of the value would discard those modifications.

However, the provided code example successfully calls a pointer method on a value. To understand why this is valid, we need to refer to the language specification:

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().

This means that if a variable is addressable (i.e., it can be passed by reference), we can invoke pointer methods on it as if it were a pointer. In the code example, the variable vAge is declared as a value, but it is addressable because it is a variable of a named type. Therefore, the call vAge.Set(10) is equivalent to (&vAge).Set(10), which is valid because &vAge is a pointer to vAge.

The above is the detailed content of ## Why Can I Call a Pointer Receiver Method on a Value in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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