【问题标题】:For Loop causing panic: runtime error due to nil map or sliceFor Loop 导致恐慌:由于 nil map 或 slice 导致运行时错误
【发布时间】:2018-04-10 16:14:07
【问题描述】:

嘿,我正在尝试为我的程序创建一个简单的标量向量。

我从一个简单的变量开始并将其递增以使其成为 32 x 1 大小的向量矩阵。

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

很简单,但是在尝试编译时出现此错误。

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

不知道为什么。仅供参考,第 69 行指的是x[i] = i + 1。 尝试分配 x[i] 时,我收到以下警告。

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

不知道为什么会出现这种情况。

【问题讨论】:

标签: arrays for-loop go indexing


【解决方案1】:

分配切片。例如,

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)
}

游乐场:https://play.golang.org/p/UVrUAZHtTw-

输出:

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]

在您的示例中,您有一个长度为 0 的零值 (nil) 切片。因此,x[i]x[0]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
    }
}

游乐场:https://play.golang.org/p/3hG5FpV3_dC

输出:

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

参考资料:

A Tour of Go

The Go Programming Language Specification

Slice types

Index expressions

Making slices, maps and channels

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2018-03-21
    相关资源
    最近更新 更多