Go Formatting Verbs

Go (Golang) – Formatting Verbs (fmt Package)

Formatting verbs are placeholders used with fmt.Printf(), fmt.Sprintf(), etc., to control how values are displayed.


1️⃣ General Formatting Verbs

Verb Meaning Example
%v Default format fmt.Printf("%v", x)
%+v Struct with field names fmt.Printf("%+v", user)
%#v Go-syntax representation fmt.Printf("%#v", user)
%T Type of value fmt.Printf("%T", x)
%% Print % fmt.Printf("%%")

2️⃣ String Formatting Verbs

Verb Meaning Example
%s String "Hello"
%q Quoted string "Hello"
%x Hex (bytes) "go"676f
fmt.Printf("%s %q\n", "Go", "Go")

3️⃣ Integer Formatting Verbs

Verb Meaning
%d Decimal
%b Binary
%o Octal
%x Hex (lowercase)
%X Hex (uppercase)
%c Unicode character
%U Unicode code point
x := 65
fmt.Printf("%d %b %c\n", x, x, x)

4️⃣ Floating-Point Formatting Verbs

Verb Meaning
%f Decimal point
%.2f 2 decimal places
%e Scientific notation
%E Scientific (uppercase)
%g Compact format
pi := 3.14159
fmt.Printf("%.2f\n", pi)

5️⃣ Boolean Formatting

Verb Meaning
%t Boolean (true / false)
fmt.Printf("%t\n", true)

6️⃣ Pointer Formatting

Verb Meaning
%p Memory address
x := 10
fmt.Printf("%p\n", &x)

7️⃣ Width & Precision

Width

fmt.Printf("%6d\n", 123)

Precision

fmt.Printf("%.3f\n", 3.14159)

Width + Precision

fmt.Printf("%8.2f\n", 12.345)

8️⃣ Alignment & Padding

Right-aligned (default)

fmt.Printf("%6d\n", 42)

Left-aligned

fmt.Printf("%-6d\n", 42)

Zero padding

fmt.Printf("%06d\n", 42)

9️⃣ Formatting Structs & Maps

type User struct {
Name string
Age int
}

u := User{"Amit", 30}

fmt.Printf("%v\n", u)
fmt.Printf("%+v\n", u)
fmt.Printf("%#v\n", u)


🔟 Common Mistakes

❌ Using wrong verb for type

fmt.Printf("%d", "Go") // error

✅ Correct

fmt.Printf("%s", "Go")

Summary Cheat Sheet

Data Type Verb
Any %v
String %s
Int %d
Float %f
Bool %t
Type %T
Pointer %p

You may also like...