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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料