Logo

Programming-Idioms

History of Idiom 26 > diff from v53 to v54

Edit summary for version 54 by programming-idioms.org:
[Go] Fix comment

Version 53

2019-03-08, 10:10:46

Version 54

2019-04-06, 14:08:34

Idiom #26 Create a 2-dimensional array

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

Illustration

Idiom #26 Create a 2-dimensional array

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

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