"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Does Go Handle Pointer and Value Receivers in Methods?

How Does Go Handle Pointer and Value Receivers in Methods?

Published on 2024-11-16
Browse:788

How Does Go Handle Pointer and Value Receivers in Methods?

Go Pointers: Receiver and Value Types

In Go, pointers are indispensable for understanding object-oriented programming and memory management. When dealing with pointers, it's crucial to grasp the distinction between receiver types in methods.

The Go Tour example you provided illustrates this concept:

type Vertex struct {
    X, Y float64
}

func (v *Vertex) Abs() float64 {
    return math.Sqrt(v.X*v.X   v.Y*v.Y)
}

func main() {
    v := &Vertex{3, 4}
    fmt.Println(v.Abs())
}

Here, the Abs method receives a pointer receiver (*Vertex). However, you noticed that you could also use a value receiver (Vertex) and obtain the same result. How is this possible?

Receiver and Value Types

Go allows derived methods. A method with a pointer receiver can inherit from a method with a value receiver. This means that a value receiver method, e.g., func (v Vertex) Abs() float64, automatically generates a pointer receiver method:

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) }  // GENERATED METHOD

Automatic Address Taking

Another important feature is Go's automatic address taking. Consider the following code without an explicit pointer receiver:

func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X v.Y*v.Y) }
func main() {
    v := Vertex{3, 4}
    v.Abs()
}

Go implicitly takes the address of the value passed to the Abs method. This is equivalent to the following:

vp := &v
vp.Abs()

Conclusion

In Go, understanding the role of receiver types and the automatic address taking feature is crucial for efficient pointer usage. You can derive pointer receiver methods from value receiver methods, and Go will automatically pass the address of values without explicitly using pointers.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3