Skip to content

Commit

Permalink
feat: OmitEmpty() omits zero-length slices and maps
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Feb 19, 2024
1 parent 437c372 commit 3d05a48
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
5 changes: 4 additions & 1 deletion repr.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,11 +256,14 @@ func (p *Printer) reprValue(seen map[reflect.Value]bool, v reflect.Value, indent
continue
}
f := v.Field(i)
ft := f.Type()
// skip private fields
if p.ignorePrivate && !f.CanInterface() {
continue
}
if p.omitEmpty && f.IsZero() {
if p.omitEmpty && (f.IsZero() ||
ft.Kind() == reflect.Slice && f.Len() == 0 ||
ft.Kind() == reflect.Map && f.Len() == 0) {
continue
}
if previous && p.indent == "" {
Expand Down
11 changes: 10 additions & 1 deletion repr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ func TestReprEmptyArray(t *testing.T) {
equal(t, "[]string{}", String([]string{}, OmitEmpty(false)))
}

func TestReprEmptySliceMapFields(t *testing.T) {
v := struct {
S []string
M map[string]string
NZ []string
}{[]string{}, map[string]string{}, []string{"a", "b"}}
equal(t, `struct { S []string; M map[string]string; NZ []string }{NZ: []string{"a", "b"}}`, String(v, OmitEmpty(true)))
}

func TestReprStringArray(t *testing.T) {
equal(t, "[]string{\"a\", \"b\"}", String([]string{"a", "b"}))
}
Expand Down Expand Up @@ -174,7 +183,7 @@ type intSliceStruct struct{ f []int }
func TestReprEmptySliceStruct(t *testing.T) {
a := intSliceStruct{f: []int{}}
s := String(a)
equal(t, "repr.intSliceStruct{f: []int{}}", s)
equal(t, "repr.intSliceStruct{}", s)
}

func TestReprNilSliceStruct(t *testing.T) {
Expand Down

0 comments on commit 3d05a48

Please sign in to comment.