Go String Formatting
String formatting is how you build complex strings from variables. Go uses "verbs" (like %d) to tell the program how to format each value.
Common Tasks
1. Building a simple string
Use fmt.Sprintf to create a new string without printing it to the console.
2. Formatting Numbers
- Decimal:
%d - Float:
%f(or%.2ffor two decimal places) - Binary:
%b
3. Working with Structs
Use %+v to see the field names of a struct.
4. Padding and Alignment
Use numbers after the % to set the width.
Reference Table
| Verb | Description |
|---|---|
%v |
The default value. |
%T |
The type of the value. |
%t |
Boolean (true/false). |
%d |
Signed decimal integer. |
%f |
Floating point number. |
%s |
String. |
%p |
Pointer (memory address). |