go / intermediate
Snippet
Customizing Format Output with the fmt.Formatter Interface
By implementing the fmt.Formatter interface, a custom Go type can define precisely how it formats across different verbs in the fmt package. This allows you to handle custom custom representation logic, like unit conversions, during standard printing.
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
package mainimport ("fmt""strconv")type Celsius float64func (c Celsius) Format(f fmt.State, verb rune) {switch verb {case 'f':f.Write([]byte(strconv.FormatFloat(float64(c), 'f', 2, 64) + " °C"))case 'k':kelvin := float64(c) + 273.15f.Write([]byte(strconv.FormatFloat(kelvin, 'f', 2, 64) + " K"))default:f.Write([]byte(strconv.FormatFloat(float64(c), 'f', 2, 64)))}}func main() {temp := Celsius(21.5)fmt.Printf("Celsius: %f, Kelvin: %k\n", temp, temp)}
Breakdown
1
func (c Celsius) Format(f fmt.State, verb rune) {
Implements the fmt.Formatter interface for the custom Celsius type.
2
f.Write([]byte(...))
Writes the formatted representation directly to the state's writer.
3
switch verb {
Inspects the formatting verb to determine the output style.