doushang2023 2016-08-24 09:05
浏览 128
已采纳

恐慌:运行时错误:索引超出范围,但数组长度不为null

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

  • 写回答

3条回答 默认 最新

  • dopcpc9207 2016-08-24 09:42
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab