Table of Contents
Question content
Solution
Home Backend Development Golang How to print a list of 2 in Golang?

How to print a list of 2 in Golang?

Feb 11, 2024 pm 02:51 PM
standard library

如何在 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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use absolute value in c++ How to use absolute value in c++ May 06, 2024 pm 06:15 PM

There are two ways to obtain absolute values ​​in C++: 1. Use the built-in function abs() to obtain the absolute value of an integer or floating point type; 2. Use the generic function std::abs() to obtain various supported absolute values. Operates on absolute values ​​of data types.

How to use std:: in c++ How to use std:: in c++ May 09, 2024 am 03:45 AM

std is the namespace in C++ that contains components of the standard library. In order to use std, use the "using namespace std;" statement. Using symbols directly from the std namespace can simplify your code, but is recommended only when needed to avoid namespace pollution.

What does prime mean in c++ What does prime mean in c++ May 07, 2024 pm 11:33 PM

prime is a keyword in C++, indicating the prime number type, which can only be divided by 1 and itself. It is used as a Boolean type to indicate whether the given value is a prime number. If it is a prime number, it is true, otherwise it is false.

How to pop up a window in python How to pop up a window in python May 05, 2024 pm 08:15 PM

There are two ways to create popups in Python: Tkinter: Use the Tkinter library to create Tk or TopLevel widgets. Pyglet: Use the Pyglet library to create Window windows.

What does fabs mean in c++ What does fabs mean in c++ May 08, 2024 am 01:15 AM

The fabs() function is a mathematical function in C++ that calculates the absolute value of a floating point number, removes the negative sign and returns a positive value. It accepts a floating point parameter and returns an absolute value of type double. For example, fabs(-5.5) returns 5.5. This function works with floating point numbers, whose accuracy is affected by the underlying hardware.

What does config mean in java? What does config mean in java? May 07, 2024 am 02:39 AM

Config represents configuration information in Java and is used to adjust application behavior. It is usually stored in external files or databases and can be managed through Java Properties, PropertyResourceBundle, Java Configuration Framework or third-party libraries. Its benefits include decoupling and flexibility. , environmental awareness, manageability, scalability.

_complex usage in c language _complex usage in c language May 08, 2024 pm 01:27 PM

The complex type is used to represent complex numbers in C language, including real and imaginary parts. Its initialization form is complex_number = 3.14 + 2.71i, the real part can be accessed through creal(complex_number), and the imaginary part can be accessed through cimag(complex_number). This type supports common mathematical operations such as addition, subtraction, multiplication, division, and modulo. In addition, a set of functions for working with complex numbers is provided, such as cpow, csqrt, cexp, and csin.

How to calculate absolute value in c++ How to calculate absolute value in c++ May 06, 2024 pm 06:21 PM

There are three ways to find the absolute value in C++: Using the abs() function, you can calculate the absolute value of any type of number. Using the std::abs() function, you can calculate the absolute value of integers, floating point numbers, and complex numbers. Manual calculation of absolute values, suitable for simple integers.

See all articles