-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
I'm currently working with a custom fmt.Formatter implementation. Similar to the request in #51195, I would like to implement some methods and then "fall back" to the default fmt
implementation for unimplemented verbs.
It's difficult to do this because State does not allow you to reconstruct the original format string, unless you enumerate all of the possible characters in a format string and call Flag(char)
on each one. This is lengthy and error prone.
I would like to formally propose what @bcmills suggested in #25150, which is to add a String() api to fmt.State
.
// State represents the printer state passed to custom formatters.
// It provides access to the io.Writer interface plus information about
// the flags and options for the operand's format specifier.
type State interface {
// Write is the function to call to emit formatted output to be printed.
Write(b []byte) (n int, err error)
// Width returns the value of the width option and whether it has been set.
Width() (wid int, ok bool)
// Precision returns the value of the precision option and whether it has been set.
Precision() (prec int, ok bool)
// Flag reports whether the flag c, a character, has been set.
Flag(c int) bool
// String returns the original format string that was used to create this State (e.g. "%#v")
String() string
}
I doubt that there are many implementations of the API, which would limit the amount of breakage from adding a new method.
In the standard library, there is currently only one implementation of fmt.State
- in the pp
struct.
If someone can give me pointers on how to do a search across all of Github, I would be happy to check whether there are in-the-wild implementations of fmt.State. I'd also appreciate if someone could do the same inside of Google.
Thanks to Bryan Mills, Github user seebs and Eric Lagergren for initial suggestions and discussion.