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

后端 未结 3 1321
孤街浪徒
孤街浪徒 2021-01-03 03:37

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:

3条回答
  •  抹茶落季
    2021-01-03 04:22

    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

提交回复
热议问题