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
}
fmt 中的接口
接口
fmt.Stringer
重写类型默认的格式化字符串占位符
%s
对应的字符串生成方法。fmt.GoStringer
重写类型默认的格式化字符串占位符
%#v
对应的字符串生成方法。fmt.State
fmt.State
由printer解析得到。占位符和fmt.State
对应关系是,Width()和Precision()对应位宽和精度,Flag()对应符号位 例如: 占位符%+3.2f
中,s.Width()返回值3
,s.Percision()返回值2
,s.Flag('+')
返回值为ture
,即判断是否是'+'
fmt.Formatter
实现自定义格式化方法,第一个参数实现了
fmt.State
,第二个参数是占位符类型,即对应%+3.2f
中f
。f
实现了io.Writer
接口,通过Write
方法将自定义的格式化字串写入示例
通过给Dog实现
fmt.Formatter
接口,实现用自定义的占位符%K
代替%#v
输出:
ref: https://zh.wikipedia.org/wiki/%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%AD%97%E7%AC%A6%E4%B8%B2 https://github.com/golang/go/tree/master/src/fmt