Go panic:运行时错误:索引超出范围,但数组长度不为null [英] Go panic: runtime error: index out of range but length of array is not null
问题描述
我有一个很难学会如何循环通过 Golang
中的字符串做一些东西(单独的单词而不是包含元音)。
我写了这段程式码片段 https:// play .golang.org / p / zgDtOyq6qf
以下是错误:
panic:索引超出范围
goroutine 1 [running]:
panic(0x1045a0,0x1040a010)
/usr/local/go/src/runtime/panic.go:500 + 0x720
main.myFunc(0x114130,0x4,0x0,0x0,0x0,0x3ba3)
/tmp/sandbox960520145/main.go:19 + 0x1a0
main.main()
/ tmp / sandbox960520145 / main.go:10 + 0x40
我在这个论坛中搜索过,由于数组的长度,但不是这里的情况。 Ican't找出如何解决这个。
有人可以建议什么吗?感谢
问题是你正在创建一个长度 0的切片
,但是最大容量为 4
,但是同时您尝试为已创建的切片的零索引分配一个值,该索引通常为空。这是为什么您收到索引超出范围错误
。
result:= make([] string,0,4)
pre>
fmt.Println(len(result))// panic:运行时错误:索引超出范围
您可以更改此代码:
result: make([] string,4)
这意味着容量将与切片长度
fmt.Println(cap(result))// 4
fmt.Println(len(result)) // 4
您可以阅读关于数组 / em>和地图: https:// blog .golang.org / go-slices-usage-and-internals
i am having a hard time learning how to loop through a string in
Golang
to do some stuff(separate words than contain vowels).I wrote this code snippet https://play.golang.org/p/zgDtOyq6qf Here is the error :
panic: runtime error: index out of range goroutine 1 [running]: panic(0x1045a0, 0x1040a010) /usr/local/go/src/runtime/panic.go:500 +0x720 main.myFunc(0x114130, 0x4, 0x0, 0x0, 0x0, 0x3ba3) /tmp/sandbox960520145/main.go:19 +0x1a0 main.main() /tmp/sandbox960520145/main.go:10 +0x40
I searched in this forum and someone said that it's due to the length of the array but it's not the case here. Ican't figure out how to solve this. Can someone please suggest anything? Thanks
解决方案The issue is that you are creating a slice with length
0
, but with a maximum capacity of4
, but at the same time you are trying to allocate already a value to the zeroth index of the slice created, which is normally empty. This is why you are receiving theindex out of range error
.result := make([]string, 0, 4) fmt.Println(len(result)) //panic: runtime error: index out of range
You can change this code with:
result := make([]string, 4)
which means the capacity will be the same length as the slice length.
fmt.Println(cap(result)) // 4 fmt.Println(len(result)) // 4
You can read about arrays, slices and maps here: https://blog.golang.org/go-slices-usage-and-internals
这篇关于Go panic:运行时错误:索引超出范围,但数组长度不为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!