Home > Backend Development > Golang > How does Go handle methods and pointers when the receiver type and the value type don't match?

How does Go handle methods and pointers when the receiver type and the value type don't match?

Barbara Streisand
Release: 2024-11-09 04:08:01
Original
532 people have browsed it

How does Go handle methods and pointers when the receiver type and the value type don't match?

Pointers in Golang: A Comprehensive Explanation

In the Tour of Go, it is mentioned that pointers are used to implement methods on values. However, what happens if we declare a method with a non-pointer receiver but attempt to use it on a pointer value, or vice versa?

The answer lies in two fundamental rules of the Go language:

Method Derivation:
Go allows methods to be derived from existing methods. In your example, the method func (v Vertex) Abs() float64 is derived from the method func (v *Vertex) Abs() float64. This means that when you declare the former method, a new implementation is automatically generated, which essentially calls the original method with a pointer to the receiver:

func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X+v.Y*v.Y) }
func (v Vertex) Abs() float64 { return Vertex.Abs(*v) } // Automatically generated
Copy after login

Therefore, regardless of whether you declare func (v *Vertex) Abs() or func (v Vertex) Abs(), in both cases, the generated method is called.

Automatic Address Taking:
Go can automatically generate a pointer to a variable. In the following case, the expression v.Abs() resolves to the code:

vp := &v
vp.Abs()
Copy after login

This means that when you pass a value to a method that expects a pointer and Go cannot automatically derive the method from an existing one, the compiler will generate a pointer to the value and then call the method on the pointer.

In summary, Go follows these rules to handle pointers and methods:

  • Methods with non-pointer receivers can be derived from methods with pointer receivers, and the derived method will call the original method with a pointer to the receiver.
  • If Go cannot automatically derive a method from an existing one, it will generate a pointer to the value and call the method on the pointer.

The above is the detailed content of How does Go handle methods and pointers when the receiver type and the value type don't match?. 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