Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print multiple slices as one slice?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading