我想为打印的结构实现一些自定义行为。然而,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})
}
}
1条答案
按热度按时间xtupzzrd1#
你可以使用类似这样的东西: