In this code:
type A struct { t time.Time } func main() { a := A{time.Now()} fmt.Println(a) fmt.Println(a.t) }
notice that A doesn't implement the String() method, so fmt.Println(a) prints its native representation. Updating String() for every new field in a struct can be tedious.
Unfortunately, this behavior is inherent to the fmt package. However, a helper function using reflection can solve this issue:
func PrintStruct(s interface{}, names bool) string { v := reflect.ValueOf(s) t := v.Type() // To avoid panic if s is not a struct: if t.Kind() != reflect.Struct { return fmt.Sprint(s) } b := &bytes.Buffer{} b.WriteString("{") for i := 0; i < v.NumField(); i++ { if i > 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() }
This function uses reflection to iterate over struct fields and call their String() methods if available.
Usage:
fmt.Println(PrintStruct(a, true))
Optionally, add a String() method to the struct that calls PrintStruct():
func (a A) String() string { return PrintStruct(a, true) }
Now, struct fields with String() will be printed automatically.
Notes:
The above is the detailed content of How Can I Easily Print Go Structs with Their Field Names and String() Methods?. For more information, please follow other related articles on the PHP Chinese website!