How to print a list of 2 in Golang?

WBOY
Release: 2024-02-11 14:51:08
forward
980 people have browsed it

如何在 Golang 中打印 2 列表?

php editor Baicao will show you how to print 2 lists in Golang. In Golang, we can use the Println function in the fmt package to print the list. First, we need to define and initialize the two lists separately, and then use the Println function to print them out. By using a loop and an index variable, we can iterate through the elements of the list one by one and print them out. In this way, we can easily print out the contents of 2 lists in Golang.

Question content

I am a little troubled by this problem. My idea is to have a function that prints two columns. The first one is for keys, which has a fixed width. The second is the value, which may be a very long string whose width depends on the current width of the terminal.

An example of what I want:

key1                                  value1value1value1value1
key2                                  value2value2value2value2value2value2value2value2value2value2value2
                                      value2value2value2value2value2value2value2value2value2value2value2
                                      value2value2value2value2value2value2
Copy after login

The best I've achieved so far is using lipgloss to set a fixed width for the first column.

func printmetadata(metadata map[string]string, color string) {
    style := lipgloss.newstyle().width(32).foreground(lipgloss.color(color))
    for k, v := range metadata {
        fmt.println(style.render(k) + v)
    }
}
Copy after login

The result is similar to:

Key1                                  Value1Value1Value1Value1
Key2                                  Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2
Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2Value2
Copy after login

So, how do I format a string the way I want? I can use both the standard library and external libraries, so any suggestions are welcome.

Solution

I created a function for this. This function takes two parameters, the first is a mapping variable for the column, and the second is how many characters to fill each row with. It just changes the value content of the key with spaces into a new variable and then prints the key value. But if you have works with unmodified values, you can use unmodified variables.

package main

import (
    "fmt"
    "errors"
    "strings"
    "sort"
)

func main() {
    a := map[string]string{
    "key1": strings.repeat("value1", 50), 
    "key2": strings.repeat("value2", 50), 
    "key3": strings.repeat("value3", 50),
    }
    
    err := columner(a, 30)
    
    if err != nil {
        fmt.println(err)
    }
    
}

func columner(m map[string]string, charamount int) error{

    var keys []string
    
    var keylens []int
    
    // to avoid index panics and gathering keys for later usage
    for key, value := range m {
        if charamount > len(value) || charamount < 1{
            return errors.new("error: charamount neither be greather than length of key's value nor below 1")
        }
        keys = append(keys, key)
        keylens = append(keylens, len(key))
    }

    sort.ints(keylens)
    
    for i := 0; i < len(keys); i++ {
        
        // for storing updated value of key
        var value2 string
        
        value := m[keys[i]]
        // will used while extracting substring of key's value as first index
        firsti := 0
        
        // last index for extract substring from key's value. the len of substring will be same as charamount
        charamount2 := charamount
        
        // will be used to advance next substring of key's value
        advance := charamount2
        
        // spaces between between key and value 
        // key       value
        spacing := strings.repeat(" ", 20 + (keylens[0] - len(keys[i])))
        
        // var for adjusting spaces of gap between key and value of next line
        // key        value
        //          value
        // to
        // key        value
        //            value
        spacingu := spacing + strings.repeat(" ", len(keys[i]) + 1)
        
        // this loop will be run as long as there is no substring left which exceed next line
        for j := 0; j < len(value); j += advance {
            
            // adjusting spaces of gap between key and value of next line
            if j > 0 {
                spacing = spacingu
            }
            
            // add space between key and value, then extract substring, then add spaces to the next line of the
            // next substring of key's value
            value2 += spacing + value[firsti:charamount2] + "\n"
            
            // finish loop when there is no substring that can be exceed to next line
            if ((len(value) - charamount2) < advance) || ((len(value) - charamount2) == advance) {
                break
            }
    
            // changing first index to start index of next substring of key's value
            firsti = charamount2
            
            // advancing to next substring of key's value
            charamount2 += advance
        }   
        
        // add last remaining substring of key's value to variable which will be show as formatted.
        value2 += spacing + value[charamount2:]

        // show formatted key and value
        fmt.println(keys[i], value2, "\n")
        
    }
    
    return nil
}
Copy after login

This is a sample output:

Key1                     Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1
                         Value1Value1Value1Value1Value1 

Key2                     Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2
                         Value2Value2Value2Value2Value2 

Key3                     Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
                         Value3Value3Value3Value3Value3
Copy after login

But please note this, the order of keys and values ​​may be different on each execution, because the map type is unordered when printing in a for loop with key, value pairs.

The above is the detailed content of How to print a list of 2 in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!