DEV Community

Discussion on: Pointers in practice

rhymes profile image

The general best practice is that you should use pointers if you want to modify the struct, values if you don't. You should also use a pointer if the struct is big. There's no rule applicable 100% of the times though. The go wiki has a really good summary on cases about receivers.

The same rules apply to return values. This is a great answer about all things pointers and values and builtin and custom types:

So, to anwser your direct questions:

In any situation it will always return a valid Session. Should this return Session or *Session? Why?

The caller is probably not going to modify the session and if the session is not a massive struct, go with values

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?

This sounds like a great case to use a pointer. Various methods modify the same instance so you shall pass around it as a pointer. It's memory efficient and GC is not going to matter since you need that instance during your program lifetime. There are going to be concurrency concerns if multiple goroutines access the same object, but that's another story (and you'd have the same access control issues with all languages) :D

Hope this helps

theodesp profile image
Theofanis Despoudis

There is a good read here