Go doesn't have generics. For matrices, a similar problem, I have a NewMatrix
function in a matrix.go
file in my snippet
folder. By design, I can simply copy it and do a global change of []int
to another type, for example, []float64
.
You could improve your function by giving w
slices a valid capacity.
For example,
package main
import "fmt"
func NewMatrix(r, c int) [][]int {
a := make([]int, c*r)
m := make([][]int, r)
lo, hi := 0, c
for i := range m {
m[i] = a[lo:hi:hi]
lo, hi = hi, hi+c
}
return m
}
func create2dSlice(w, h int) [][]int {
a := make([]int, w*h)
s := make([][]int, h)
lo, hi := 0, w
for i := range s {
s[i] = a[lo:hi:hi]
lo, hi = hi, hi+w
}
return s
}
func main() {
r, c := 2, 3
m := NewMatrix(r, c)
fmt.Println(m)
w, h := c, r
a := create2dSlice(w, h)
fmt.Println(a)
}
Output:
[[0 0 0] [0 0 0]]
[[0 0 0] [0 0 0]]
The Go Programming Language Specification
Slice expressions
Slice expressions construct a substring or slice from a string, array,
pointer to array, or slice. There are two variants: a simple form that
specifies a low and high bound, and a full form that also specifies a
bound on the capacity.
Full slice expressions
For an array, pointer to array, or slice a (but not a string), the
primary expression
a[low : high : max]
constructs a slice of the same type, and with the same length and
elements as the simple slice expression a[low : high]
. Additionally,
it controls the resulting slice's capacity by setting it to max - low
.