When to use pointers

Jim Pedid picture Jim Pedid · Dec 24, 2015 · Viewed 18.5k times · Source

I'm new to the Go Language, and have only minimal background in C/C++, so naturally I'm struggling with the idea of when to use pointers and when not to use pointers. Although this question might be considered open-ended, I'm wondering what some guidelines on when to return structs and when to return pointers, (and equivalently when to accept structs / pointers as arguments).

From what I can guess, the following statements hold true:

  1. structs are passed into functions by value. That is, a copy of a structure is made when passing it into a function.
  2. if I want to pass a structure by reference, then I would instead use a pointer argument in the function definition, and use the addressof operator when calling the function.
  3. The reason why I would want to pass in a structure by reference is because either the structure I'm passing in is large, and it would be taxing on memory to pass it by value (unlikely) or if I want to make changes to the copy that I'm passing in (more likely).
  4. As a corollary to 3.), I should pass by value unless I have one of the reasons above to pass by reference.

Are my assumptions correct? Or am I missing the mark on pointers?

Answer

Uvelichitel picture Uvelichitel · Dec 24, 2015

Your assumptions are correct. About #3, Go is concurrent language and passing by reference in goroutines make them all read same structure which is safe, but also make them modify same structure which is dangerous.