一个分片只有一个名为list的元素,为什么subslice list [1:]可以工作? [英] A slice has only one element, named list, why can subslice list[1:] work?

查看:81
本文介绍了一个分片只有一个名为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.

这篇关于一个分片只有一个名为list的元素,为什么subslice list [1:]可以工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆