66

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Jim Pedid
  • 2,730
  • 3
  • 23
  • 27
  • 3
    That's basically it -- I'm not sure if you're asking more than a yes or no question. Re: #2, it's good to remember that *everything* in Go is passed by value, and in this case you would be passing a pointer by value. – JimB Dec 24 '15 at 18:14
  • 1
    It is essentially a Yes/No question, but if it were a no then I would have wanted to know what was wrong. Thanks for your input. For 2, is it correct to say that the pointer is passed by value, but we use that pointer to modify the object that it points to, but if we pass in a struct (instead of a pointer to that struct), then we will only ever be able to modify the copy? – Jim Pedid Dec 24 '15 at 18:15
  • yes, for number two your comment is correct. The pointer is passed by value but allows you access to the thing it points to. If your receiver is a struct rather than a struct pointer, the method will be operating on a copy. – evanmcdonnal Dec 24 '15 at 20:19

1 Answers1

32

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.

Uvelichitel
  • 8,220
  • 1
  • 19
  • 36