Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of array literal in Golang

Tags:

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 [][]int }  bar := Test{foo: [[1,2,3], [1,2,3]]} 
like image 284
praks5432 Avatar asked Oct 14 '15 05:10

praks5432


2 Answers

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.

like image 130
evanmcdonnal Avatar answered Oct 21 '22 10:10

evanmcdonnal


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.

like image 43
twotwotwo Avatar answered Oct 21 '22 10:10

twotwotwo