Go: Print with fmt cheat sheet

A format specifier is a string that contains the text you want to format plus some placeholders, called verbs, that tell the functions in the fmt package how to format your arguments.

In this example:

fmt.Printf("Hex: %x.\n", 255) // Output: "Hex: ff."

Use the special verb %%, which consumes no argument, to write a literal percent sign:

fmt.Printf("%d %%", 50) // Output: "50 %"

Generic formatting

Argument: []int{1, 2}

Formatting Description Verb
[1 2] Default format %v
[]int{1, 2} Go-syntax format %#v
[]int The type of the value %T

Integer

Argument: 109

Formatting Description Verb
109 Base 10 %d
+109 Always show sign %+d
␣109 Width 4, right justify %4d
109␣ Width 4, left justify %-4d
0109 Width 4, pad with zero %04d
m Character %c
'm' Quoted character %q
1101101 Base 2 %b
155 Base 8 %o
6d Base 16, lowercase %x
6D Base 16, uppercase %X
0x6d Base 16, with leading 0x %#x
U+006D Unicode %U
U+006D 'm' Unicode with character %#U

Boolean

Use %t to format a boolean as true or false.

Pointer

Use %p to format a pointer in base 16 notation with leading 0x.

Float

Argument: 123.456

Formatting Description Verb
1.234560e+02 Scientific notation %e
123.456000 Decimal point, no exponent %f
123.46 Default width, precision 2 %.2f
␣␣123.46 Width 8, precision 2 %8.2f
123.456 Exponent as needed, necessary digits only %g

String or byte slice

Argument: "café"

Formatting Description Verb
café Plain string %s
␣␣café Width 6, right justify %6s
café␣␣ Width 6, left justify %-6s
"café" Quoted string %q
636166c3a9 Hex dump of byte values %x
63 61 66 c3 a9 Hex dump with spaces % x

Special values

Value Description
\a U+0007 alert or bell
\b U+0008 backspace
\f U+000C form feed
\n U+000A line feed or newline
\r U+000D carriage return
\t U+0009 horizontal tab
\v U+000b vertical tab
\\ U+005c backslash

Arbitrary values can be encoded with backslash escapes. There are four different formats:

The escapes \u and \U represent Unicode code points.

These special values can be used in any "" string literal:

fmt.Println("\\caf\u00e9") // Output: \café

Comments

Be the first to comment!