乐闻世界logo
搜索文章和话题

What is the difference between a pointer receiver and a value receiver in Go?

1个答案

1

In Go, when defining methods for a type, you can choose to use a pointer receiver or a value receiver. The main difference between these two approaches lies in how the method receives and processes instances of the type.

Value Receiver

With a value receiver, the method receives a copy of the variable on which it is called. This means that any modifications made within the method do not affect the original data. Value receivers are suitable for:

  • When the method does not need to modify the receiver.
  • When the receiver type is small (e.g., basic data types or small structs), where copying has low cost.

Example:

go
type Rectangle struct { Length, Width float64 } func (r Rectangle) Area() float64 { return r.Length * r.Width }

In this example, the Area method uses a value receiver because it only reads the fields of the Rectangle struct without modifying them.

Pointer Receiver

With a pointer receiver, the method receives the memory address of the variable on which it is called. Through this address, the method can directly access (and modify) the original variable. Pointer receivers are suitable for:

  • When the method needs to modify the receiver.
  • When the receiver type is large (e.g., structs or arrays), where copying is expensive.
  • To maintain consistency when other methods of the type already use pointer receivers.

Example:

go
type Rectangle struct { Length, Width float64 } func (r *Rectangle) Scale(s float64) { r.Length *= s r.Width *= s }

In this example, the Scale method uses a pointer receiver because it needs to modify the original Rectangle struct's length and width.

Summary

Choosing between a value receiver and a pointer receiver primarily depends on the method's requirements (whether it needs to modify the receiver) and performance considerations (the size of the data structure and copying cost). Generally, if you need to modify the data in the receiver or the data structure is large, it is recommended to use a pointer receiver. If you only need to read the data and the data structure is small, a value receiver is sufficient.

2024年8月7日 18:23 回复

你的答案