Go fmt formattings Cheat Sheet

A Programming › Golang cheat sheet in English by fenistil

Go fmt package formatting with examples

6,711 views 1,312 downloads 3 Jul 2021 History

Formatting functions

//Prints the formatted string
fmt.Printf("format",value1, value2, ...)

//Returns the formatted string
s := fmt.Sprintf("format",value1, value2, ...)

Default formats and type

Default format
%v
[4.13 7.13]
Golang syntax
%#v
[]floa­t64­{4.13, 7.13}
The type of the value
%T
[]float64

Pointer

Memory address
%p
0xc000­00713f
The %b, %d, %o, %x and %X verbs also work with pointers, formatting the value exactly as if it were an integer.

Boolean

Boolean as true / false
%t
true

Integer

Base 10
%d
13
Always show sign
%+d
+13
Right padding with spaces
%4d
__13
Left padding with spaces
%-4d
13__
Pad with zeros
%04d
0013
Binary repres­ent­ation
%b
1101
Octal repres­ent­ation
%o
15
Octal repres­ent­ation with leading 0o
%O
0o15
Hex repres­ent­ation, lowercase
%x
d
Hex repres­ent­ation, uppercase
%X
D
Hex repres­ent­ation with leading 0x
%#x
0xf
The unicode character
%c
A
The unicode code point
%U
U+0041

Float

Scientific format
%e
7.1341­30e+02
With decimal point
%f
713.413000
Fixed precision
%.2f
713.41
Left padding with spaces
%8.2f
__713.41
Automatic decimal count
%g
713.413

Rune

Character
%c
D
Quoted character
%q
'­D'
Unicode code
%U
U+0044
Unicode code and character
%#U
U+0044 '­D'

String and byte slice

Plain string
%s
Gopher
Left padding with spaces
%10s
____Gopher
Right padding with spaces
%-10s
Gopher____
Quoted string
%q
"­Gop­her­"
Hex dump
%x
476f70­686572
Hex dump with spaces
% x
47 6f 70 68 65 72
Hex dump, uppercase
%X
476F70­686572
Hex dump with spaces, uppercase
% X
47 6F 70 68 65 72

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.