Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use pointers [duplicate]

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?

like image 597
Jim Pedid Avatar asked Dec 24 '15 18:12

Jim Pedid


People also ask

Should I use a pointer instead of a copy of my struct?

Illustration created for “A Journey With Go”, made from the original Go Gopher, created by Renee French. For many Go developers, the systematic use of pointers to share structs instead of the copy itself seems the best option in terms of performance.

What is the purpose of pointers in C++?

Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.

Can we assign one pointer to another in C?

Pointer assignment between two pointers makes them point to the same pointee. So the assignment y = x; makes y point to the same pointee as x . Pointer assignment does not touch the pointees. It just changes one pointer to have the same reference as another pointer.


1 Answers

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.

like image 166
Uvelichitel Avatar answered Sep 20 '22 14:09

Uvelichitel