3 ms·
>if you have two juxtaposed slices backed by the same contiguous block of memory, growing the former will write over the latter, but you quickly learn that you
by everybodyknows 6y ago
>if you have two juxtaposed slices backed by the same contiguous block of memory, growing the former will write over the latter, but you quickly learn that you should virtually never be appending to slices that don't have sole ownership over their backing memory.
You also may have to learn the hard way that saving a pointer to an entry of a slice that is later appended to may, or may not, depending on len()<cap(), produce an unintended copy.
>I particularly disagree here as well. There's often one way to do something in Go, and I've had very good luck by Googling "How to do x in Go?".
How about deciding whether a heavily-used pure-function method should take a whole struct as its receiver, or instead a pointer to it?
If a whole struct, then non-modification of the receiver is guaranteed by the compiler, a great boon to the code maintainer.
If a pointer, then any number of members may be added to the struct with no performance penalty per invocation.
How to choose?
- throwaway894345 6y ago> How about deciding whether a heavily-used pure-function method should take a whole struct as its receiver, or instead a pointer to it? If a whole struct, then non-modification of the receiver is guaranteed by the compiler, a great boon to the code maintainer. If a pointer, then any number of members may be added to the struct with no performance penalty per invocation. How to choose? It seems like you answered your own question. I’m not really sure what you’re looking for here... > You also may have to learn the hard way that saving a pointer to an entry of a slice that is later appended to may, or may not, depending on len()<cap(), produce an unintended copy. That’s all pretty inductive from the simple definition of a slice: a growable view into a backing array (where “grow” implies copying to a new, larger backing array). But yes, it can be surprising if you are jumping into Go without ever reading the basics. In general, the best practice is to avoid multiple references into a mutable slice (this seems like generally good advice in any language).