doushang2023 2016-08-24 09:05
浏览 128


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 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
    /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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?