Go array initialization

func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?


Solution 1:

func identityMat4() [16]float64 {
    return [...]float64{
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}

(Click to play)

Solution 2:

If you were writing your program using Go idioms, you would be using slices. For example,

package main

import "fmt"

func Identity(n int) []float {
    m := make([]float, n*n)
    for i := 0; i < n; i++ {
        for j := 0; j < n; j++ {
            if i == j {
                m[i*n+j] = 1.0
            }
        }
    }
    return m
}

func main() {
    fmt.Println(Identity(4))
}

Output: [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1]