146 points · by rednafi · 1y ago · 77 comments
The classic slice mistake is to forget that append doesn't necessarily return a completely new slice backed by a disjoint piece of memory, especially easy if you've been using a language where variables are immutable by default.
The problem is that it will often accidentally work; if you over-run the backing store, you will get a new piece of memory:
a := make([]int, 1, 1) // a is backed by a one-element-long piece of memory
a[0] = 42
b := append(a, 17) // this must allocate a new piece of memory
c := append(a, 37) // this must also allocate a new piece of memory
// At this point a == [42], b == [42, 17], c == [42, 37]
The problem is when the existing capacity is sufficient: a := make([]int, 1, 10) // a is backed by a ten-element-long piece of memory
a[0] = 42
b := append(a, 17) // no need to allocate: just use the existing memory
c := append(a, 37) // no need to allocate: just (re)use the existing memory
// At this point a == [42], b == [42, 37], c == [42, 37]
// ^^^^^^^^^^^^^ a := make([]int, 1, 10)
a[0] = 42
b := append(a, 17)
c := append(a, 37)
// Surprise! b and c both equal [42, 37]
The fact that append()'s behavior changes based on a hidden property (capacity) violates what I consider a core principle of language design: fundamental operations should be predictable and easy to reason about without having to think about implementation details.While I understand the performance benefits of reusing memory, language fundamentals shouldn't require developers to constantly think about backing array capacity to avoid bugs. This is especially problematic because it "usually works" until it doesn't - the worst kind of bug.
Modern languages have shown us better ways. Rust makes ownership explicit. Immutable-by-default languages prevent such surprises entirely. Even if Go wanted to maintain performance, they could have made this behavior more explicit - perhaps with separate "append_safe" and "append_reuse" functions.
Programming language fundamentals should be like good UI design - they should do what you expect them to do. When core operations have surprising edge cases, it creates cognitive overhead that ripples through all code written in that language.
``` a = append(a, elem) ```
If you assign it to anything else, `a` might still remain with the older slice memory which will cause worse problems than equality comparison.
So the kind of code you wrote is hardly ever written in production.
The advantage of having this is avoiding one more heap allocation for slice, which is a good tradeoff if you ask me.
`foo, err := callSomeFn()`
is followed by
``` if err != nil { return err } ```
too; it’s the ones that get missed that are the problem because convention will do nothing to prevent silly mistakes.
Like many things in Go, there are steps the language could take but chooses not to. For example, Swift implements copy-on-write for variable-length arrays. I’m not qualified to comment on whether the Go team is right or wrong in their decisions, but these aren’t unsolved problems.
In Go, this garbage collector frees people from thinking about freeing memory. But it doesn't free people from thinking about owned vs borrowed memory. And that's where bugs can happen.
It's not like you could have appended twice to the same List in Java and expected to get two disjoint arrays, unless you copy first, and `slices.Clone()` makes that easy in Go now too.
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 regression from C is the lack of const pointers.
type Colours (Red, Blue, Green)
//....
c := Colours.Blue
a := pred(c)
b := succ(c)
for x := range Colours {
//....
}
1976's Pascal style is unthinkable to ever land in Go, but we have iota and const, lets not complain.https://build-your-own.org/blog/20241125_go_slice_surprise/ goes a bit further, but this is really the point where I decided I wouldn't be able to stand Go.
I think you want Rust.
If all I need is a slice of memory, I'd rather only have to pass around the two pieces of data (pointer and length) than all three.
The growable array type (what you call "vector") is a venerable data type, although it does still have parameters you might reasonable tweak e.g. what's the correct growth factor? Doubling is popular but e.g. Zig chooses new_size = (old_size * 1.5) + 8 and you'll see disagreement about what API should be offered and why - e.g. C++ std::vector has the wrong reservation API
But this thing clearly isn't a mistake, it's intentionally a hybrid, and if it had been a huge success maybe everybody else would scramble to copy it.
A mutable String or Vec has all three fields, but the borrowed slice or str has just pointer and length.
Go chooses to be simpler by not having those kinds of separations, which also makes it a little less efficient under some circumstances.
This type isn't either of those things, it's a hybrid, and Go tries to get away with that because it's a garbage collected language so people don't need to care as much about ownership.
That can be addressed by passing the slice as a pointer: https://go.dev/play/p/h9Cg8qL9kNL
It's true that little has changed, but very little is changing in the data representation of any language, really. Even ones that are evolving rapidly.