Why does the following behavior occur:
a := []int{1, 2, 3}
fmt.Println(a[0:])
fmt.Println(a[1:])
fmt.Println(a[2:])
fmt.Println(a[3:])// doesn't panic - why??
fmt.Println(a[4:])// panics as expected
Why does the following behavior occur:
a := []int{1, 2, 3}
fmt.Println(a[0:])
fmt.Println(a[1:])
fmt.Println(a[2:])
fmt.Println(a[3:])// doesn't panic - why??
fmt.Println(a[4:])// panics as expected
a[3:]
builds an empty slice which, just like an empty array, is a valid and useful object (in all languages, not just in Go).
An empty slice also still points to an underlying array, a position and a capacity and can sometimes be extended:
a := []int{1, 2, 3}
emptySlice := a[1:1]
fmt.Println(emptySlice) // []
notEmpty := emptySlice[0:2]
fmt.Println(notEmpty) // [2 3]
On the other end, a slice with a negative length is inconsistent. It means nothing and thus is forbidden.