只实现fmt.Formatter的一些动词(其他的则回退到Go的默认值)

uz75evzq  于 2023-06-27  发布在  Go
关注(0)|答案(1)|浏览(83)

我想为打印的结构实现一些自定义行为。然而,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})
    }
}
xtupzzrd

xtupzzrd1#

你可以使用类似这样的东西:

package hello

import "fmt"

type world int

func (w world) Format(f fmt.State, c rune) {
   switch c {
   case 'd':
      fmt.Fprint(f, "Ceci n'est pas un nombre")
   case 's':
      fmt.Fprint(f, w)
   default:
      type hideMethods world
      type world hideMethods
      fmt.Fprintf(f, fmt.FormatString(f, c), world(w))
   }
}

相关问题