如果我在go语言中定义了以下类型:
type myType ...
func (m myType) String() string { ... }
如何使用默认表示打印此类型(使用各种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)
}
}
%v
格式。请参考我的回答。 - Ainar-Gtype myType struct { a myOtherType}
这样的情况就不那么直接了。Effective Go 中似乎也没有任何提示表明 %#v 不是 OP 想要的东西。 - nos