英文:
How do I define a slice of slices containing an int and a slice of strings in Go?
问题
它看起来会像这样:
[[1,["a", "b", "c"]], [2,["z", "x", "y"]]]
直观地,我会尝试使用[][]int[]string
这样的语法,但这是无效的:语法错误:意外的"[", 期望分号、换行符或"}"
,那么我应该如何做呢?
英文:
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?
答案1
得分: 5
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 } ).
It would usually be something like:
所以对于:包含{int和字符串切片}的切片。
通常会是这样的:
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]}]
在Playground上运行(还包括更多示例)
英文:
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]}]
<kbd>Run on Playground</kbd> (also includes more examples)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论