Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #26 Create a 2-dimensional array

Declare and initialize a matrix x having m rows and n columns, containing real numbers.

func make2D(m, n int) [][]float64 {
	buf := make([]float64, m*n)

	x := make([][]float64, m)
	for i := range x {
		x[i] = buf[:n:n]
		buf = buf[n:]
	}
	return x
}

This works even when m, n are not compile-time constants.
This code allocates one big slice for the numbers, plus one slice for x itself.
The same function would have to be rewritten, for types other than float64.
const m, n = 3, 4
var x [m][n]float64

m, n must be constant for this syntax to be valid.
Here x is of type [3][4]float64, it is not a slice.
func make2D[T any](m, n int) [][]T {
	buf := make([]T, m*n)

	x := make([][]T, m)
	for i := range x {
		x[i] = buf[:n:n]
		buf = buf[n:]
	}
	return x
}

This generic func works for any type parameter T.
m, n do not need to be compile-time constants.
This code allocates one big slice for the elements, plus one slice for x itself.
X : array (1 .. M, 1 .. N) of Float := (others => (others => 1.0));

New implementation...