53
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?

1
  • Why is your matrix a one-dimensional array? Go supports multi-dimensional arrays / slices - wouldn't these be a better fit for the problem? (golang.org/ref/spec#Array_types) Commented Dec 9, 2012 at 15:05

3 Answers 3

58
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)

Sign up to request clarification or add additional context in comments.

3 Comments

You are not returning an identity matrix.
also you can write return [16]float64
Upvoted for use of "three dots". Never knew that! Go lang is a simple language but so much small details to learn!
7

How to use an array initializer to initialize a test table block:

tables := []struct {
    input []string
    result string
} {
    {[]string{"one ", " two", " three "}, "onetwothree"},
    {[]string{" three", "four ", " five "}, "threefourfive"},
}

for _, table := range tables {
    result := StrTrimConcat(table.input...)

    if result != table.result {
        t.Errorf("Result was incorrect. Expected: %v. Got: %v. Input: %v.", table.result, result, table.input)
    }
}

Comments

3

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]

2 Comments

See blog.golang.org/2011/01/go-slices-usage-and-internals.html for the difference between arrays and slices.
The official Go blog now specifically points out transformation matrices as one of the few good use cases for using arrays directly: "Arrays have their place — they are a good representation of a transformation matrix for instance — but their most common purpose in Go is to hold storage for a slice."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.