How to format and print data in a tabular format (table) using fmt in Go?

To format and print data in a tabular format using fmt in Go, you can follow these steps:

  1. Import the fmt package:
import "fmt"
  1. Define the data you want to display in the table. This can be a slice of structs, a slice of slices, or any other suitable data structure.
data := [][]string{ {"John", "Doe", "[email protected]"}, {"Jane", "Smith", "[email protected]"}, {"Bob", "Johnson", "[email protected]"}, }
  1. Determine the maximum width of each column by iterating over the data and finding the length of the longest element in each column.
columnWidths := make([]int, len(data[0])) for _, row := range data { for i, cell := range row { if len(cell) > columnWidths[i] { columnWidths[i] = len(cell) } } }
  1. Iterate over the data and print each row in a tabular format using fmt.Printf and the %*s format specifier to specify the width of each cell.
for _, row := range data { for i, cell := range row { fmt.Printf("%-*s ", columnWidths[i], cell) } fmt.Println() }

Putting it all together, the complete code will look like this:

package main import "fmt" func main() { data := [][]string{ {"John", "Doe", "[email protected]"}, {"Jane", "Smith", "[email protected]"}, {"Bob", "Johnson", "[email protected]"}, } columnWidths := make([]int, len(data[0])) for _, row := range data { for i, cell := range row { if len(cell) > columnWidths[i] { columnWidths[i] = len(cell) } } } for _, row := range data { for i, cell := range row { fmt.Printf("%-*s ", columnWidths[i], cell) } fmt.Println() } }

This code will output the data in a tabular format like this:

John Doe [email protected] Jane Smith [email protected] Bob Johnson [email protected]

You can adjust the formatting by modifying the separator between cells or adding additional formatting options.