我的代码:
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超出了长度为3的b
的范围,但访问b[4]
就不行?哪些Go语言规则解释了这种行为?