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

huangapple go评论92阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2015年3月19日 02:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/29130423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定