创建数组文本的Golang阵列

问题描述 投票:9回答:4

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

我试过了

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

type Test struct {
   foo [][]iint
}

bar := Test{foo: [[1,2,3], [1,2,3]]}
go
4个回答
17
投票

你几乎有正确的事情,但你的内部数组的语法略有偏离,需要花括号像; 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

但作为一个基本的经验法则,如果你有嵌套结构,你必须递归使用语法。它非常冗长。


4
投票

在其他一些语言(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而你没有在每个元素上这样说。但是,您必须写出外部类型的名称。


1
投票

只需用花括号替换方括号即可。在Go中,数组文字用大括号标识。

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


0
投票

切片文字写成[]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)
} 
© www.soinside.com 2019 - 2024. All rights reserved.