在golang中使用make方法创建2D数组时,我遇到问题“紧急:运行时错误:索引超出范围”

I am new in golang and try to learn with small examples.

So I am trying to create a 2D array and assign a value but I am stuck here can anyone help me. here is my code.

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")

    letters := make([][]string,0,2)
    letters[0][0] = "a"
    letters[0][1] = "b"
    letters[1][0] = "c"
    letters[1][1] = "d"

    fmt.Println(letters)
}

I am getting error when I run this code

panic: runtime error: index out of range


The Go Programming Language Specification

Array types

An array is a numbered sequence of elements of a single type, called the element type. The number of elements is called the length and is never negative.

Slice types

A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array. A slice type denotes the set of all slices of arrays of its element type. The value of an uninitialized slice is nil.

Making slices, maps and channels

The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values.

Appending to and copying slices

The built-in functions append and copy assist in common slice operations. For both functions, the result is independent of whether the memory referenced by the arguments overlaps.

The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S.


In Go, arrays and slices are not the same thing. Your make([][]string,0,2) statement creates a 2D slice. Here is your 2D slice with initial values,

package main

import (
    "fmt"
)

func main() {
    letters := make([][]string, 2)
    letters[0] = append(letters[0], "a", "b")
    letters[1] = append(letters[1], "c", "d")
    fmt.Println(letters)
}

Playground: https://play.golang.org/p/l40xv_7W5h

Output:

[[a b] [c d]]