Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang: return a pointer or pass a reference

Tags:

go

What is the best way to "build" an object.

Leme write some code:

type Car struct {
   Wheels int
   Doors  int
} 

This cars are stored somewhere, somehow. So should my interface be the type of

func (s Store) GetCar() *Car

or should I make it

func (s Store) GetCar(*Car)

and pass a reference to a variable?

Im looking for some sort of rule of thumb.

Thanks!

like image 838
jisuskraist Avatar asked Sep 12 '25 16:09

jisuskraist


2 Answers

Go manages the heap/stack, keeping track when the reference goes outside of scope. So, you can return the pointer without any worries.

func (s *Store) GetCar() *Car {
    return &Car{Store: s}
}
like image 81
mattn Avatar answered Sep 16 '25 06:09

mattn


In many cases this is preferable

func (s Store) GetCar() *Car

because it is more convenient and readable, but has consequences. All variables such as Car are created inside the function which means they are placed onto stack. After function return this memory of stack is marked as invalid and can be used again. It a bit differs for pointer values such as *Car. Because pointer is virtually means you want to share the value with other scope and return an address, the value has to be stored somewhere in order to be available for calling function. It is copied onto heap memory and stays there until garbage collection finds no references to it.

It implies overheads:

  • copying values from stack to heap
  • additional work for garbage collection

The overheads is not significant if the value is relatively small. This is a reason why we have to pass an argument in io.Reader and io.Writer rather than have the value in return.

If you'd like to dive yourself into guts follow the links: Language Mechanics On Stacks And Pointers and Bad Go: pointer returns

like image 41
FDG Avatar answered Sep 16 '25 07:09

FDG