Logo

Programming-Idioms

History of Idiom 27 > diff from v15 to v16

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

Version 15

2015-12-30, 17:14:12

Version 16

2015-12-30, 17:26:25

Idiom #27 Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

Idiom #27 Create a 3-dimensional array

Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.

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

	x := make([][][]float64, m)
	for i := range x {
		x[i] = make([][]float64, n)
		for j := range x[i] {
			x[i][j] = buf[:p:p]
			buf = buf[p:]
		}
	}
	return x
}
Comments bubble
This works even when m, n, p are not compile-time constants.
This code allocates one big slice for the numbers, then a few slices for intermediate dimensions.
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/SsCRecCclG