如何基于传递给数组的长度创建2D数组

问题描述:

func matrix(n int) {
  var result [n][n]int //Does not work
  fmt.Println(result)
}

How to create a 2D array based on the length passed to an array; n is the length of the array.

  func matrix(n int){
 var result [n] [n] int // //  
 fmt.Println(result)
} 
  code>  pre> 
 
 

如何根据传递给数组的长度创建二维数组; n是数组的长度。 p> div>

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.

ArrayType   = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
ElementType = Type .

The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int. The length of array a can be discovered using the built-in function len. The elements can be addressed by integer indices 0 through len(a)-1. Array types are always one-dimensional but may be composed to form multi-dimensional types.


The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int.

The size of an array is fixed at compile-time.


Use a slice instead.

For example,

package main

import "fmt"

func matrix(n int) [][]int {
    m := make([][]int, n)
    for i := range m {
        m[i] = make([]int, n)
    }
    return m
}

func main() {
    fmt.Println(matrix(3))
}

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

Output:

[[0 0 0] [0 0 0] [0 0 0]]

You have to allocate the further dimensions individually, like so:

func matrix(n int) {
    var result = make([][]int, n)
    for i := range result {
        result[i] = make([]int, n)
    }
    fmt.Println(result)
}

With an actual array with fixed dimensions known at compile-time, you can do something like:

var result [5][5]int

but this is not the case you have.