为什么go不报告“切片范围超出范围"?在这种情况下? [英] Why go doesn't report "slice bounds out of range" in this case?
问题描述
以下是要复制的代码:
package main
import "fmt"
func main() {
var v []int
v = append(v,1)
v = append(v,v[1:]...)
fmt.Println("hi", v)
}
v[1]
将报告index out of range
,但v[1:]...
不会,为什么?
v[1]
will report index out of range
, but v[1:]...
won't, why?
推荐答案
这就是spec定义切片表达式的方式
That's how spec defines slice expressions
对于数组或字符串,如果0< =低< =高< = len(a),则索引在范围内,否则它们不在范围内.对于切片,索引的上限是切片容量cap(a)而不是长度.
For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length.
https://golang.org/ref/spec#Slice_expressions
这就是切片的索引表达式的定义方式
And that's how index expressions for slices are defined
如果0< = x<则索引x在范围内. len(a),否则超出范围
the index x is in range if 0 <= x < len(a), otherwise it is out of range
如果x在运行时超出范围,则会发生运行时恐慌
if x is out of range at run time, a run-time panic occurs
https://golang.org/ref/spec#Index_expressions
以您的示例为例:
v[1]
恐慌,因为它属于上述定义的范围(因为1
不符合0 <= x < len(a)
的要求)
v[1]
panics because it's our of range as per the definition above (because 1
does not qualify the 0 <= x < len(a)
reqirement)
v[1:]
运行正常,因为它与v[1:len(v)]
相同并且符合if 0 <= low <= high <= cap(a)
的要求.
v[1:]
runs fine because it's identical to v[1:len(v)]
and fits the if 0 <= low <= high <= cap(a)
requirement.
这篇关于为什么go不报告“切片范围超出范围"?在这种情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!