我想为打印结构实现一些自定义行为。然而,Go 为结构定义了几种不同格式的动词,我不想重写所有这些,只想重写其中的一些。
我不知道如何在 Go 中做到这一点,而且这更困难,因为据我所知,如果你只有一个
fmt.State
,你就无法轻松恢复原始格式字符串 - 你必须枚举标志并然后调用 state.Flag(flag)
查看是否每一项都已设置。
这就是我到目前为止所拥有的 - 对于未实现的动词,只需创建第二个不带 Format() 参数的结构并在其上调用 fmt.Print 。还有比这更好的办法吗?
// Help values are returned by commands to indicate to the caller that it was
// called with a configuration that requested a help message rather than
// executing the command.
type Help struct {
Cmd string
}
// Fallback for unimplemented fmt verbs
type fmtHelp struct{ cmd string }
// Format satisfies the fmt.Formatter interface, print the help message for the
// command carried by h.
func (h *Help) Format(w fmt.State, v rune) {
switch v {
case 's':
printUsage(w, h.Cmd)
printHelp(w, h.Cmd)
case 'v':
if w.Flag('#') {
io.WriteString(w, "cli.Help{")
fmt.Fprintf(w, "%#v", h.Cmd)
io.WriteString(w, "}")
return
}
printUsage(w, h.Cmd)
printHelp(w, h.Cmd)
default:
// fall back to default struct formatter. TODO this does not handle
// flags
fmt.Fprintf(w, "%"+string(v), fmtHelp{h.Cmd})
}
}
对于后备,您会希望在默认情况下使用此功能
default:
// Get the bypassed format directive
fmtDirective := fmt.FormatString(w, v)
fmt.Fprintf(f, fmtDirective, h.Cmd)
此外,最好使用未使用的指令,例如)
h
,以便将功能添加到代码库中。