5

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

1 Answer 1

3

[...]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]
1
  • @LukeMann Not sure though, this was an out of range on a slice: I have edited the answer.
    – VonC
    May 22, 2016 at 2:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.