Pointer or not and mutable or not
If you don’t know what’s a pointer or want a reminder you may read the excelent Dave Cheney post : Understand Go pointers in less than 800 words or your money back
When should I use pointer, when should I use reference ?
TLDR: Methods using receiver pointers are common; the rule of thumb for receivers is, “If in doubt, use a pointer.”
- Slices, maps, channels, strings, function values, and interface values are implemented with pointers internally, and a pointer to them is often redundant.
- Elsewhere, use pointers for big structs or structs you’ll have to change, and otherwise pass values, because getting things changed by surprise via a pointer is confusing.
There is more advices on StackOverFlow
Mutable or Immutable ?
In Go pointer are mutable and value are not. The trap (as seen in point before) is that some type are pointers, and so are mutable :
String despite being a pointer is immutable (in fact a string is an encapsulation of a slice).
So be careful not mutating your slice, maps or pointer in your function… if you don’t want to.
How to copy a slice ?
In Go internaly a slice is a pointer, so you may be surprised if you try to copy a slice with a new affectation. And in your function should be carefully not mess with value passed as slice… if you don’t want to modify it.
// Copy slice a in b b = make(T, len(a)) // a and b are now two slice containing same data copy(b, a)
More tips : slice trick
Explain internal struct / slice / string :
Ho, and : Forget arithmetic on pointer
Unlike C, you can’t do arithmetic on pointer in golang, this is for your good (and I really apreciate).