对于导致恐慌的循环:由于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.

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