Logo

Programming-Idioms

History of Idiom 26 > diff from v16 to v17

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

Version 16

2015-12-30, 17:46:26

Version 17

2015-12-30, 17:50:58

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.

Code
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
}
Comments bubble
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.
To same function would be rewritten, for types other than float64.
Doc URL
https://golang.org/doc/effective_go.html#two_dimensional_slices
Demo URL
http://play.golang.org/p/hURXPWWziq