In Go, instantiating a struct in a function doesn’t always result in heap allocated memory. If you create a struct and it never leaves the function, Go can stack-allocate it. If you create a struct and pass it to another function directly, Go can copy the struct in place, which means it can still be stack-allocated. If you reference it then pass the pointer, now Go has to heap-allocate it, which means more GC.
Additionally, good programming practice recommends the use of immutable variables wherever you can. By passing references, you’re opening yourself up to unintentionally mutating structs all over the place. There are two cases where passing a pointer makes sense.
- If your function literally needs to mutate the inside of the struct. There are cases where this might be useful, primarily in some struct methods.
- Some singletons where there is internal state you probably don’t want to copy. A good example is a database connection; most database libraries will return their “connection” struct as a pointer.