dpb75177
2015-10-14 05:00
浏览 193
已采纳

在Golang中创建数组文字数组

How do I create an array of int arrays in Golang using slice literals?

I've tried

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

and

type Test struct {
   foo [][]iint
}

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

图片转代码服务由CSDN问答提供 功能建议

如何使用切片文字在Golang中创建int数组的数组? < p>我已经尝试过

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

 类型测试结构{
 foo [] [] iint 
} 
 
bar:=测试{  foo:[[1,2,3],[1,2,3]]} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dtpf76658 2015-10-14 05:14
    已采纳

    You almost have the right thing however your syntax for the inner arrays is slightly off, needing curly braces like; test := [][]int{[]int{1,2,3},[]int{1,2,3}} or a slightly more concise version; test := [][]int{{1,2,3},{1,2,3}}

    The expression is called a 'composite literal' and you can read more about them here; https://golang.org/ref/spec#Composite_literals

    But as a basic rule of thumb, if you have nested structures, you have to use the syntax recursively. It's very verbose.

    打赏 评论
  • doujizhong8352 2015-10-14 05:08

    A slice literal is written as []type{<value 1>, <value 2>, ... }. A slice of ints would be []int{1,2,3} and a slice of int slices would be [][]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
    ", sub, sum)
    } 
    
    打赏 评论
  • doukan6564 2015-10-14 06:25

    In some other langauges (Perl, Python, JavaScript), [1,2,3] might be an array literal, but in Go, composite literals use braces, and here, you have to specify the type of the outer slice:

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

    You can run or play with that on the Playground.

    The Go compiler is just tricky enough to figure out that the elements of an [][]int are []int without you saying so on each element. You do have to write out the outer type's name, though.

    打赏 评论
  • doutiaosu2310 2018-09-05 00:41

    Just replace the square brackets with curly braces. In Go, array literals are identified with curly braces.

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

    打赏 评论

相关推荐 更多相似问题