简体   繁体   English

如何在Go中定义一个包含int和一个字符串切片的切片?

[英]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? 凭直觉我会做类似[] [] int [] string的操作,但这是无效的: syntax error: unexpected [, expecting semicolon or newline or } ,那么我该怎么做?

Slice of T: var x []T T切片: var x []T

Slice of slice of T: var x [][]T T的切片: var x [][]T

Slice of T1 and T2: You need to put T1 and T2 into a struct. T1和T2的片段:您需要将T1和T2放入一个结构中。

So for: slice of (slices containing { int and a slice of strings } ). 因此,适用于:切片(包含{int和字符串切片}的切片)。 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 : 但是您的示例看起来更像是[]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) 在Playground上运行 (还包括更多示例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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