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

前端 未结 1 645
慢半拍i
慢半拍i 2021-01-29 12:13

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条回答
  • 2021-01-29 13:09

    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:]                              ^
    

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

    0 讨论(0)
提交回复
热议问题