forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 2
/
deepprint.go
81 lines (75 loc) · 1.51 KB
/
deepprint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package util
import (
"bytes"
"fmt"
"reflect"
)
// DeepPrint is like printing with the %#v formatter of fmt, but it prints
// pointer fields recursively.
func DeepPrint(x interface{}) string {
b := &bytes.Buffer{}
deepPrint(b, reflect.ValueOf(x))
return b.String()
}
func deepPrint(b *bytes.Buffer, v reflect.Value) {
i := v.Interface()
t := v.Type()
// GoStringer
if g, ok := i.(fmt.GoStringer); ok {
b.WriteString(g.GoString())
return
}
// nil
switch v.Kind() {
case reflect.Interface, reflect.Map, reflect.Slice, reflect.Ptr:
if v.IsNil() {
b.WriteString("nil")
return
}
}
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.Map, reflect.Struct:
// Composite kinds
b.WriteString(t.String())
b.WriteRune('{')
switch v.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < v.Len(); i++ {
if i > 0 {
b.WriteString(", ")
}
deepPrint(b, v.Index(i))
}
case reflect.Map:
keys := v.MapKeys()
for i, k := range keys {
if i > 0 {
b.WriteString(", ")
}
deepPrint(b, k)
b.WriteString(": ")
deepPrint(b, v.MapIndex(k))
}
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(t.Field(i).Name)
b.WriteString(": ")
deepPrint(b, v.Field(i))
}
}
b.WriteRune('}')
case reflect.Ptr:
b.WriteRune('&')
deepPrint(b, reflect.Indirect(v))
return
case reflect.Interface:
deepPrint(b, v.Elem())
return
default:
fmt.Fprintf(b, "%#v", i)
return
}
}