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

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

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?