打印Go类型,忽略"String()string"方法

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)

Jim*_*imB 6

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)


nos*_*nos 4

使用%#v而不是%v

这不会调用 String()。- 但如果你实现它,它会调用GoString ()。