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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办