Skip to content

Commit 10e4ceb

Browse files
author
Leon Huston
committed
add HideName option to printer
1 parent 17a3fb5 commit 10e4ceb

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

repr.go

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,12 @@ func Hide[T any]() Option {
105105
}
106106
}
107107

108+
func HideName(name string) Option {
109+
return func(o *Printer) {
110+
o.excludeNames[name] = true
111+
}
112+
}
113+
108114
// AlwaysIncludeType always includes explicit type information for each item.
109115
func AlwaysIncludeType() Option { return func(o *Printer) { o.alwaysIncludeType = true } }
110116

@@ -118,18 +124,20 @@ type Printer struct {
118124
alwaysIncludeType bool
119125
explicitTypes bool
120126
exclude map[reflect.Type]bool
127+
excludeNames map[string]bool
121128
w io.Writer
122129
useLiterals bool
123130
}
124131

125132
// New creates a new Printer on w with the given Options.
126133
func New(w io.Writer, options ...Option) *Printer {
127134
p := &Printer{
128-
w: w,
129-
indent: " ",
130-
omitEmpty: true,
131-
omitZero: true,
132-
exclude: map[reflect.Type]bool{},
135+
w: w,
136+
indent: " ",
137+
omitEmpty: true,
138+
omitZero: true,
139+
exclude: map[reflect.Type]bool{},
140+
excludeNames: map[string]bool{},
133141
}
134142
for _, option := range options {
135143
option(p)
@@ -280,6 +288,9 @@ func (p *Printer) reprValue(seen map[reflect.Value]bool, v reflect.Value, indent
280288
if p.exclude[t.Type] {
281289
continue
282290
}
291+
if p.excludeNames[t.Name] {
292+
continue
293+
}
283294
f := v.Field(i)
284295
ft := f.Type()
285296
// skip private fields

repr_test.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ func TestReprPrivateBytes(t *testing.T) {
278278
}
279279

280280
func TestReprAnyNumeric(t *testing.T) {
281-
var value = []any{float64(123)}
281+
value := []any{float64(123)}
282282
equal(t, "[]any{float64(123)}", String(value))
283283
}
284284

@@ -293,3 +293,12 @@ func TestScalarLiterals(t *testing.T) {
293293
d := time.Second
294294
equal(t, "time.Duration(1000000000)", String(d, ScalarLiterals()))
295295
}
296+
297+
func TestHideStructFieldsByName(t *testing.T) {
298+
actual := testStruct{
299+
S: "str",
300+
A: anotherStruct{A: []int{1}},
301+
}
302+
res := String(actual, HideName("A"))
303+
equal(t, `repr.testStruct{S: "str"}`, res)
304+
}

0 commit comments

Comments
 (0)