If I have a type in go like this:
type myType ...
func (m myType) String() string { ... }
how can I print (using the various fmt functions) this type using the default representation (that is, instead of having String() called)? What I'd like to do is something like this:
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)
    }
}
                fmt.Stringer is the default format, which is called when you use %v. If you want the Go syntax, use %#v. 
Alternatively, you can bypass the reflection in fmt altogether, and format your output as you see fit.
func (m myType) String() string {
    return fmt.Sprintf("{Field: %s}", m.Value)
}
If the underlying type of myType is a number, string or other simple type, then convert to the underlying type when printing:
func (m mType) String() string {
    return fmt.Sprint(int(m))
}
                        Use %#v instead of %v
That will not invoke String(). - but it will invoke GoString() if you implement it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With