Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Panic: runtime error: index out of range

Tags:

go

Sorry if this seems pretty basic but why am I getting this error? I dont see any slices/arrays out of range.

package main

import "fmt"

func main(){
    s:= [...]int{1,2,3}
    rev(s[:])
    fmt.Println(s)
}

func rev(input []int) []int {
    var j int
    l:=len(input)-1
    for i:=0; i<l;i++ {
        j= input[len(input)-i]
        input=append(input, j)
        i++
    }
    return input[:l]
}

Thanks

like image 553
Luke Mann Avatar asked Oct 19 '22 09:10

Luke Mann


1 Answers

[...]int{1,2,3} is not a slice. It is an array of capacity 3.
See "golang-101-hacks: Array"

If you try to append a fourth element... that will be out of range.

But here s[:] transforms it into a slice.

The actual 'index out of range' comes from input[len(input)-i] which, with i=0, means input[len(input)]: out of range.

This would work better (playground) (no out of range)

The final fmt.Println(s) was still print the original array, not the return of rev() (which is ignored).
This prints the "expected" result (using append, so mutating and adding to the slice):

package main

import "fmt"

func main() {
    s := [...]int{1, 2, 3}
    t := rev(s[:])
    fmt.Println(s)
    fmt.Println(t)
}

func rev(input []int) []int {
    var j int
    l := len(input) - 1
    for i := 0; i <= l; i++ {
        j = input[l-i]
        input = append(input, j)
    }
    return input
}

Result:

[1 2 3]
[1 2 3 3 2 1]

This (playground) would actually reverse the slice:

var j int
var res []int
l := len(input) - 1
for i := 0; i <= l; i++ {
    j = input[l-i]
    res = append(res, j)
}
return res

Result:

[1 2 3]
[3 2 1]
like image 187
VonC Avatar answered Oct 21 '22 06:10

VonC