在Go中,为什么对于容量= 1片,a [1:]为什么不给出超出范围的索引错误? [英] In Go, why does a[1:] not give an index out of bounds error for a capacity = 1 slice?

查看:52
本文介绍了在Go中,为什么对于容量= 1片,a [1:]为什么不给出超出范围的索引错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下代码 not 不会给出切片边界超出范围"错误?

Why does the following code not give a "slice bounds out of range" error?

a := []int{0}
a = a[1:]
fmt.Println(a) // []

推荐答案

因为切片表达式的Go规范状态:

对于字符串,数组,指向数组的指针或切片a,主表达式

For a string, array, pointer to array, or slice a, the primary expression

a [low:high]

a[low : high]

构造一个子字符串或切片.

constructs a substring or slice.

...

为方便起见,任何索引都可以省略.缺少的低索引默认为零;默认值为0.缺少的高索引默认为切片操作数的长度:

For convenience, any of the indices may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand:

a [2:]//与a [2:len(a)]

a[2:] // same as a[2 : len(a)]

...

对于数组或字符串,如果0< =低< =高< = len(a),则索引在范围内,否则它们不在范围内.

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range.

在您的情况下, len(a)为1,而 a [1:] a [1:1] ,这表示它在范围内.

In your case, len(a) is 1, and a[1:] is the same as a[1:1], which means it is within range.

这篇关于在Go中,为什么对于容量= 1片,a [1:]为什么不给出超出范围的索引错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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