Go array initialization

前端 未结 4 1839
面向向阳花
面向向阳花 2021-02-05 00:30
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

相关标签:
4条回答
  • 2021-02-05 00:34
    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)

    0 讨论(0)
  • 2021-02-05 00:34

    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]
    
    0 讨论(0)
  • 2021-02-05 00:46

    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)
        }
    }
    
    0 讨论(0)
  • 2021-02-05 00:57
    s := []int{5, 2, 6, 3, 1, 4} // unsorted
    sort.Ints(s)
    fmt.Println(s)
    
    0 讨论(0)
提交回复
热议问题