英文:
How to use one slice in another slice in golang?
问题
在这段代码中,我希望整个developers
切片在一行中打印出来。但是问题在于,在使用循环之后,切片被分成多个部分,并且{"first project", ...}
多次重复。
期望的结果
[[first developer second developer third developer] [forth developer fifth developer sixth developer] [first project second project third project forth project]]
给定的结果
[[first developer second developer third developer] [first project second project third project forth project]]
[[forth developer fifth developer sixth developer] [first project second project third project forth project]]
代码
package main
import "fmt"
func main() {
developers := [][]string{
{"first developer", "second developer", "third developer"},
{"forth developer", "fifth developer", "sixth developer"},
}
for i := 0; i < 2; i++ {
data := [][]string{developers[i], {"first project", "second project", "third project", "forth project"}}
fmt.Println(data)
}
}
英文:
in this code I want the whole developers
slice to be printed in one line. But here is a problem, after using the loop, the slice is divided in multiple times and the {"first project", ...}
is repeating multiple times.
Required result
[[first developer second developer third developer] [forth developer fifth developer sixth developer] [first project second project third project forth project]]
Given result
[[first developer second developer third developer] [first project second project third project forth project]]
[[forth developer fifth developer sixth developer] [first project second project third project forth project]]
Code
package main
import "fmt"
func main() {
developers := [][]string{
{"first developer", "second developer", "third developer"},
{"forth developer", "fifth developer", "sixth developer"},
}
for i := 0; i < 2; i++ {
data := [][]string{developers[i], {"first project", "second project", "third project", "forth project"}}
fmt.Println(data)
}
}
答案1
得分: 1
请尝试以下代码:
package main
import "fmt"
func main() {
developers := [][]string{
{"第一个开发者", "第二个开发者", "第三个开发者"},
{"第四个开发者", "第五个开发者", "第六个开发者"},
}
var data []string
for i := 0; i < 2; i++ {
data = append(data, developers[i]...)
}
data = append(data, []string{"第一个项目", "第二个项目", "第三个项目", "第四个项目"}...)
fmt.Println(data)
}
输出结果:
[第一个开发者 第二个开发者 第三个开发者 第四个开发者 第五个开发者 第六个开发者 第一个项目 第二个项目 第三个项目 第四个项目]
英文:
Please Try the below one
package main
import "fmt"
func main() {
developers := [][]string{
{"first developer", "second developer", "third developer"},
{"forth developer", "fifth developer", "sixth developer"},
}
var data []string
for i := 0; i < 2; i++ {
data = append(data, developers[i]...)
}
data = append(data, []string{"first project", "second project", "third project", "forth project"}...)
fmt.Println(data)
}
Output:
-------
[first developer second developer third developer forth developer fifth developer sixth developer first project second project third project forth project]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论