Logo

Programming-Idioms

History of Idiom 26 > diff from v101 to v102

Edit summary for version 102 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 101

2022-08-29, 08:29:23

Version 102

2022-08-29, 09:35:29

Idiom #26 Create a 2-dimensional array

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

Idiom #26 Create a 2-dimensional array

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

Variables
x,m,n
Variables
x,m,n
Extra Keywords
2d
Extra Keywords
2d
Code
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
}
Comments bubble
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.
Demo URL
https://go.dev/play/p/nW0pRQdVW2Z