dtqf81594 2018-04-10 16:14
浏览 339
已采纳

对于导致恐慌的循环:由于nil映射或切片导致运行时错误

Hey I am trying to create a simple scalar vector for my program.

I was starting with a simple variable and incrementing it to make it a 32 by 1 size vector matrix.

var x []int
for i := 0; i < 32 ; i++{
    x[i] = i + 1
}

Simple enough but when trying to compile this I get this error.

panic: runtime error: index out of range

goroutine 1 [running]:
main.main()
    /Users/jeanmac/go/src/matrices/main.go:69 +0x7d

Process finished with exit code 2

Not sure why. FYI Line 69 refers to x[i] = i + 1. When trying to assign x[i] I receive the following warning.

Reports indexing of nil map or slice that may lead to runtime panic.

Not sure why this seems to be happening.

  • 写回答

1条回答 默认 最新

  • doutu1939 2018-04-10 16:20
    关注

    Allocate the slice. For example,

    package main
    
    import "fmt"
    
    func main() {
        x := make([]int, 32)
        for i := range x {
            x[i] = i + 1
        }
        fmt.Println(x == nil, len(x), cap(x), x)
    }
    

    Playground: https://play.golang.org/p/UVrUAZHtTw-

    Output:

    false 32 32 [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32]
    

    In your example, you have a zero-value (nil) slice which has length 0. Therefore, x[i] or x[0] is panic: runtime error: index out of range.

    package main
    
    import "fmt"
    
    func main() {
        var x []int
        fmt.Println(x == nil, len(x), cap(x), x)
        for i := 0; i < 32; i++ {
            x[i] = i + 1
        }
    }
    

    Playground: https://play.golang.org/p/3hG5FpV3_dC

    Output:

    true 0 0 []
    panic: runtime error: index out of range
    main.go:9
    

    References:

    A Tour of Go

    The Go Programming Language Specification

    Slice types

    Index expressions

    Making slices, maps and channels

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况