如何使用切片文字在Golang中创建一个int数组数组?
我试过了
test := [][]int{[1,2,3],[1,2,3]}
和
type Test struct {
foo [][]iint
}
bar := Test{foo: [[1,2,3], [1,2,3]]}
你几乎有正确的事情,但你的内部数组的语法略有偏离,需要花括号像; test := [][]int{[]int{1,2,3},[]int{1,2,3}}
或稍微简洁的版本; test := [][]int{{1,2,3},{1,2,3}}
该表达式称为“复合文字”,您可以在这里阅读更多关于它们的信息; https://golang.org/ref/spec#Composite_literals
但作为一个基本的经验法则,如果你有嵌套结构,你必须递归使用语法。它非常冗长。
在其他一些语言(Perl,Python,JavaScript)中,[1,2,3]
可能是一个数组文字,但在Go中,composite literals使用大括号,在这里,您必须指定外部切片的类型:
package main
import "fmt"
type T struct{ foo [][]int }
func main() {
a := [][]int{{1, 2, 3}, {4, 5, 6}}
b := T{foo: [][]int{{1, 2, 3}, {4, 5, 6}}}
fmt.Println(a, b)
}
你可以run or play with that on the Playground。
Go编译器很难弄清楚[][]int
的元素是[]int
而你没有在每个元素上这样说。但是,您必须写出外部类型的名称。
只需用花括号替换方括号即可。在Go中,数组文字用大括号标识。
test := [][]int{{1,2,3},{1,2,3}}
切片文字写成[]type{<value 1>, <value 2>, ... }
。一片int将是[]int{1,2,3}
,一片int切片将是[][]int{[]int{1,2,3},[]int{4,5,6}}
。
groups := [][]int{[]int{1,2,3},[]int{4,5,6}}
for _, group := range groups {
sum := 0
for _, num := range group {
sum += num
}
fmt.Printf("The array %+v has a sum of %d\n", sub, sum)
}