Article
columnize — format text into columns in Go
Columnize is a little Go package that formats strings with separators into columns.
Here's an example:
package main
import (
"fmt"
"github.com/ryanuber/columnize"
)
func main() {
lines := []string{
"Name | Type | Country | ABV",
"Krombacher Pils | Pilsener | Germany | 4.8%",
"Paulaner Hell | Helles | Germany | 4.9%",
"Kozel Černý | Dunkel | Czech Republic | 3.8%",
}
fmt.Println(columnize.SimpleFormat(lines))
}
Running this program will produce the following output:
Name Type Country ABV
Krombacher Pils Pilsener Germany 4.8%
Paulaner Hell Helles Germany 4.9%
Kozel Černý Dunkel Czech Republic 3.8%
As you can see, it splits string parts separated with |
into nicely aligned columns.
You can customize the columnizer by creating a Config
and changing its properties:
config := columnize.DefaultConfig()
config.Delim = "|"
config.Glue = " "
config.Prefix = ""
Instead of SimpleFormat
, which uses the default config, call Format
, passing it a slice of strings to format and the config you created:
Format(input []string, config *Config) string
That's it! This package is really easy to use.