I generally understand what pointers are and how they work. Where I run into trouble is when to use them in my own code.
When I have a struct that I want to create a new instance of, when should I return the instance and when should I return it as a pointer? Say I have a function to get a Session
instance in a web app. It either looks up the session from a cookie or creates a new one. In any situation it will always return a valid Session. Should this return Session
or *Session
? Why?
Now consider a card game that has Card
, Deck
, and Hand
structs. When creating a Hand
, a Card
is removed from the Deck
and put in a Hand
. There can only ever be 1 instance of a particular Card
, such as 8 of hearts, should Card
be passed around as a pointer? Would this be more memory efficient? Is there a concern about garbage collection here? Or can the GC still keep track of memory only being passed as a pointer?
My experience is in languages like Java, Ruby, Lua, Php, if that helps know where I'm coming from.
I'd highly, highly recommend these questions from the FAQs:
golang.org/doc/faq#Pointers