Go Slices Pitfalls
The cluster focuses on the quirks, bugs, and counterintuitive behaviors of slices in Go, including shared underlying arrays, append reallocation effects, passing by value with hidden references, and comparisons to other languages.
Activity Over Time
Top Contributors
Keywords
Sample Comments
Have you used Go and ran into problems with people overwriting data in slices underneath you? Was it to such a degree that it took precedence over other bugs and slowed down development in the effort to catch these mistakes manually?
This isn't really a practical problem.If you created the slice, you control it and you can modify its elements, append to it, etc.If you didn't create the slice, you don't control it. If you want to modify it or append to it, you should copy it first.This has reflected how I've seen Go used professionally by people experienced in the language. The language could offer more help (but probably never will), but it's not hardly a regression from C. The real r
100% agree - slices are a very leaky abstraction in Go
Indeed: https://go.googlesource.com/go/+/master/src/runtime/slice.go...
There's a layer of pointer indirection when using slices in Go, you may be able to eke out some time by moving to arrays on the stack.
Go has it's own fundamental problems. Something very basic that turns me off is what happens to the original slice when appending to a it (done by calling append(slice, item) and using the result). Does it get modified? It may or it may not. Either one would be useful, but this way nobody else can hold a reference to the slice because it becomes useless to them.
Yes, that's not good, but it seems like in practice this doesn't come up too often in Go?More typically you're building a new slice containing the results of a query or other computation, and returning it without keeping a reference. Or instead of exposing an internal map, you have a Get method.
Maps and channels and functions are passed by reference. Slices are passed and returned by value but sometimes share state invisibly, the worst of both worlds. It would make more sense if Go either made this stuff immutable, made defensive copies, or refused and required using explicit pointers for all these cases.
I am afraid there isn't. In fact, it's called a "slice trick" and listed in Go wiki: https://github.com/golang/go/wiki/SliceTricks
Golang's slices view of the world is addictive.