Aligning text with tabwriter
In certain cases, the output (usually data output) is done via tabbed text, which is formatted in well-arranged cells. This format could be achieved with the text/tabwriter
package. The package provides the Writer
filter, which transforms the text with the tab characters into properly formatted output text.
How to do it...
- Open the console and create the folder
chapter02/recipe05
. - Navigate to the directory.
- Create the
tabwriter.go
file with the following content:
package main import ( "fmt" "os" "text/tabwriter" ) func main() { w := tabwriter.NewWriter(os.Stdout, 15, 0, 1, ' ', tabwriter.AlignRight) fmt.Fprintln(w, "username\tfirstname\tlastname\t") fmt.Fprintln(w, "sohlich\tRadomir\tSohlich\t") fmt.Fprintln(w, "novak\tJohn\tSmith\t") w.Flush() }
- Run the code by executing
go run tabwriter.go
. - See the output in...