Go Pass by Value or Pointer
I’ve long struggled with the choice of how to pass around Go values, specifically structs. I was happy to find this article on the topic, specifically the conclusion, reproduced here:
- Types that are not structs or arrays should be passed by value.
- Struct types that don’t export their members and are clearly built as immutable value types, like time.Time, should be passed by value. Note that these types are relatively rare, and are even rarer to be defined by you.
- Arrays and all other struct types should be passed by pointer, whether small, large, stateful, or whatever.
- If you’re passing data that could be mutated by a concurrent process and its important to you for that data not to be mutated, explicitly make a copy of it before passing it along. Be aware that you can’t just rely on passing the data by value since that does not create a deep copy.
I’ll be referencing this moving forward, and taking the guesswork out of my passing conventions.