@@ -13,13 +13,18 @@ const structFieldTagKey = "table"
13
13
// StructValues tab delimits the values of a given struct.
14
14
//
15
15
// Tag a field `table:"-"` to hide it from output.
16
+ // Tag a field `table:"_"` to flatten its subfields.
16
17
func StructValues (data interface {}) string {
17
18
v := reflect .ValueOf (data )
18
19
s := & strings.Builder {}
19
20
for i := 0 ; i < v .NumField (); i ++ {
20
21
if shouldHideField (v .Type ().Field (i )) {
21
22
continue
22
23
}
24
+ if shouldFlatten (v .Type ().Field (i )) {
25
+ fmt .Fprintf (s , "%v\t " , StructValues (v .Field (i ).Interface ()))
26
+ continue
27
+ }
23
28
fmt .Fprintf (s , "%v\t " , v .Field (i ).Interface ())
24
29
}
25
30
return s .String ()
@@ -28,14 +33,22 @@ func StructValues(data interface{}) string {
28
33
// StructFieldNames tab delimits the field names of a given struct.
29
34
//
30
35
// Tag a field `table:"-"` to hide it from output.
36
+ // Tag a field `table:"_"` to flatten its subfields.
31
37
func StructFieldNames (data interface {}) string {
32
38
v := reflect .ValueOf (data )
39
+ if v .Kind () == reflect .Ptr {
40
+ v = v .Elem ()
41
+ }
33
42
s := & strings.Builder {}
34
43
for i := 0 ; i < v .NumField (); i ++ {
35
44
field := v .Type ().Field (i )
36
45
if shouldHideField (field ) {
37
46
continue
38
47
}
48
+ if shouldFlatten (field ) {
49
+ fmt .Fprintf (s , "%s\t " , StructFieldNames (reflect .New (field .Type ).Interface ()))
50
+ continue
51
+ }
39
52
fmt .Fprintf (s , "%s\t " , fieldName (field ))
40
53
}
41
54
return s .String ()
@@ -45,6 +58,7 @@ func StructFieldNames(data interface{}) string {
45
58
// tabular format. Headers abide by the `table` struct tag.
46
59
//
47
60
// `table:"-"` omits the field and no tag defaults to the Go identifier.
61
+ // `table:"_"` flattens a fields subfields.
48
62
func WriteTable (length int , each func (i int ) interface {}) error {
49
63
if length < 1 {
50
64
return nil
@@ -73,6 +87,10 @@ func fieldName(f reflect.StructField) string {
73
87
return f .Name
74
88
}
75
89
90
+ func shouldFlatten (f reflect.StructField ) bool {
91
+ return f .Tag .Get (structFieldTagKey ) == "_"
92
+ }
93
+
76
94
func shouldHideField (f reflect.StructField ) bool {
77
95
return f .Tag .Get (structFieldTagKey ) == "-"
78
96
}
0 commit comments