如果我有这样的旅途中类型:打印围棋类型忽略“字符串()字符串”方法
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)
}
}
这是Effective Go中的内容。 OP应该将该值转换为基础类型,然后使用'%v'格式。看到我的答案。 – 2014-09-24 14:52:01
@ Ainar-G对于类型别名,您的答案很简单,但对于例如'输入myType struct {myOtherType}'。 Effective Go中似乎也没有任何内容表明%#v不是OP想要的。 – nos 2014-09-24 15:09:24
你是对的,编辑我的答案。 – 2014-09-24 15:18:11