Printing Go type ignoring String () method

If I have a type, follow these steps:

type myType ...

func (m myType) String() string { ... }

      

how can I print (using various functions fmt

) this type using the default view (i.e. instead of being called String()

)? I would like to do 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)
    }
}

      

+3


source to share


3 answers


fmt.Stringer

is the default format that is invoked when used %v

. If you want Go syntax use %#v

.

Alternatively, you can bypass reflection fmt

altogether and format your output as you see fit.

func (m myType) String() string {
    return fmt.Sprintf("{Field: %s}", m.Value)
}

      



If the base type myType is a number, string, or some other simple type, then it should be converted to the base type when printing:

func (m mType) String() string {
    return fmt.Sprint(int(m))
}

      

+6


source


Use %#v

instead%v



This will not call String (). - but it will call GoString () if you implement it.

+3


source


Using format is %#v

not the correct answer if you want your base type to String

work, or if your type is an alias for a type.

As explained in Efficient Move , just cast it back to the type it represents:

type Foo int

func (f Foo) String() string {
    if f == 0 {
        return "foo"
    }
    return fmt.Sprintf("%v", int(f)) // N.B.
}

func main() {
    fmt.Println(Foo(0))
    fmt.Println(Foo(42))
}

      

Playground .

EDIT: . As other comments have pointed out, if your type is a struct, using the format %#v

seems like the only way other than converting it to an anonymous struct type with the same fields.

+2


source







All Articles