3 ms·
I would add WAT 2.5: https://play.golang.org/p/gwcHh4-QhHK https://play.golang.org/p/gwcHh4-QhHK func main() { x := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
by schmichael 8y ago
I would add WAT 2.5: https://play.golang.org/p/gwcHh4-QhHK https://play.golang.org/p/gwcHh4-QhHK
func main() {
x := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println("orig: ", x)
mutate(x)
fmt.Println("append: ", x)
mutate(x[:4])
fmt.Println("sliced: ", x)
}
Appending to the end of the slice creates a new slice and therefore the caller doesn't see the mutation.
However appending to a slice-of-the-slice leaves capacity in mutate's copy-of-the-slice to append without allocating a new backing array. Therefore mutate happy bumps the len of its slice copy and mutates the callers slice!
This bit me once in real production code when reusing a []byte array to avoid allocations. The bug was obviously my fault, but this behavior can be easy to inadvertently trigger if you're trying to avoid allocations!
Edit: fixed code formatting. It's 2018 YC, please please please implement at least a subset of markdown.
- howeyc 8y agoIndeed, that's why one of the go versions (I don't remember which) added the capacity as the third argument when "slicing." https://play.golang.org/p/FCm8nOElz2n https://play.golang.org/p/FCm8nOElz2n