Create an array of array literals in the Golang

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

I tried

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

and

type Test struct {
   foo [][]iint
}

bar := Test{foo: [[1,2,3], [1,2,3]]}
+4
source share
3 answers

You have almost everything right, but your syntax for internal arrays is slightly off; curly braces are needed for this; test := [][]int{[]int{1,2,3},[]int{1,2,3}}or a slightly shorter 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, if you have nested structures, you should use the syntax recursively. This is a lot.

+7
source

langauges (Perl, Python, JavaScript) [1,2,3] , Go, , :

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

.

Go , , [][]int []int, . .

+4

The literal fragment is written as []type{<value 1>, <value 2>, ... }. There will be []int{1,2,3}a slice of ints , and a slice of internal fragments will 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\n", sub, sum)
} 
0
source

Source: https://habr.com/ru/post/1611538/


All Articles