We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
A common dilemma when you define the methods of a structs is how you define your methods. Should you use value receivers or pointer receivers?
So, basically, it boils down to:
func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct) valueMethod() { } // method on value
Luckily, there are some basic rules you need to keep in mind:
- For a given type, donβt mix value and pointer receivers.
- If in doubt, use pointer receivers (they are safe and extendable).
You must use pointer receivers
- if any method needs to mutate the receiver
- for structs that contain a
sync.Mutex
or similar synchronizing field (they musnβt be copied)
You probably want to use pointer receivers
- for large structs or arrays (it can be more efficient)
- in all other cases
You probably want to use value receivers
- for
map
,func
andchan
types - for simple basic types such as
int
orstring
- for small arrays or structs that are value types, with no mutable fields and no pointers
- when they need to be concurrency safe (pointer receivers are not concurrency safe)
You may want to use value receivers
- for slices with methods that do not reslice or reallocate the slice.
You can read more about it in the Golang FAQ.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.