4 ms·
The contract for append() has _always_ been that it might return the original pointer or it might copy-and-extend into a new pointer. That you can keep a refere
by brianolson 11y ago
The contract for append() has _always_ been that it might return the original pointer or it might copy-and-extend into a new pointer. That you can keep a reference of the previous version is programmer error for not having clear ownership of that pointer. There should be one canonical context for it, being a member of a struct or a local variable on the stack. Then you don't have to worry about having two copies of it. If you need multiple threads accessing the pointer, then you should have put a mutex on it.
- GhotiFish 11y agoI'd have to agree, that would fit my programming style, however it's not unreasonable for a beginner to think of slices and interfaces as basically "A pointer with some additional info". So if you have two data-structures that have a slice of the same data, you may conceptualize that as two data-structures pointing to the same data. It's wrong, but it's also not far off. I do think it's a little surprising that this doesn't work: func append6(is []int){ append(is, 6); } even though it appears to with basic testing.
- twic 11y agoThe point is more that it's a bad contract, isn't it? If a slice is something which can't safely be copied, then why can it be copied?
- SamReidHughes 11y agoSo that you can pass your slice to functions and actually make use of them. That somebody could go along and start modifying data structures they aren't supposed to is a problem in Java, C#, ... many languages.