切片索引大于长度且小于容量会产生错误
以下代码在运行时出现错误。
package main
import fmt "fmt"
func main(){
type b []int
var k = make([]b, 5, 10)
fmt.Printf("%d\n",k[8])
fmt.Printf("%d", len(k))
}
错误如下。
panic: runtime error: index out of range
runtime.panic+0x9e /go/src/pkg/runtime/proc.c:1060
runtime.panic(0x453b00, 0x300203f0)
runtime.panicstring+0x94 /go/src/pkg/runtime/runtime.c:116
runtime.panicstring(0x4af6c6, 0xc)
runtime.panicindex+0x26 /go/src/pkg/runtime/runtime.c:73
runtime.panicindex()
main.main+0x8d C:/GOEXCE~1/basics/DATATY~1/slice.go:9
main.main()
runtime.mainstart+0xf 386/asm.s:93
runtime.mainstart()
runtime.goexit /go/src/pkg/runtime/proc.c:178
runtime.goexit()
----- goroutine created by -----
_rt0_386+0xbf 386/asm.s:80
如果打印 k[0]
或 k[1]
,则运行正常。您能否解释一下容量对于切片到底意味着什么?
Following code gives a error at runtime.
package main
import fmt "fmt"
func main(){
type b []int
var k = make([]b, 5, 10)
fmt.Printf("%d\n",k[8])
fmt.Printf("%d", len(k))
}
Error is as follows.
panic: runtime error: index out of range
runtime.panic+0x9e /go/src/pkg/runtime/proc.c:1060
runtime.panic(0x453b00, 0x300203f0)
runtime.panicstring+0x94 /go/src/pkg/runtime/runtime.c:116
runtime.panicstring(0x4af6c6, 0xc)
runtime.panicindex+0x26 /go/src/pkg/runtime/runtime.c:73
runtime.panicindex()
main.main+0x8d C:/GOEXCE~1/basics/DATATY~1/slice.go:9
main.main()
runtime.mainstart+0xf 386/asm.s:93
runtime.mainstart()
runtime.goexit /go/src/pkg/runtime/proc.c:178
runtime.goexit()
----- goroutine created by -----
_rt0_386+0xbf 386/asm.s:80
While if k[0]
or k[1]
is printed, it runs fine. Can you please explain what exactly capacity means for slices.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只是简单地建立索引,因此索引必须小于长度。 Go 规范的相关部分 指出
但是,如果您要“切片”(例如
a[6:9]
),那么它将适用于大于长度但在容量范围内的索引。You are simply indexing, so the index must be less than the length. The relevant section of the Go specification says that
However, if you were "slicing" (e.g.
a[6:9]
), then it would work with indexes that are greater than the length but within the capacity.等于
不同的是,当使用
var slice = make([]b, 5, 10)
时,无法访问slice下的
。array
slice := array[:5]
表示slice
的第一个元素是array[0]
并且slice< 的长度/code> 是 5,这意味着
slice[0] == array[0], slice[1] == array[1], ... slice[4] == array[4]
。因为你只能访问小于长度的索引(这意味着0 <=索引<长度
)。slice
的长度为5,array
的长度为10,因此可以访问array[8]
(0<=8<10 ) 但无法访问slice[8]
(8>5)。完整示例:
参考
is equal to
The difference is that when you use
var slice = make([]b, 5, 10)
, you can't access thearray
underslice
. Theslice := array[:5]
means the first element ofslice
isarray[0]
and the length ofslice
is 5, which meansslice[0] == array[0], slice[1] == array[1], ... slice[4] == array[4]
. Because you can only access the index that is less than the length(which means0 <= index < length
). The length ofslice
is 5 and the length ofarray
is 10, so you can accessarray[8]
(0<=8<10) but can't accessslice[8]
(8>5).Full sample:
Reference