Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 147 ยท Getting Started

Printing with fmt

Master printing in Go with fmt - Println, Print, Printf, Sprintf and Fprintf, every common verb (%v %+v %#v %T %d %s %q %x %f), width, precision, flags and os.Stderr.

You will print values constantly while learning Go, and in real programs you will format messages, log lines and reports. The standard fmt package (pronounced "fumpt" by some, "eff-em-tee" by most) does all of it. It follows a simple idea: a family of functions that differ in where the text goes and how it is formatted.

This lesson walks through that family, then through the formatting verbs such as %d and %s, width and precision, how structs, slices, maps and pointers print, and how to write to standard error. It also previews the Stringer interface, which lets your own types control how they look.

The print family

The names follow a pattern. Take the base word and add letters:

Function Writes to Formatting
Print, Println, Printf standard output none / spaces and newline / format string
Sprint, Sprintln, Sprintf returns a string the same three styles
Fprint, Fprintln, Fprintf any io.Writer the same three styles

The prefix says where the text goes (S for string, F for a file or writer, nothing for stdout). The suffix says how: ln adds spaces between all arguments and a newline at the end, f uses a format string, and the plain version adds spaces only between operands when neither is a string.

Go Print, Println and Printf

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 shows the odd rule of Print: it adds a space between 1 and 2 (both are numbers), but not between "a" and "b" or around the strings. In practice you use Println for quick output and Printf when layout matters. Sprintf builds a string without printing it, which is the way to format text for anything other than the terminal.

Printf does not add a newline. End the format string with \n yourself, or the next output continues on the same line.

Format verbs

A format string mixes ordinary text with verbs that start with %. Each verb consumes the next argument and decides how to show it. The most useful ones:

Verb Meaning Example (input then output)
%v the value in its default format [1 2 3]
%+v like %v, with field names for structs {Name:Ada Age:36}
%#v Go-syntax representation main.User{Name:"Ada", Age:36}
%T the type of the value []int
%% a literal percent sign %
%t boolean true
%d integer in base 10 255
%b, %o, %x, %X integer in binary, octal, hex (lower, upper) 11111111, 377, ff, FF
%c the character for a code point A
%U Unicode format U+0041
%f, %e, %g float: fixed, scientific, shortest 3.141593, 3.141593e+00, 3.14159
%s string (or error, or Stringer) hello
%q quoted string or character, with escapes "hello"
%x on a string hex bytes 68656c6c6f
%p pointer address 0xc000012345
Go The common 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.

Two things to notice. %f prints six digits after the decimal point by default, and 'x' (a rune literal) has the type int32, which %T reports. rune is an alias for int32, so Go prints the real type name.

Wrong verbs and missing arguments

Go does not stop you at compile time when the verb does not match the argument. The result is visible in the output instead. go vet catches most of these mistakes, as The go Command and Basic Tooling explains.

Go Mismatches show up in the output

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=text), %!s(int=42), %!d(MISSING) and %!(EXTRA int=2). The %! marker is the sign of a formatting bug.

Width, precision and flags

Between % and the verb you can put modifiers. The general form is %[flags][width][.precision]verb.

  • Width is the minimum number of characters. Shorter output is padded with spaces on the left (right-aligned).
  • Precision after a dot means: digits after the decimal point for floats, maximum characters for strings.
  • Flags: - left-aligns, 0 pads with zeros, + always shows the sign, a space leaves room for a sign, and # adds a prefix such as 0x for hex.
  • A * in place of the width takes it from the argument list.
Go Aligning a small table

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.

%-12s means "left-aligned in 12 characters". Widths count runes, not bytes, so accented letters and emoji line up, though wide East-Asian characters may still look misaligned in a terminal.

How values print

%v works for every type, and its default output is consistent:

  • Slices and arrays: [1 2 3]. Maps: map[a:1 b:2] with keys sorted, so map printing is stable. Structs: {Ada 36}, or {Name:Ada Age:36} with %+v.
  • Pointers to structs print as &{Ada 36}, but a pointer to anything else prints an address, and addresses change between runs.
  • nil prints <nil>. Errors print their message.
Go Printing structs, slices, maps and pointers

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.

For a pointer, the address is meaningful only for debugging, so do not print it in tests or compare it in output. Use %p when you do need it. The variable err is a nil interface, so %T prints <nil> for its type.

Writing to other places

The F family takes any io.Writer. The two you will use first are os.Stdout and os.Stderr. Standard error is a second output stream meant for errors and diagnostics, so that normal output can be piped to a file or another program without mixing them.

Go Stdout and stderr

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.

In our editor both streams appear in the output panel, with stderr marked separately. In a terminal, go run main.go > out.txt would send only the normal output to the file. The builtin println also writes to stderr, but it is meant for bootstrapping and debugging only; use fmt in real code. Writers such as strings.Builder, files, network connections and HTTP responses all work with Fprintf, which is why Go I/O is so composable (os, io and bufio covers this).

A preview: the Stringer interface

If a type has a method String() string, fmt calls it when printing with %v or %s. That is how you control how your own types look. (Interfaces and methods get their own chapters, so treat this as a preview.)

Go Customizing output with String

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.

Notice that %v, %s, %+v and slices of Point all use String(), while %#v ignores it and prints the Go-syntax form (a separate GoString method can customize that). Number verbs such as %.2f do not call String(); the example converts to float64 to make that explicit. String is covered properly in Methods and Common Interfaces, and the whole verb list lives in fmt in Depth.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fmt.Printf("%5.1f|", 3.14159) print?

    Width 5 pads on the left with spaces; precision .1 keeps one digit after the decimal point, giving ' 3.1' (two spaces, then 3.1).
  2. 2. Which verb prints a value together with its struct field names?

    %+v adds field names to struct output. %v omits them and %T prints the type.
  3. 3. What does fmt.Sprintf return?

    The S functions return the result as a string instead of writing it anywhere.
  4. 4. How do you write a diagnostic message to standard error?

    The F functions write to any io.Writer, and os.Stderr is one. Println always goes to standard output.
  5. 5. What is printed by fmt.Printf("%d %s\n", 7)?

    Go compiles it, but the missing argument shows up as %!s(MISSING) in the output. go vet would flag this call.

Summary

  • Print, Println and Printf write to stdout. The S versions return a string, and the F versions write to any io.Writer.
  • Println always separates operands with spaces and adds a newline. Printf adds neither.
  • Core verbs: %v, %+v, %#v, %T, %d, %s, %q, %x, %f, %e, %g, %t, %c, %U, %p.
  • %[flags][width][.precision]verb controls alignment, padding and the number of decimals.
  • Maps print with sorted keys. Pointers to structs print as &{...}; other pointers print addresses.
  • A String() string method customizes how your type prints. Send diagnostics to os.Stderr.

Next: Reading Input shows how to get text and numbers from the user into your program.