在 Golang 中创建数组文字数组

如何使用切片文字在 Golang 中创建一个 int 数组数组?


我试过了


test := [][]int{[1,2,3],[1,2,3]}


type Test struct {

   foo [][]int

}


bar := Test{foo: [[1,2,3], [1,2,3]]}


三国纷争
浏览 246回答 3
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但作为基本的经验法则,如果您有嵌套结构,则必须递归地使用语法。它非常冗长。

慕姐4208626

在其他一些语言(Perl、Python、JavaScript)中,[1,2,3]可能是数组字面量,但在 Go 中,复合字面量使用大括号,在这里,您必须指定外部切片的类型:package mainimport "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)}您可以在 Playground 上运行或玩。Go 编译器非常棘手,可以弄清楚 an 的元素[][]int是[]int不是你对每个元素都这么说。不过,您必须写出外部类型的名称。

不负相思意

切片文字写为[]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 {&nbsp; &nbsp; sum := 0&nbsp; &nbsp; for _, num := range group {&nbsp; &nbsp; &nbsp; &nbsp; sum += num&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("The array %+v has a sum of %d\n", sub, sum)}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go