英文:
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
Slice1
和Slice2
的类型是[]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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论