Home > Enterprise >  How to print the keys and values side by side?
How to print the keys and values side by side?

Time:08-31

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

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

CodePudding user response:

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.

  • Related