简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM