我的代码:
package main
import (
"fmt"
)
func main() {
a := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
b := a[1:4]
fmt.Println("a:", a)
fmt.Println("b:", b)
// Works fine even though c is indexing past the end of b.
c := b[4:7]
fmt.Println("c:", c)
// This fails with panic: runtime error: index out of range [4] with length 3
// d := b[4]
}
输出:
a: [0 1 2 3 4 5 6 7 8 9]
b: [1 2 3]
c: [5 6 7]
如果我取消注释包含 的行d := b[4],则会导致此错误:
panic: runtime error: index out of range [4] with length 3
我的问题:
为什么b[4:7]即使索引 4 超出b长度为 3 的范围也可以访问,但不能访问b[4]?什么 Go 语言规则解释了这种行为?
30秒到达战场
相关分类