dongyinglan8707
2016-05-22 02:11
浏览 95
已采纳

紧急:运行时错误:索引超出范围

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条回答 默认 最新

  • dongpo8250 2016-05-22 02:24
    最佳回答

    [...]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]
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题