fmt, verbs and a text table
fmt is the package every Go program meets first and most: it prints a value with %v, reads it back with Sscanf, and builds strings that go into logs, CSV files and terminal tables. It sorts out the type of every argument at run time, so a wrong verb is not a compile error: it is a line of text with a complaint in it. The strings lesson covered the bytes; this one covers the presentation.
One value, several verbs
%v prints a value the way a reader expects, %+v adds the field names of a struct, and %#v prints Go syntax that could be pasted back into source. %T prints the type. For numbers, %d is decimal, %x hexadecimal, %b binary and %c a character; %q quotes a string or a rune.
package main
import "fmt"
type user struct {
Name string
Age int
Admin bool
}
func main() {
u := user{Name: "ada", Age: 36, Admin: true}
fmt.Printf("%v\n", u)
fmt.Printf("%+v\n", u)
fmt.Printf("%#v\n", u)
fmt.Printf("%T\n", u)
fmt.Printf("%d %x %b %o %c\n", 255, 255, 255, 255, 255)
fmt.Printf("%f %.2f %e %g\n", 3.14159, 3.14159, 31415.9, 31415.9)
fmt.Printf("%s %q %q\n", "go", "go", 'g')
}
go run verbs.go
{ada 36 true}
{Name:ada Age:36 Admin:true}
main.user{Name:"ada", Age:36, Admin:true}
main.user
255 ff 11111111 377 ÿ
3.141590 3.14 3.141590e+04 31415.9
go "go" 'g'
%#v shows the package-qualified type main.user and the field names, which is why it is the verb for a failing test that prints its input. %g chose the shorter of the fixed and the exponent form, and the rune 'g' came out quoted as 'g', not as 103.
Width, precision and padding
A width comes before the verb, and a minus sign left-aligns: %8s pads on the left, %-8s on the right. For a float the width counts the whole number and the precision after the dot, so %8.2f is eight columns with two decimals. A zero before the width pads with zeros, and %% prints a percent sign.
package main
import "fmt"
func main() {
fmt.Printf("|%8s|%-8s|%8.2f|\n", "right", "left", 3.14159)
fmt.Printf("|%8s|%-8s|%8.2f|\n", "go", "go", 2.5)
fmt.Printf("%05d %+d % d\n", 42, 42, 42)
fmt.Printf("%08.3f %x %X\n", 3.14159, 255, 255)
fmt.Printf("%6.2f%%\n", 12.3456)
}
go run width.go
| right|left | 3.14|
| go|go | 2.50|
00042 +42 42
0003.142 ff FF
12.35%
The two data rows line up because the columns have the same width, not because of tabs. %+d forces a sign and % d reserves a space for it, which is how a column of signed numbers stays aligned. The last line needed %% to print a literal percent after the number.
A table with text/tabwriter
text/tabwriter is the standard library answer to a table that must line up in a terminal: it buffers the lines, measures every column and writes them with the padding the widest cell needs. A tab separates the columns, and Flush writes the result. It is what gofmt does to aligned declarations and what many command-line tools use for their output.
package main
import (
"fmt"
"os"
"text/tabwriter"
)
func main() {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "name\tbytes\trunes")
fmt.Fprintln(w, "hello\t5\t5")
fmt.Fprintln(w, "héllo\t6\t5")
fmt.Fprintln(w, "Привет\t12\t6")
w.Flush()
}
go run table.go
name bytes runes
hello 5 5
héllo 6 5
Привет 12 6
The padding is two spaces here, the fourth argument, and the byte and rune counts line up even though the Cyrillic row is twelve bytes wide. Tabwriter counts bytes, not columns, so a table of wide CJK characters still looks ragged: that is a rendering problem the terminal owns, not one the package can solve.
Sprintf and Fprintf
Sprintf returns a string, Fprintf writes to any io.Writer, and Printf is the special case that writes to standard output. A program that formats a response body, a CSV row or a log line uses the first two and keeps the result away from the terminal until it is ready.
package main
import (
"fmt"
"strings"
)
type row struct {
ID int
Name string
Score float64
}
func main() {
rows := []row{{1, "ada", 91.5}, {2, "grace", 88}, {3, "linus", 77.25}}
var b strings.Builder
for _, r := range rows {
fmt.Fprintf(&b, "%d,%s,%.1f\n", r.ID, r.Name, r.Score)
}
fmt.Print(b.String())
line := fmt.Sprintf("%-4d %-6s %5.1f", rows[0].ID, rows[0].Name, rows[0].Score)
fmt.Printf("formatted: %q\n", line)
}
go run build.go
1,ada,91.5
2,grace,88.0
3,linus,77.2
formatted: "1 ada 91.5"
The CSV rows were built into a strings.Builder and printed in one write, and the formatted line kept its column widths when it was quoted with %q, which is how a test shows the exact spaces it expects.
A verb that does not fit the value
The verb is matched against the argument at run time, so a mismatch is not an error: fmt prints a marked fragment that names the type it got. A log line with %!d(string=...) in it is a bug that a test would have caught, and go vet reports the statically visible cases before the program runs.
package main
import "fmt"
func value() any {
return "seven"
}
func main() {
fmt.Printf("%d\n", value())
fmt.Printf("%s\n", value())
format := "%d items"
fmt.Println(format, 5)
}
go run badverb.go
%!d(string=seven)
seven
%d items 5
fmt.Println does not interpret verbs at all, so the third line printed the percent sign literally. That is the most common formatting bug: a Printf replaced by a Println and a format string left in place.
Exercises
- Print a table of three products with names, prices and quantities, aligned with text/tabwriter and with a total row.
- Format a duration of 3725 seconds as 1h 02m 05s with Sprintf. Which widths keep the minutes and seconds two digits?
- Run go vet on a program with Printf("%d", "x"). What does it report, and why did the program still compile?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which verb prints a struct with its field names?
Answer
%+v
%v prints the values, %+v adds the field names, %#v prints Go syntax with the type.
-
What does the second line of this program print?
package main import "fmt" type user struct { Name string Age int Admin bool } func main() { u := user{Name: "ada", Age: 36, Admin: true} fmt.Printf("%v\n", u) fmt.Printf("%+v\n", u) fmt.Printf("%#v\n", u) fmt.Printf("%T\n", u) fmt.Printf("%d %x %b %o %c\n", 255, 255, 255, 255, 255) fmt.Printf("%f %.2f %e %g\n", 3.14159, 3.14159, 31415.9, 31415.9) fmt.Printf("%s %q %q\n", "go", "go", 'g') }Answer
{ada 36 true} / {Name:ada Age:36 Admin:true} / main.user{Name:"ada", Age:36, Admin:true} / main.user / 255 ff 11111111 377 ÿ / 3.141590 3.14 3.141590e+04 31415.9 / go "go" 'g'
%+v adds the field names to the struct printout.
-
What does %8.2f do with 3.14159?
Answer
Prints it in eight columns with two decimals
The width is the whole field, the precision follows the dot, so the output is ' 3.14'.
-
What does the first line of this program print?
package main import "fmt" func main() { fmt.Printf("|%8s|%-8s|%8.2f|\n", "right", "left", 3.14159) fmt.Printf("|%8s|%-8s|%8.2f|\n", "go", "go", 2.5) fmt.Printf("%05d %+d % d\n", 42, 42, 42) fmt.Printf("%08.3f %x %X\n", 3.14159, 255, 255) fmt.Printf("%6.2f%%\n", 12.3456) }Answer
| right|left | 3.14| / | go|go | 2.50| / 00042 +42 42 / 0003.142 ff FF / 12.35%
%8s pads the left, %-8s pads the right, and %8.2f is eight columns with two decimals.
-
What does text/tabwriter need before it writes anything?
Answer
A Flush call
Tabwriter buffers the rows to measure the columns, so Flush is what writes them.
-
What does this program print?
package main import ( "fmt" "os" "text/tabwriter" ) func main() { w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintln(w, "name\tbytes\trunes") fmt.Fprintln(w, "hello\t5\t5") fmt.Fprintln(w, "héllo\t6\t5") fmt.Fprintln(w, "Привет\t12\t6") w.Flush() }Answer
name bytes runes / hello 5 5 / héllo 6 5 / Привет 12 6
Tabwriter replaces the tabs with padding wide enough for each column.
-
What does the last line of this program print?
package main import ( "fmt" "strings" ) type row struct { ID int Name string Score float64 } func main() { rows := []row{{1, "ada", 91.5}, {2, "grace", 88}, {3, "linus", 77.25}} var b strings.Builder for _, r := range rows { fmt.Fprintf(&b, "%d,%s,%.1f\n", r.ID, r.Name, r.Score) } fmt.Print(b.String()) line := fmt.Sprintf("%-4d %-6s %5.1f", rows[0].ID, rows[0].Name, rows[0].Score) fmt.Printf("formatted: %q\n", line) }Answer
1,ada,91.5 / 2,grace,88.0 / 3,linus,77.2 / formatted: "1 ada 91.5"
%-4d and %-6s pad to the right and %5.1f pads the score to five columns.
-
What does this program print?
package main import "fmt" func value() any { return "seven" } func main() { fmt.Printf("%d\n", value()) fmt.Printf("%s\n", value()) format := "%d items" fmt.Println(format, 5) }Answer
%!d(string=seven) / seven / %d items 5
Printf marks the mismatch, and Println prints its arguments literally.
-
Why does a wrong verb compile?
Answer
Printf takes ...any, so the types are checked at run time
Variadic any arguments hide the types from the compiler; vet catches the constant cases.
-
Which verb prints a string with quotes around it?
Answer
%q
%q quotes a string or a rune, escaping what needs escaping, which is what a test wants to show.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev