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!
The most common way to do that would be to write it as:
func (s Store) GetCar() *Car
Or, if you don't want to use pointers, you can do it like:
func (s Store) GetCar() Car
The other alternative, making it GetCar(aCar *Car)
might work, but it will not be as clear since it's not obvious that aCar
should be sent empty and then populated by the function.
Go manage the heap/stack with looking the reference goes outside of scope. So you can return the pointer without any worries.
func (s *Store) GetCar() *Car {
return &Car{Store: s}
}