How to align text and numbers in formatted output with fmt in Go?

To align text and numbers in formatted output using the fmt package in Go, you can utilize the strconv.Itoa() function to convert numbers to strings and then use strings.Repeat() to add appropriate spacing. Here's an example:

package main import ( "fmt" "strconv" "strings" ) type Item struct { Name string Price int } func main() { items := []Item{ {"Apple", 10}, {"Banana", 20}, {"Orange", 30}, } fmt.Println("Item\t\tPrice") fmt.Println(strings.Repeat("-", 20)) // Line Separator for _, item := range items { // Right-align the item name with a tab separator name := item.Name + strings.Repeat(" ", 16-len(item.Name)) // Left-align the price using strconv.Itoa() price := strconv.Itoa(item.Price) fmt.Println(name + "\t" + price) } }

In the example above, the output will be formatted with the item names right-aligned and the prices left-aligned. The strings.Repeat() function is used to add whitespace in order to align the text and numbers properly.

Output:

Item Price -------------------- Apple 10 Banana 20 Orange 30

By adjusting the number of spaces added, you can control the alignment as per your requirements.