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!
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}
}
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With