26 ms·
This makes it very unclear what's going on. I had to test it to find that this specific use is special cased to not copy. And very surprisingly you don't even h
by ziml77 6y ago
This makes it very unclear what's going on. I had to test it to find that this specific use is special cased to not copy. And very surprisingly you don't even have to assign back to the same variable to get this no-copy behavior!
Edit: I didn't do my test quite right. It's not really special-cased. But it's still very surprising to see this happen:
Code:
s1 := []int{1, 2, 3, 10, 11, 12}
s2 := []int{4, 5, 6}
s3 := s1[:2]
s4 := append(s3[:2], s2...)
fmt.Println(s1)
fmt.Println(s4)
Output:
[1 2 4 5 6 12]
[1 2 4 5 6]
- millstone 6y agoThis is a Go idiom, one of the "slice tricks" that you are expected to just know. In fairness every language has its non-obvious idioms. It may or may not copy.
- Groxx 6y agoYup. Simple! But not easy. Go is absolutely filled with nuggets like this in my experience. False-simplicity is deeply ingrained in the standard library as well: https://fasterthanli.me/articles/i-want-off-mr-golangs-wild-ride https://fasterthanli.me/articles/i-want-off-mr-golangs-wild-...