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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.