Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 147 ยท Standard Library

fmt in Depth: Formatting and Scanning

Master Go's fmt package - every Printf verb and flag, width and precision, argument indexes, Stringer, GoStringer and Formatter, Sscanf and Fscan, and aligned tables with text/tabwriter.

You met fmt.Println and fmt.Printf in Printing with fmt. This lesson goes through the whole package: every verb, every flag, what happens when you get a format wrong, how to teach your own types to print themselves, how to read formatted input back with the Scan family, and how to line up columns with text/tabwriter.

Almost all of fmt rests on one idea. A format string contains ordinary text and verbs that start with %. Each verb consumes the next argument and decides how to render it. Everything else, such as width, precision, flags and argument indexes, only adjusts that rendering. Once you know the verbs and the five adjustments, there is nothing else to learn.

The family of print functions

There are three families and three destinations, which gives nine everyday functions:

Destination Plain Add spaces and a newline Formatted
Standard output Print Println Printf
Returned string Sprint Sprintln Sprintf
Any io.Writer Fprint Fprintln Fprintf

There is also Append, Appendln and Appendf, which add the text to a []byte and return it (useful in hot loops to avoid allocating a string). The differences between the plain and the line versions are small but easy to trip over, so run this example:

Go Print, Println, Sprint and friends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first line prints ab1 2c3.5 4. A space appears between 1 and 2, and between 3.5 and 4, because those neighbors are not strings. Because the rule is so odd, prefer Println or Printf for human-readable output. The byte count for hรฉllo is 7, not 6, because the letter รฉ takes two bytes in UTF-8 (see strings and runes).

The verbs

Here is the complete set of everyday verbs. The ones in the first row work for every type, so they are the ones you will use most:

Verb Meaning Example (value โ†’ output)
%v the default format for the value [1 2] โ†’ [1 2]
%+v like %v, but with field names in structs {X:1 Y:2}
%#v Go-syntax representation, for debugging main.Point{X:1, Y:2}
%T the type of the value main.Point
%% a literal percent sign %
%t boolean true
%d integer, base 10 42
%b %o %O integer in binary, octal, octal with 0o prefix 101010 52 0o52
%x %X hexadecimal (lower or upper case); also strings and byte slices ff FF
%c the character for a Unicode code point G
%q quoted string or quoted character "hi\n" 'G'
%U Unicode notation U+0047
%f %F decimal float, default precision 6 3.141590
%e %E scientific notation 1.234568e+03
%g %G the shortest of %e and %f that keeps all information 1e+21
%s string, or anything with an Error or String method hi
%p pointer address (varies between runs) 0xc000012345
Go A tour of the verbs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at the results:

  • %v on User prints <nil> for the nil pointer, and the map as map[a:2 z:1] even though we wrote z first. fmt prints maps sorted by key, which makes map output deterministic (a rare exception to Go's random map order, and only for printing).
  • %#v is the only verb that prints the type and quotes strings, which is why it is the best choice in debug output and test failure messages.
  • %x with a space flag (% x) puts a space between bytes: 68 69.
  • %x works on strings and byte slices, giving the hex of every byte. %s on a []byte prints it as text.

A pointer to a struct at the top level prints as &{...}. A pointer inside a struct or slice prints only its address (like 0xc000012345), and the address changes on every run. If you need to see the pointed-to data of a nested pointer, print it yourself with *u.Boss.

Width, precision and flags

Between the % and the verb you can add, in this order: flags, a width, and a precision that starts with a dot. Width is the minimum number of characters the output takes up. Precision means something different for each type: digits after the point for floats, the maximum characters for strings.

Flag Effect
- left-justify (pad on the right)
+ always print the sign of numbers (+42)
space leave a space for the sign of positive numbers, or put spaces between hex bytes
0 pad numbers with zeros instead of spaces
# alternate format: 0x prefix for hex, 0 for octal, raw string for %q
Go Width, precision and flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Some notes on these results:

  • A negative number with %x prints -2a: Go prints the sign and the magnitude, it does not show two's-complement bits. Use %b or %x on an unsigned type if you want the bit pattern.
  • %08.2f pads with zeros up to width 8, giving 00003.14. Zero padding applies to numbers only, never to strings.
  • %[1]d repeats the first argument several times. Without an index, each verb takes the next unused argument.
  • max is the built-in from Go 1.21, used to find the widest word.

Be careful with float rounding in %.1f: fmt.Printf("%.1f", 2.25) prints 2.2, not 2.3, because 2.25 is stored exactly and Go rounds half to even. For money, store integer cents.

When the format is wrong

fmt never panics on a bad format. It tells you what went wrong right in the output, which makes mistakes visible:

Go What bad formats look like

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You will see %!d(string=hi), 1 %!d(MISSING), 1 followed by %!(EXTRA int=2), %!z(int=1), %!s(int=42) and %!t(int=1). They all share a shape: %!verb(type=value). These bugs are easy to catch before running. go vet checks the arguments of Printf-style calls at build time, and go test runs the most important of these checks automatically. See vet and linting.

Use Printf("%v", x) to print "whatever it is" while exploring, and %+v or %#v while debugging. Switch to specific verbs (%d, %.2f, %q) for output that other people or programs read.

Making your own types print well

fmt looks for a few methods on the value before it falls back on the default rendering. They are checked in this order, and the first one that the value has wins:

  1. Formatter: Format(f fmt.State, verb rune) takes complete control of every verb.
  2. GoStringer: GoString() string is used only for %#v.
  3. error: Error() string is used for %v, %s, %q, %x and %X.
  4. Stringer: String() string is used for the same verbs as error.

You already know the String method from the output lesson. The surprises come from the details:

Go Stringer, GoStringer and Formatter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The details to remember:

  • fmt calls these methods recursively for values nested in slices, maps and struct fields, so [$0.05 $2.50] came out right without extra work. The one exception is an unexported struct field: fmt cannot call methods on those, so it prints their raw contents.
  • With %d, Money printed , since %d is not one of the verbs that use String.
  • With %x, the Stringer is used and the text is hex-encoded: $0.01 becomes 24302e3031. This is a common surprise. If you want hex of a numeric field, print the field.
  • A method with a pointer receiver is only found when you print a pointer. fmt.Println(b) printed {}, while fmt.Println(&b) used the method. The rule is the same as for interfaces and method sets.
  • Never call fmt.Sprintf("%v", m) inside m.String(). It calls String again, which recurses until the stack overflows. Convert to the underlying type first: fmt.Sprintf("%d", int64(m)).

Implementing Formatter is rare in application code, but it is how math/big numbers and some error libraries support their own flags. When you need it, fmt.State gives you Width(), Precision(), Flag(c) and the Write method.

Scanning: reading formatted input

The Scan functions are the mirror image of the Print functions. They parse text into pointers to variables:

Reads from Newlines count as spaces Stops at a newline Uses a format string
a string Sscan Sscanln Sscanf
an io.Reader Fscan Fscanln Fscanf
standard input Scan Scanln Scanf

All of them return the number of items successfully scanned and an error. Always check the error. The next example reads from strings and from standard input (the input is preset in the editor):

Go Sscan, Sscanf and Fscan

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Pay attention to the first Fscanln. The earlier Fscan read 42 3.5 gopher but left the newline that ended that line in the reader. The following Fscanln sees that newline first and fails with unexpected newline and a count of 0. The second Fscanln then reads Ada 36 correctly. Mixing Scan and Scanln on the same input is a classic source of confusion.

A few practical rules:

  • For whole lines of text, use bufio.Scanner or bufio.Reader.ReadString, as shown in user input. Scan splits on spaces, so it cannot read line three here into one string.
  • For competitive-programming style input (many numbers), wrap os.Stdin in a bufio.Reader once and call fmt.Fscan(in, ...). Unbuffered fmt.Scan on os.Stdin is much slower.
  • When parsing a single token, strconv.Atoi, ParseFloat and ParseBool give clearer errors than Sscan.
  • Sscanf is handy for fixed patterns such as "%d-%d-%d" or "#%02x%02x%02x", but it is lenient about whitespace. For complex input use a real parser or regular expressions.

Aligned columns with text/tabwriter

Padding with %-10s works when you know the widest value in advance. The text/tabwriter package works it out for you. Write cells separated by tab characters, and tabwriter aligns each column to the widest cell when you call Flush:

Go Tables with text/tabwriter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first table pads every column to its widest cell plus 2 spaces. The second right-aligns, and the Debug flag draws | between columns, which helps while you are working out the layout. With AlignRight, each cell must end with a tab, which is why the lines end in \t.

Remember that tabwriter buffers: nothing appears until Flush. Forgetting it is the number one reason for "my table prints nothing". For tables with colors or wide Unicode characters, use a dedicated library; tabwriter counts runes, not terminal columns.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fmt.Printf("%d\n", "hi") print?

    fmt never panics on a bad format. It reports the problem inline in the form %!verb(type=value). go vet finds such mistakes before you run the program.
  2. 2. What does fmt.Printf("[%6.2f]", 3.14159) print?

    The width 6 is the minimum total size and the precision 2 means two digits after the point. The 4-character result 3.14 is padded with spaces on the left. Use - to pad on the right or 0 for zeros.
  3. 3. A type has func (c Color) String() string. What does fmt.Printf("%d", c) print for Color(1)?

    String is used for %v, %s, %q, %x and %X, but %d prints the underlying integer.
  4. 4. Which verb prints a value in Go syntax, including its type name?

    %#v prints main.Point{X:1, Y:2}, ready to paste into code. %+v adds field names only, and %T prints just the type.
  5. 5. After fmt.Fscan(in, &x) reads 42 from the line 42\n, what does the next fmt.Fscanln(in, &y) do?

    Fscan stops right after the number and leaves the newline unread. Fscanln then sees the newline before any value and returns an unexpected newline error.

Summary

  • Three families (Print, Println, Printf) times three destinations (stdout, Sprint for strings, Fprint for any io.Writer); Append* writes to a byte slice.
  • Use %v, %+v, %#v and %T for exploring values, and %d, %s, %q, %x, %f, %e, %g, %t, %c, %U for specific output. %% prints a percent sign.
  • A verb can be adjusted with flags (-, +, space, 0, #), a width, a .precision, * to take them from arguments, and [n] to choose which argument to use.
  • Wrong formats never panic. They show up as %!verb(type=value), MISSING or EXTRA, and go vet finds them statically.
  • fmt prints maps sorted by key and calls Format, GoString, Error and String methods recursively. A pointer-receiver String is used only for pointers, and %x on a Stringer hex-encodes the text.
  • The Scan family parses into pointers and returns a count and an error. Share one bufio.Reader, remember that Scan and Scanln treat newlines differently, and use a bufio.Scanner for lines.
  • text/tabwriter aligns columns; call Flush.

Next: Math and Random Numbers covers the math package, seeded random generators and crypto-grade randomness.