arraysstringgocompiler-errorsstring-length

Go “panic: runtime error: index out of range” when the length of array is not null


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).

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?


Solution

  • 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