一个分片只有一个名为list的元素,为什么subslice list [1:]可以工作?

问题描述:

一个切片只有一个名为list的元素,为什么subslice list [1:]可以工作? 例如:

A slice has only one element, named list, why can subslice list[1:] work? For example:

list := []int{1}
fmt.Println(list[1:])
fmt.Println(list[1])

列表中没有索引为1的元素,因此第三行会导致紧急:运行时错误:索引超出范围",但是为什么第二行能正常工作呢?

The list hasn't the element with index 1, so the third line causes "panic: runtime error: index out of range", but why does the second line works well?

好,该语言只是定义这是有效的.

Well, the language simply defines this to be valid.

想想在细分中使用的索引指向元素之间":

Think of the indices used in subslicing as pointing "between" elements:

Slice a Elements:   | 0 | 1 | 2 | 3 | 4 | 5 |
Subslice a[2:]              ^===============
Subslice a[2:4]             ^===========^
Subslice a[6:]                              ^

您的列表[1:]空片的片.

Your list[1:] slices of the empty slice.