Fmt Width Padding And Alignment
Control column width, zero padding, and left alignment with printf verbs so tabular CLI output and fixed-width logs line up without manual spacing.
Code
package main
import "fmt"
func main() {
// %9.3f:总宽 9、小数 3 位,右对齐(默认)
fmt.Printf("[%9.3f]\n", 3.14159)
fmt.Printf("[%9.3f]\n", 1234.5)
// %-8s:左对齐(负号),不足右侧补空格
fmt.Printf("[%-8s]\n", "go")
fmt.Printf("[%8s]\n", "go")
// %05d:宽度 5,空位补零——工单号、时间戳的定宽输出
fmt.Printf("[%05d]\n", 42)
// % + d:强制显示正负号,便于对齐差异列
fmt.Printf("[% +d] [% +d]\n", 12, -12)
// 组合:左对齐名称 + 右对齐金额,组成两列报表
rows := []struct {
name string
cents int
}{
{"widget", 199_00},
{"gadget-xl", 4_999_00},
}
for _, r := range rows {
fmt.Printf("%-12s %9.2f\n", r.name, float64(r.cents)/100)
}
}What the code does
All of the logic lives in the function main.
Iteration happens inside for _, r := range rows — everything outside it runs once.
Iteration is driven by for _, r := range rows.
Statements that decide the outcome
for _, r := range rows {
fmt.Printf("%-12s %9.2f\n", r.name, float64(r.cents)/100)
}
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 do you run Fmt Width Padding And Alignment?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.