Tabwriter Aligns Table Columns For CLI Output

Print aligned CLI tables with text/tabwriter: tab-separated cells line up in columns once Flush runs, with configurable padding and a chosen pad character.

GoCli Tooling

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"os"
	"text/tabwriter"
)

// aligned table: cells separated by tabs share one column width
func main() {
	// minwidth=0 tabwidth=2 padding=2:列间至少 2 个空格
	writer := tabwriter.NewWriter(os.Stdout, 0, 2, 2, ' ', 0)

	fmt.Fprintln(writer, "SERVICE	REPLICAS	CPU")
	for _, row := range [][3]string{
		{"orders", "3", "12m"},
		{"billing", "1", "250m"},
		{"auth", "9", "80m"},
	} {
		fmt.Fprintf(writer, "%s	%s	%s
", row[0], row[1], row[2])
	}

	if err := writer.Flush(); err != nil {
		panic(err)
	}
}

The snippet, taken apart

Tabwriter Aligns Table Columns For CLI Output is built around the function main.

Repetition is confined to for _, row := range [][3]string — the rest of the file is straight-line. Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

What to watch for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Statements that matter

for _, row := range [][3]string{
{"orders", "3", "12m"},
{"billing", "1", "250m"},
{"auth", "9", "80m"},
} {
fmt.Fprintf(writer, "%s	%s	%s
", row[0], row[1], row[2])
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
Through `panic(err)` — the 1 checkpoints test `err` and abort the run on the first non-nil one.
How do you run Tabwriter Aligns Table Columns For CLI Output?
Run it as a complete program — compile or interpret the file directly; there is nothing to install first.