To format and print data in a tabular format using fmt in Go, you can follow these steps:
fmt
package:import "fmt"
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)
}
}
}
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.