01AutoMonkey
01AutoMonkey

Reputation: 2809

How do I define a slice of slices containing an int and a slice of strings in Go?

It would look something like this:

[[1,["a", "b", "c"]], [2,["z", "x", "y"]]]

Intuitively I would do something like [][]int[]string, but that's not valid: syntax error: unexpected [, expecting semicolon or newline or }, so how would I do it?

Upvotes: 1

Views: 2142

Answers (1)

Dave C
Dave C

Reputation: 7878

Slice of T: var x []T

Slice of slice of T: var x [][]T

Slice of T1 and T2: You need to put T1 and T2 into a struct.

So for: slice of (slices containing { int and a slice of strings } ). It would usually be something like:

type foo struct {
    i int
    s []string
}
var x [][]foo

But your example looks more like just a []foo:

bar := []foo{
    {1, []string{"a", "b", "c"}},
    {2, []string{"z", "x", "y"}},
}
fmt.Println("bar:", bar)
// bar: [{1 [a b c]} {2 [z x y]}]

Run on Playground (also includes more examples)

Upvotes: 5

Related Questions