Slice within a slice golang

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

Slice within a slice golang

问题

我正在尝试在golang中创建一个切片中的切片,但一直没有成功。这是我的代码片段:

Slice1 := []string{"a","b","c"}
Slice2 := []string{"x","y","z"}
SliceOfSlices := []string{Slice1,Slice2}

http://play.golang.org/p/-ECPRTS0_X

给我报错:cannot use Slice1 (type []string) as type string in array or slice literal

我该如何正确实现这个功能?

英文:

I am trying to make a slice within a slice in golang, but have been unsuccessful. Here is my code snippet:

Slice1 := []string{"a","b","c"}
Slice2 := []string{"x","y","z"}
SliceOfSlices := []string{Slice1,Slice2}

http://play.golang.org/p/-ECPRTS0_X

Gives me the error : cannot use Slice1 (type []string) as type string in array or slice literal

How do I do this correctly?

答案1

得分: 3

你缺少了一对方括号:

SliceOfSlices := [][]string{Slice1, Slice2}
英文:

You're missing a set of square brackets:

SliceOfSlices := [][]string{Slice1, Slice2}

答案2

得分: 3

Slice1Slice2的类型是[]string,所以它们的切片类型将是[][]string

http://play.golang.org/p/FPS5r5qbfO

Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
SliceOfSlices := [][]string{Slice1, Slice2}
英文:

Slice1 and Slice2 are of type []string, so a slice of those will be a [][]string

http://play.golang.org/p/FPS5r5qbfO

Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
SliceOfSlices := [][]string{Slice1, Slice2}

答案3

得分: 0

如上所建议,您需要像以下示例一样添加方括号:

Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
SliceOfSlices := [][]string{Slice1, Slice2}

如果您不知道SliceOfSlices的长度,您也可以使用以下方法:

SliceOfSlices := make([][]string, 0)
Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
Slice3 := []string{"w", "w", "w"}
SliceOfSlices = append(SliceOfSlices, Slice1, Slice2, Slice3)
英文:

As suggested above, you have to add a square brackets like the following example:

Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
SliceOfSlices := [][]string{Slice1, Slice2}

If you do not know the length of SliceOfSlices, you can also use the following approach:

SliceOfSlices := make([][]string, 0)
Slice1 := []string{"a", "b", "c"}
Slice2 := []string{"x", "y", "z"}
Slice3 := []string{"w", "w", "w"}
SliceOfSlices = append(SliceOfSlices, Slice1, Slice2, Slice3)

huangapple
  • 本文由 发表于 2016年3月19日 05:18:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/36094400.html
匿名

发表评论

匿名网友

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

确定