jos*_*hlf 3 formatting printf interface go
如果我有一个这样的类型:
type myType ...
func (m myType) String() string { ... }
Run Code Online (Sandbox Code Playgroud)
如何fmt
使用默认表示(即,而不是String()
调用)打印(使用各种函数)此类型?我想做的是这样的事情:
func (m myType) String() string {
// some arbitrary property
if myType.isValid() {
// format properly
} else {
// will recurse infinitely; would like default
// representation instead
return fmt.Sprintf("invalid myType: %v", m)
}
}
Run Code Online (Sandbox Code Playgroud)
fmt.Stringer
是默认格式,在您使用时调用%v
.如果您想要Go语法,请使用%#v
.
或者,您可以fmt
完全绕过反射,并根据需要格式化输出.
func (m myType) String() string {
return fmt.Sprintf("{Field: %s}", m.Value)
}
Run Code Online (Sandbox Code Playgroud)
如果myType的基础类型是数字,字符串或其他简单类型,则在打印时转换为基础类型:
func (m mType) String() string {
return fmt.Sprint(int(m))
}
Run Code Online (Sandbox Code Playgroud)