-
Notifications
You must be signed in to change notification settings - Fork 1
/
kind_struct.go
97 lines (77 loc) · 1.98 KB
/
kind_struct.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package dapper
import (
"reflect"
"strings"
)
// renderStructKind renders [reflect.Struct] values.
func renderStructKind(r Renderer, v Value) {
// We don't render anonymous types even if the type is ambiguous. Otherwise
// we'd be printing the full type definition of the anonymous type. Instead
// we mark each field as ambiguous and render their types inline.
if v.IsAmbiguousType() && !v.IsAnonymousType() {
r.WriteType(v)
}
if v.DynamicType.NumField() == 0 {
r.Print("{}")
return
}
if v.Value.IsZero() && !v.IsAnonymousType() {
r.Print("{%s}", r.Config().ZeroValueMarker)
return
}
r.Print("{\n")
r.Indent()
renderStructFields(r, v)
r.Outdent()
r.Print("}")
}
func renderStructFields(r Renderer, v Value) error {
omitUnexported := r.Config().OmitUnexportedFields
alignment := longestFieldName(v.DynamicType, omitUnexported)
for i := 0; i < v.DynamicType.NumField(); i++ {
f := v.DynamicType.Field(i)
if omitUnexported && isUnexportedField(f) {
continue
}
fv := v.Value.Field(i)
isInterface := f.Type.Kind() == reflect.Interface
r.Print(
"%s: %s",
f.Name,
strings.Repeat(
" ",
alignment-len(f.Name),
),
)
r.WriteValue(
Value{
Value: fv,
DynamicType: fv.Type(),
StaticType: f.Type,
IsAmbiguousDynamicType: isInterface,
IsAmbiguousStaticType: v.IsAmbiguousStaticType && v.IsAnonymousType(),
IsUnexported: v.IsUnexported || isUnexportedField(f),
},
)
r.Print("\n")
}
return nil
}
// isUnxportedField returns true if f is an unexported field.
func isUnexportedField(f reflect.StructField) bool {
return f.PkgPath != ""
}
// longestFieldName returns the length of the longest field name in a struct.
func longestFieldName(rt reflect.Type, exportedOnly bool) int {
width := 0
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
if !exportedOnly || !isUnexportedField(f) {
n := len(f.Name)
if n > width {
width = n
}
}
}
return width
}