Should you pass by value OR pass by address!?

·

1 min read

Go has the concept of address and pointer. And luckily -- no pointer arithmetic (we will talk more about this in the future). When we pass the parameters, we can either pass by value or pass by address.

Passing by value

creates a copy of the parameter's value in memory, and costs more space in the memory generally

Passing by address

creates a copy of the address of the parameter, pointing to the parameter's value, and costs less space in the memory generally, since the placeholder to store the address is fixed-sized.

But how do we know which to go with?

Here are a few rules of thumb -

  • Don't pass by address just to save a few bytes. Neglecting maintainability, for instance.
  • Don't pass pointers to a string (string) or to an interface value (io.Reader). In both cases, the value itself is fixed-sized and can be passed directly.
  • Use pointers on large structs, or smaller structs that will likely grow.

Hope these tips help you save a few brain cells next time!