package main
import "fmt"
func main() {
a := make([]int, 5)
printSlice("a", a)
b := make([]int, 0, 5)
printSlice("b", b)
c := b[1:]
printSlice("c", c)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %v\n",
s, len(x), cap(x), x)
}
上面给了我一个越界错误:
a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
panic: runtime error: slice bounds out of range
goroutine 1 [running]:
main.main()
/private/var/folders/q_/53gv6r4s0y5f50v9p26qhs3h00911v/T/compile117.go:10 +0x150
为什么创建 c
slice 的 slice 表达式会导致错误?
最佳答案
简而言之:问题不在于可以等于或大于len()
的下限。 (在 slice 的情况下,上限由 cap()
决定)。问题在于上限:它必须大于或等于下限。由于您没有指定上限,因此默认为 len()
(而不是 cap()
!)这是 0
.和 1
不小于或等于 0
.
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 capacitycap(a)
rather than the length.
由于您正在 slice ,索引在范围内如果:
0 <= low <= high <= cap(a)
所以这一行:
c := b[1:]
无效,因为:
A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.
所以在你的情况下low = 1
和 high = 0
(隐式),不满足:
0 <= low <= high <= cap(a)
例如,以下表达式是有效的:
c := b[1:1] // c len=0 cap=4 []
c := b[1:2] // c len=1 cap=4 [0]
c := b[1:cap(b)] // c len=4 cap=4 [0 0 0 0]
关于go - slice : Out of bounds error in Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33859066/