Index out of range
yourbasic.org/golang
Why does this program crash?
a := []int{1, 2, 3}
for i := 1; i <= len(a); i++ {
fmt.Println(a[i])
}
panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
../main.go:3 +0xe0
Answer
In the last iteration, i
equals len(a)
which is outside the bounds of a
.
Arrays, slices and strings are indexed starting from zero so the values of a
are found at a[0]
, a[1]
, a[2]
, …, a[len(a)-1]
.
Loop from 0
to len(a)-1
instead.
for i := 0; i < len(a); i++ {
fmt.Println(a[i])
}
Or, better yet, use a range loop.
for _, n := range a {
fmt.Println(n)
}