简体   繁体   English

如何在golang的另一个切片中使用一个切片?

[英]How to use one slice in another slice in golang?

in this code I want the whole developers slice to be printed in one line.在这段代码中,我希望将整个developers切片打印在一行中。 But here is a problem, after using the loop, the slice is divided in multiple times and the {"first project", ...} is repeating multiple times.但是这里有一个问题,使用循环后,切片被分成多次, {"first project", ...}重复多次。

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)
    }
}

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM