0 day streak
go / intermediate
Snippet

Customizing String Formatting with fmt.Formatter

Go's fmt.Formatter interface allows developers to customize how types are formatted when using fmt.Printf. By implementing the Format(f fmt.State, verb rune) method, you can inspect the verb (like '%c' or '%f') and print custom representations directly to the writer state.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main
import (
"fmt"
"strconv"
)
type Temperature float64
func (t Temperature) Format(f fmt.State, verb rune) {
switch verb {
case 'c':
f.Write([]byte(strconv.FormatFloat(float64(t), 'f', 1, 64) + "°C"))
case 'f':
fah := float64(t)*9/5 + 32
f.Write([]byte(strconv.FormatFloat(fah, 'f', 1, 64) + "°F"))
default:
f.Write([]byte(strconv.FormatFloat(float64(t), 'f', 2, 64)))
}
}
func main() {
temp := Temperature(25.0)
fmt.Printf("Celsius: %c\n", temp)
fmt.Printf("Fahrenheit: %f\n", temp)
}
Breakdown
1
type Temperature float64
Defines a custom floating-point type representing temperature.
2
func (t Temperature) Format(f fmt.State, verb rune)
Implements the fmt.Formatter interface for the Temperature type.
3
switch verb {
Evaluates the formatting verb passed in the print statement.
4
f.Write([]byte(strconv.FormatFloat(float64(t), 'f', 1, 64) + "°C"))
Writes the formatted string bytes directly into the state destination.