This gist demonstrates the use of pointers in go (and other similar languages)
Use &x
to get the address of x
Use *x
to get a value from an address x
When should I use a pointer?
- When you want to pass a variable to a function, to change something on the variable (perform a side-effect on the variable)
- When you have a large object that you want to pass between functions, it is more performant to pass a pointer around rather than copy a large object any times -- on a 64 bit machine, a pointer will take 8 bytes (64 bits / 8 bits in a byte)
When should I not use a pointer?
- When you want to protect against modifications to the original variable
Generally it comes down to a trade off between protecting against modifications to the original variable (immutability) and performance of copying the variable.
See some examples in action:
go run go-pointers.go