英文:
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 }
}
答案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 "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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论