【发布时间】:2020-12-01 08:14:30
【问题描述】:
我的代码:
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
我的问题:
为什么即使索引 4 超出了长度为 3 的 b 的范围,但访问 b[4] 却不能访问 b[4:7],仍然可以访问?什么 Go 语言规则解释了这种行为?
【问题讨论】:
-
为什么投反对票?我该怎么做才能使这个问题变得更好?
-
为什么会出现“不可复制或由拼写错误”的原因的近距离投票?我的问题的哪一部分不可重现?
标签: go slice indexoutofboundsexception semantics