Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a Go type ignoring "String() string" method

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)
    }
}
like image 907
joshlf Avatar asked Dec 14 '22 19:12

joshlf


2 Answers

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))
}
like image 126
JimB Avatar answered Jan 28 '23 16:01

JimB


Use %#v instead of %v

That will not invoke String(). - but it will invoke GoString() if you implement it.

like image 43
nos Avatar answered Jan 28 '23 16:01

nos