Home > Enterprise >  How to print multiple slices as one slice?
How to print multiple slices as one slice?

Time:09-23

In this Golang code, I have a variable called developers which is equal to two slices. I want them to be equal to one slice as shown in the required result.

Although I could do it by writing it in a single slice like this {"first developer", "second developer"}, but I want to write them separately and print them as one but to be considered as multiple entities like this [[first developer second developer]...]

Given result

[[first developer] [second developer] [first project second project] [third project forth project]]

Required result

[[first developer second developer] [first project second project] [third project forth project]]

Code

package main

import "fmt"

func main() {
    developers := [][]string{
        {"first developer"},
        {"second 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)
}

CodePudding user response:

It looks first you want to "flatten" the developers 2D slice ([][]string). To do that, range over it and append its 1D slice elements to a 1D slice ([]string). Then use this 1D slice as an element of the final data 2D slice.

For example:

developers := [][]string{
    {"first developer"},
    {"second developer"},
}
var devs []string
for _, v := range developers {
    devs = append(devs, v...)
}

data := [][]string{
    devs,
    {"first project", "second project"},
    {"third project", "forth project"},
}
fmt.Println(data)

This will output (try it on the Go Playground):

[[first developer second developer] [first project second project] [third project forth project]]
  • Related