Logo

Programming-Idioms

History of Idiom 26 > diff from v31 to v32

Edit summary for version 32 by programming-idioms.org:
[Go] Comment emphasis

Version 31

2016-11-04, 11:53:50

Version 32

2016-11-04, 11:54:44

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.
To same function would 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