当数组的长度不为null时,请执行"panic:运行时错误:索引超出范围" [英] Go “panic: runtime error: index out of range” when the length of array is not null

查看:142
本文介绍了当数组的长度不为null时,请执行"panic:运行时错误:索引超出范围"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难学习如何在Go中遍历字符串来做一些事情(具体来说,是将单词分隔成包含元音的单词).

I am having a hard time learning how to loop through a string in Go to do some stuff (specifically, to separate words than contain vowels).

我编写了以下代码段: https://play.golang.org/p/zgDtOyq6qf.

I wrote this code snippet: https://play.golang.org/p/zgDtOyq6qf.

这是我在运行时遇到的错误:

Here is the error I’m getting when running it:

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. I cannot figure out how to solve this issue. Can someone please suggest something?

推荐答案

问题是您正在创建长度为0但最大容量为4的切片,但同时您正在尝试为已经创建的切片的第零个索引分配一个值,该切片通常为空.这就是为什么您收到index out of range error.

The issue is that you are creating a slice with length 0, but with a maximum capacity of 4, 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 the index 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

这篇关于当数组的长度不为null时,请执行"panic:运行时错误:索引超出范围"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆