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