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 the keys and values side by side?

In this code, I print the roles, and with every role, I want to write the key attached to it. But I don’t know how to do it. If I write i < 3 in for loop then the three keys are printed six times because the roles variable contains six string values.

package main

import "fmt"

func main() {
    roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"}
    keys := [3]string{"name", "email address", "job role"}
    for _, data := range roles {
        for i := 0; i < 1; i++ {
            fmt.Println("Here is the "+keys[i]+":", data)
        }
    }
}

Given Result

Here is the name: first name
Here is the name: first email
Here is the name: first role
Here is the name: second name
Here is the name: second email
Here is the name: second role

Required 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

Here is the name: first name
Here is the email address: first email
Here is the job role: first role

Here is the name: second name
Here is the email address: second email
Here is the job role: second role

>Solution :

Use the integer mod operator to convert a roles index to a keys index:

roles := []string{"first name", "first email", "first role", "second name", "second email", "second role"}
keys := []string{"name", "email address", "job role"}

// i is index into roles
for i := range roles {
    // j is index into keys
    j := i % len(keys)

    // Print blank line between groups.
    if j == 0 && i > 0 {
        fmt.Println()
    }

    fmt.Printf("Here is the %s: %s\n", keys[j], roles[i])
}

Run the example on the playground.

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