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
The issue is that you are creating a slice with length
0
, but with a maximum capacity of4
, 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 theindex out of range error
.You can change this code with:
which means the capacity will be the same length as the slice length.
You can read about arrays, slices and maps here: https://blog.golang.org/go-slices-usage-and-internals
Index out of range error is appearing because you are not initializing the
result
array with sufficient length.In
myFunc
, you have:This creates a slice of strings which has an underlying array of length 4, but since you have declared slice length to be 0, none of the elements from underlying array are accessible to the slice. So even
result[0]
is out of range of the available indices.To fix this, simply supply a sufficiently large length parameter to
make
:You can read more about how slices operate here.
First let's explain:
The make built-in function allocates and initializes an object of type
[]string
call itSlice
ofstring
Slice internals:
So
result := make([]string, 0, 4)
allocates and initializes an object of type[]string
withlength = 0
andcapacity = 4
.And
result := make([]string, 4, 4)
allocates and initializes an object of type[]string
withlength = 4
andcapacity = 4
, which is equal toresult := make([]string, 4)
.Now what is the difference between
result := make([]string, 0, 4)
andresult := make([]string, 4)
:With
result := make([]string, 0, 4)
the underlying array of this Slice is empty meaning usingresult[0]
will panic: runtime error: index out of range.With
result := make([]string, 4)
the underlying array of this Slice has 4string
elements, meaning usingresult[0]
,result[1]
,result[2]
,result[3]
is OK:output:
And
result := make([]string, 4)
is equal toresult := []string{"", "", "", ""}
meaning this code:output is the same as above code:
Now in your code inside function
myFunc
afterresult := make([]string, 0, 4)
, you may useappend
, like this working code (The Go Playground):You may simplify that code, like this working code (The Go Playground):