https://tour.golang.org/moretypes/11
in this tutorial, s
is first assigned to
s := []int{2, 3, 5, 7, 11, 13}
then after that a series of actions are done to s
s = s[:0]
printSlice(s) // len=0 cap=6 []
s = s[:4]
printSlice(s) // len=4 cap=6 [2 3 5 7]
I code in python normally, so this confuses me a bit. When assigning s=s[:0]
, shouldn't s
be changed to the slice of original s
, meaning the s
is no longer an array but a slice? How can this slice again be assigned to a different length that actually has content in it?
Slices in go are a fancy structure that sits on top of an array. In your example:
s := []int{2, 3, 5, 7, 11, 13}
Creates an array with the contents: 2, 3, 5, 7, 11, 13 and the slice s
points to that array and it's as long as the array itself.
When slicing s = s[:0]
this creates a new slice with length 0 on the same array. Although the new slice is empty, because it shares the same array when you make the slice bigger with s = s[:4]
it allows you to see the first 4 values of the array.
Slices are like windows into an underlying array, and modifying the slice don't modify the array. So the first slice lets you see all of the elements in the array, the second one doesn't show you any of the elements and the third one let's you see only the first 4 elements.
Here I use []
to represent what the slice a
contents are in each part of your example:
[2 3 5 7 11 13]
[]2 3 5 7 11 13
[2 3 5 7] 11 13
But the array always remains the same.
As a note, because slicing doesn't create a new array, even if you save each of those slices in a different variable, the underlying array is the same, so if you modify one of the elements in one slice, you would see that same change in all of the slices that share the same array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With