Skip to main content

Command Palette

Search for a command to run...

Method Receivers - Pointer vs Value

Updated
1 min read
A

Golang Developer and Blockchain certified professional

Pointer receivers Vs Value receivers

//pointer receiver

func (t *Type) Method() {}

//value receiver

func (t Type) Method() {}

**When should you use pointer receivers ? **

Modify the receiver If you want to change the state of the receiver in a method, manipulating the value of it, use a pointer receiver. It’s not possible with a value receiver, which copies by value. Any modification to a value receiver is local to that copy.

Second is the consideration of efficiency. If the receiver is large, a big struct for instance, it will be much cheaper to use a pointer receiver.

Value receivers operate on a copy of the original type value. This means that there is a cost involved, especially if the struct is very large, and pointer received are more efficient.

**When should you use value receivers **

If you don’t need to edit the receiver value, use a value receiver. Value receivers are concurrency safe, while pointer receivers are not concurrency safe.

There can be a situation when you might want to use pointer receivers for methods where you’d normally use a value receiver, and it’s when you have other pointer receivers defined on that type, and for consistency you should use pointer receivers across all the methods.

More from this blog

Ashok V

37 posts

Go beyond limits with our Golang blog with Tips, Tricks, and Insights