Memory Management

Learn about memory management in Go.

Should structs be passed by value or by reference

Arguments to Go functions are always passed by value. When a struct (or array) type variable is passed into a function, the whole struct gets copied. If a pointer to a struct gets passed, then the pointer is copied, but the struct it points to isn’t. 8 bytes of memory (for 64bit architectures) get copied instead of whatever the size of the struct is. So does that mean it’s better to pass structs as pointers? As always - it depends.

Taking a pointer to a struct (or array):

  1. places it in heap memory rather than stack where it would normally be
  2. involves a garbage collector to manage that heap allocation.

Stack is fast and heap is slow. That means if you allocate structs more than pass them around, it’s way faster to let them be copied on stack:

Get hands-on with 1400+ tech skills courses.