Formatting Strings
Go uses a system of “formatting verbs” to interpolate values into strings, similar to the printf function in C.
Output vs. Return
fmt.Printf(): Prints a formatted string directly to the console (standard out).fmt.Sprintf(): Returns a formatted string as a value instead of printing it.
Common Formatting Verbs
| Verb | Description | Example |
|---|---|---|
%v |
Default representation (any type) | fmt.Sprintf("%v", 10) -> "10" |
%T |
Type of the value | fmt.Printf("%T", 10.5) -> float64 |
%s |
String | fmt.Sprintf("Hi %s", "Dalinar") |
%d |
Decimal integer | fmt.Sprintf("Age: %d", 45) |
%f |
Float | fmt.Sprintf("%.2f", 3.14159) -> "3.14" |
\n |
Newline character | Starts a new line in the console |
Precision
For floating-point numbers, you can control the number of decimal places using %.Nf, where N is the number of digits:
rate := 30.567
fmt.Printf("Rate: %.1f", rate) // Rate: 30.6