3 ms·
You cannot "overrun the buffer" nor can a callee add stuff to the end of your list; you can give them a memory buffer with unused space and they may use it, and
by morelisp 4y ago
You cannot "overrun the buffer" nor can a callee add stuff to the end of your list; you can give them a memory buffer with unused space and they may use it, and then you can also mistakenly use it later.
Honestly, you seem to be too detached to understand this. If you really want to know how it works go through some official Go documentation. It's not fundamentally different than some feature in other languages, it's just that in Go this is the default growable list type and in other languages it's usually a non-default type.
As for whether it's ultimately useful - of course we can debate, but everyone still builds lists one element at a time and allocators still allocate by doubling, so there's at least one immediate and obvious use of capacity beyond the used length.
- iainmerrick 4y agoI coincidentally was just looking at some docs, and I think I have a handle on it (to it?:) now. The specific strange design decision in Go is that you can create a child slice that has its own starting offset and length, but may or may not inherit its parent’s capacity. Just because it’s well-defined doesn’t mean it isn’t tricky. Even if you kept the semantics the same but made cap=len for subslices by default, surely that would be an improvement. Rather than a “rare slice trick”, it ought to be normal. Or is there an advantage to the current default that I’m overlooking?
- Groxx 4y agocap==len is effectively the default - most slicing is done with [start:end], not [start:end:additional-cap]
- iainmerrick 4y agoNo it’s not -- I just checked the language specification and it says: After slicing the array a a := [5]int{1, 2, 3, 4, 5} s := a[1:4] the slice s has type []int, length 3, capacity 4 Many of us here are arguing that the default should be cap==len==3, but it’s not, it’s 4.
- Groxx 4y agoWelp. TIL. Yeah, that's much more error prone I think. It's the sort of thing that only kinda makes sense on zero-valued arrays... and even then it's dubious at best. Bleh. I'm gonna go review some old code now D:
- morelisp 4y agoI mean, if you want Java, it's right there. The advantage is that you get the fast path by default. Since Go programs are generally not awash in buffer reuse bugs despite its semantic trickiness, this seems like something different languages can reasonably prioritize differently.