fmt.Formatter Custom Verbs
Implement fmt.Formatter so Printf hands your type the verb and flags, letting it render its own %v, %+v, and %q output.
Code
package main
import (
"fmt"
"time"
)
type Latency struct {
d time.Duration
}
// Format 实现 fmt.Formatter:fmt 把 verb 与 flag 一起交给你解释
func (l Latency) Format(state fmt.State, verb rune) {
switch verb {
case 'v', 's':
// Flag('+') 对应 %+v:带单位后缀的详细形式
if state.Flag('+') {
fmt.Fprintf(state, "%dms(total)", l.d.Milliseconds())
return
}
fmt.Fprintf(state, "%dms", l.d.Milliseconds())
case 'q':
// 转交给下层 verb:%q 会加上引号
fmt.Fprintf(state, "%q", l.d.String())
default:
// 未支持的 verb 显式报告,而不是默默输出零值
fmt.Fprintf(state, "%%!%c(Latency)", verb)
}
}
func main() {
l := Latency{d: 1500 * time.Millisecond}
fmt.Printf("%v\n", l) // 默认形式
fmt.Printf("%+v\n", l) // flag 分支
fmt.Printf("%q\n", l) // 引号形式
fmt.Printf("%d\n", l) // 走 default 分支
// 同一个值放进复合结构时,%+v 会把 flag 传进每个元素
fmt.Printf("%+v\n", []Latency{l, {d: 250 * time.Millisecond}})
}Verbs handed to the type
Two pieces do the work: the Format method plus a main that exercises each verb.
Caveats
- fmt and time are all it pulls in — both ship with the toolchain.
Applying it
The entry-point signature is func (l Latency) Format(state fmt.State, verb rune)
Lines that decide the output
func main() {
l := Latency{d: 1500 * time.Millisecond}
fmt.Printf("%v\n", l) // 默认形式
fmt.Printf("%+v\n", l) // flag 分支
fmt.Printf("%q\n", l) // 引号形式
fmt.Printf("%d\n", l) // 走 default 分支
// 同一个值放进复合结构时,%+v 会把 flag 传进每个元素
fmt.Printf("%+v\n", []Latency{l, {d: 250 * time.Millisecond}})
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run fmt.Formatter Custom Verbs?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.