Why slicing slice not panic?

func main() {
	var s []int
	s = append(s, 1)
	// why not panic with 'index out of range' ?
	s = s[1:]
	println(len(s))
}

as the comment describes, thanks for help :slight_smile:

The length of the resulting slice is 0, but zero-length slices are fine. It’s somewhat less interesting than how appending to a nil slice results in the automatic allocation of a new slice.

1 Like

When you use the : to get a slice the indices i:j must be 0 <= i,j <= length, so the index in your example is within range.

One way to think of it is that the indices represent the gaps between the items. So for a slice of length 4 you have ‘gaps’ 0, 1, 2, 3, 4, where 0 is before the first item and 4 after the last item. (Without allowing 4, how do you include the last item?)

  s := []int{1,2,3,4}

  fmt.Printf("%v\n", s[0:2])

Prints [1 2] because the range is from the start of index 0 to start of index 2 (end of index 2-1).

and s[2:4] is [3 4] because the range is from the start of index 2 to start of index 4 (end of index 4-1).

s[4:] is [] because the range is from start of index 4 to end - equivalent to s[4:4], an empty slice.

s[5:] is an error, because 5 is greater than the length of s.

1 Like

i checked the doc of append, it says:

// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
...

appending to nil slice maybe similar to the case of unsufficient capacity.

thanks for your explaination, i also found the 0 <= low <= high <= length condition in the spec.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.