go - How to print struct with String() of fields? -
this code:
type struct { t time.time } func main() { := a{time.now()} fmt.println(a) fmt.println(a.t) }
prints:
{{63393490800 0 0x206da0}} 2009-11-10 23:00:00 +0000 utc
a
doesn't implement string()
, it's not fmt.stringer
, prints native representation. tedious implement string()
every single struct want print. worse, have update string()
s if add or remove fields. there easier way print struct, fields' string()
s?
this how fmt
package implemented, can't change that.
but can write helper function uses reflection (reflect
package) iterate on fields of struct, , can call string()
method on fields if have such method.
example implementation:
func printstruct(s interface{}, names bool) string { v := reflect.valueof(s) t := v.type() // avoid panic if s not struct: if t.kind() != reflect.struct { return fmt.sprint(s) } b := &bytes.buffer{} b.writestring("{") := 0; < v.numfield(); i++ { if > 0 { b.writestring(" ") } v2 := v.field(i) if names { b.writestring(t.field(i).name) b.writestring(":") } if v2.caninterface() { if st, ok := v2.interface().(fmt.stringer); ok { b.writestring(st.string()) continue } } fmt.fprint(b, v2) } b.writestring("}") return b.string() }
now when want print struct
, can do:
fmt.println(printstruct(a, true))
you may choose add string()
method struct has call our printstruct()
function:
func (a a) string() string { return printstruct(a, true) }
whenever change struct, don't have string()
method uses reflection dynamically walk on fields.
notes:
since we're using reflection, have export t time.time
field work (also added few fields testing purposes):
type struct { t time.time int unexported string }
testing it:
a := a{time.now(), 2, "hi!"} fmt.println(a) fmt.println(printstruct(a, true)) fmt.println(printstruct(a, false)) fmt.println(printstruct("i'm not struct", true))
output (try on go playground):
{t:2009-11-10 23:00:00 +0000 utc i:2 unexported:hi!} {t:2009-11-10 23:00:00 +0000 utc i:2 unexported:hi!} {2009-11-10 23:00:00 +0000 utc 2 hi!} i'm not struct
Comments
Post a Comment