在Go语言中,为什么对于容量为1的切片a,a[1:]不会导致索引越界错误?

huangapple go评论136阅读模式
英文:

In Go, why does a[1:] not give an index out of bounds error for a capacity = 1 slice?

问题

为什么以下代码没有出现“切片边界超出范围”错误?

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

这段代码没有出现错误是因为在切片操作中,如果切片的起始索引超过了切片的长度,Go语言会自动将起始索引调整为切片的长度。在这段代码中,切片a的起始索引为1,超过了切片的长度1,但是Go语言会自动将起始索引调整为切片的长度,所以a变成了一个空切片。因此,打印a的结果是一个空切片"[]"。

英文:

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

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

答案1

得分: 5

根据Go语言切片表达式的规范

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

>a[low : high]

>构造一个子字符串或切片。

>...

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

>a[2:] // 等同于 a[2 : len(a)]

>...

>对于数组或字符串,如果 0 <= low <= high <= len(a),则索引在范围内,否则索引超出范围。

在你的情况下,len(a)为1,而a[1:]等同于a[1:1],这意味着它在范围内。

英文:

Because the Go specification for slice expressions states:

>For a string, array, pointer to array, or slice a, the primary expression
>
>a[low : high]
>
>constructs a substring or slice.
>
>...
>
>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:] // same as a[2 : len(a)]
>
>...
>
>For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range.

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

huangapple
  • 本文由 发表于 2017年5月29日 14:35:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/44235969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定