Go数组初始化

huangapple go评论95阅读模式
英文:

Go array initialization

问题

希望你从示例中能理解我想做什么。在Go中,我该如何实现这个?

英文:
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

得分: 54

func identityMat4() [16]float64 {
return [...]float64{
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 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)

答案2

得分: 6

如何使用数组初始化器来初始化一个测试表块:

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("结果不正确。期望值:%v。实际值:%v。输入:%v。", table.result, result, table.input)
	}
}
英文:

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

答案3

得分: 3

如果您使用Go语言的惯用语法来编写程序,您将会使用切片。例如,

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))
}
 
输出: [1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1]
英文:

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

package main

import &quot;fmt&quot;

func Identity(n int) []float {
	m := make([]float, n*n)
	for i := 0; i &lt; n; i++ {
		for j := 0; j &lt; 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]

huangapple
  • 本文由 发表于 2011年1月19日 06:24:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/4729736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定