3 ms·
What would you expect that code to do? I'd expect to have two different slices, s2 and s3, to contain all the same elements aside from the last. [a, b, c, x]
by sethammons 4y ago
What would you expect that code to do?
I'd expect to have two different slices, s2 and s3, to contain all the same elements aside from the last.
[a, b, c, x] and [a, b, c, y] and s1 remains [a, b, c]
- deleted 4y ago[deleted]
- Groxx 4y agoWhen printing s1, s2, then s3: It does exactly that, yes: https://go.dev/play/p/rs2FeK_QUjs https://go.dev/play/p/rs2FeK_QUjs [a b c] [a b c x] [a b c y] But maybe it doesn't: https://go.dev/play/p/Na-eL0sOV9e https://go.dev/play/p/Na-eL0sOV9e [a b c] [a b c y] <- this is now "y" [a b c y] So... maybe they share the same backing array? Lets try setting s2[0] to "z" after appending with the original code: https://go.dev/play/p/mAB-gUb0shB https://go.dev/play/p/mAB-gUb0shB [a b c] [z b c x] [a b c y] Apparently not. But also apparently yes? https://go.dev/play/p/k1ciGzyS2gc https://go.dev/play/p/k1ciGzyS2gc [z b c] <- this changed too [z b c y] [z b c y] Let's try appending just one more item before redoing ^ that example, where they all shared the same data: https://go.dev/play/p/5JneXHMeUjx https://go.dev/play/p/5JneXHMeUjx [a b c] [z b c x x2] [a b c y y2] Notice that in all of these examples, I haven't explicitly declared a length or capacity. There's nothing "funny looking" or clearly intentionally allowing these different behaviors, it's just simple, very-common slice use. .... so yeah. This is a source of a number of hard-to-track-down bugs.
- sethammons 4y agoAmazing, very interesting
- Jcowell 4y agoIs there a bug or issue on this in their GitHub cause wtf is this ?
- Groxx 4y agoThis is expected behavior. It's just an easy thing to screw up by accident.