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 //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.
The Go Programming Language Specification
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]]