golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.55k stars 520 forks source link

tour: [Slice defaults - Does not work as expected] #1532

Open mayyaannkk opened 1 year ago

mayyaannkk commented 1 year ago

Context: https://go.dev/tour/moretypes/10

In the description, it was defined correctly that "default is zero for the low bound and the length of the slice for the high bound" and the examples were also correct. But in the given code we are updating the values of our original array

// Given code
s := []int{2, 3, 5, 7, 11, 13}

s = s[1:4]
fmt.Println(s)

s = s[:2]
fmt.Println(s)

s = s[1:]
fmt.Println(s)

Output: image

This does not work as expected as each time s is updated to point to new values, after s = s[1:4] new array (or slice) becomes [3, 5, 7] and the next computation of s = s[:2] will be formed from this array only, giving us unexpected results.


The correct code will look something like this:

s := []int{2, 3, 5, 7, 11, 13}

a := s[1:4]
fmt.Println(a)

a = s[:2]
fmt.Println(a)

a = s[1:]
fmt.Println(a)

Output: image

lvpx commented 1 year ago

I believe this is intentional to show how default upper and lower bounds are changing while slicing. I may be wrong.

mayyaannkk commented 1 year ago

It might be but it did confuse me. I missed that it was overriding the slice and it made me think about how that output was even possible.