Go Formatting Verbs

Go Formatting Verbs – Complete Guide with Examples
In Go (Golang), formatting verbs are special placeholders used with fmt.Printf, fmt.Sprintf, and related functions to control how values are displayed.
They allow you to print data in a clean, readable, and formatted way, which is essential for debugging, logging, and user output.
What Are Formatting Verbs in Go?
Formatting verbs are symbols that start with % and tell Go how to format a value.
Example
%s→ string%d→ integer
Why Formatting Verbs Are Important?
Formatting verbs help you:
- Control output appearance
- Print different data types correctly
- Debug values and types
- Create readable logs
- Format numbers and text
Commonly Used Formatting Verbs
General Verbs
| Verb | Description |
|---|---|
%v | Default value |
%+v | Struct with field names |
%#v | Go-syntax representation |
%T | Type of the value |
%% | Prints % |
Example
Integer Formatting Verb
| Verb | Meaning |
|---|---|
%d | Decimal |
%b | Binary |
%o | Octal |
%x | Hexadecimal (lowercase) |
%X | Hexadecimal (uppercase) |
Example
Floating-Point Formatting Verb
| Verb | Meaning |
|---|---|
%f | Decimal notation |
%.2f | 2 decimal places |
%e | Scientific notation |
%g | Compact format |
Example
- Controls decimal precision
String Formatting Verb
| Verb | Meaning |
|---|---|
%s | String |
%q | Quoted string |
%x | Hex dump of string |
Example
Boolean Formatting Verb
| Verb | Meaning |
|---|---|
%t | Boolean value |
Example
Pointer Formatting Verb
| Verb | Meaning |
|---|---|
%p | Memory address |
Example
Struct Formatting Verb
| Verb | Output |
|---|---|
%v | {Amit 25} |
%+v | {Name:Amit Age:25} |
%#v | main.User{Name:"Amit", Age:25} |
Width and Alignment
Width
Left Alignment
- Useful for tables
Zero Padding
Output: 00025
Formatting Multiple Values
Printf vs Sprintf vs Fprintf
| Function | Purpose |
|---|---|
Printf | Prints to console |
Sprintf | Returns formatted string |
Fprintf | Writes to writer (file, buffer) |
Example
Common Mistakes
- Using wrong verb for type
- Forgetting
\ninPrintf Mismatch between verb and value- Overusing
%veverywhere
Best Practices
- Use specific verbs (
%d,%s) - Use
%vfor quick debugging - Control precision for floats
- Use
%+vfor structs - Keep output readable
Interview Questions: Go Formatting Verb
1. What does %v do?
Prints the default value.
2. How to print type of variable?
Use %T.
3. Which verb prints struct field names?%+v.
4. How to print float with 2 decimals?%.2f.
5. How to print memory address?%p.
Summary
- Formatting verb control output
- Used with
fmt.Printffamily - Different verb for different types
- Precision and alignment supported
- Essential for debugging & logging
Mastering Go formatting verb will make your output clean, professional, and interview-ready
