Go Formatting Verbs

Go Formatting Verbs #

Go provides several formatting verbs that can be used with the fmt.Printf() function to control the output format of data.


✅ General Formatting Verbs #

These verbs work with all data types:

VerbDescription
%vPrints the value in default format
%#vPrints the value in Go-syntax format
%TPrints the type of the value
%%Prints the percent sign (%)

Example: #

package main

import "fmt"

func main() {
    var i = 15.5
    var txt = "Hello World!"

    fmt.Printf("%v\n", i)
    fmt.Printf("%#v\n", i)
    fmt.Printf("%v%%\n", i)
    fmt.Printf("%T\n", i)

    fmt.Printf("%v\n", txt)
    fmt.Printf("%#v\n", txt)
    fmt.Printf("%T\n", txt)
}

Result:

15.5
15.5
15.5%
float64
Hello World!
"Hello World!"
string

✅ Integer Formatting Verbs #

VerbDescription
%bBase 2 (binary)
%dBase 10 (decimal)
%+dBase 10 with sign
%oBase 8 (octal)
%OBase 8 with leading “0o”
%xBase 16 (lowercase hex)
%XBase 16 (uppercase hex)
%#xBase 16 with “0x” prefix
%4dWidth 4, right justified
%-4dWidth 4, left justified
%04dWidth 4, padded with zeros

Example: #

package main

import "fmt"

func main() {
    var i = 15

    fmt.Printf("%b\n", i)
    fmt.Printf("%d\n", i)
    fmt.Printf("%+d\n", i)
    fmt.Printf("%o\n", i)
    fmt.Printf("%O\n", i)
    fmt.Printf("%x\n", i)
    fmt.Printf("%X\n", i)
    fmt.Printf("%#x\n", i)
    fmt.Printf("%4d\n", i)
    fmt.Printf("%-4d\n", i)
    fmt.Printf("%04d\n", i)
}

Result:

1111
15
+15
17
0o17
f
F
0xf
  15
15  
0015

✅ String Formatting Verbs #

VerbDescription
%sPlain string
%qDouble-quoted string
%8sRight-justified with width 8
%-8sLeft-justified with width 8
%xHex dump of byte values
% xHex dump with spaces

Example: #

package main

import "fmt"

func main() {
    var txt = "Hello"

    fmt.Printf("%s\n", txt)
    fmt.Printf("%q\n", txt)
    fmt.Printf("%8s\n", txt)
    fmt.Printf("%-8s\n", txt)
    fmt.Printf("%x\n", txt)
    fmt.Printf("% x\n", txt)
}

Result:

Hello
"Hello"
   Hello
Hello   
48656c6c6f
48 65 6c 6c 6f

✅ Boolean Formatting Verbs #

VerbDescription
%tPrints true or false (same as %v)

Example: #

package main

import "fmt"

func main() {
    var i = true
    var j = false

    fmt.Printf("%t\n", i)
    fmt.Printf("%t\n", j)
}

Result:

true
false

✅ Float Formatting Verbs #

VerbDescription
%eScientific notation (e.g., 1.234e+00)
%fDecimal point without exponent
%.2fDefault width, precision 2
%6.2fWidth 6, precision 2
%gExponent as needed, only necessary digits

Example: #

package main

import "fmt"

func main() {
    var i = 3.141

    fmt.Printf("%e\n", i)
    fmt.Printf("%f\n", i)
    fmt.Printf("%.2f\n", i)
    fmt.Printf("%6.2f\n", i)
    fmt.Printf("%g\n", i)
}

Result:

3.141000e+00
3.141000
3.14
  3.14
3.141

🚀 Now you have a solid understanding of Go’s powerful formatting verbs for Printf()!