Skip to content

Commit 59b4212

Browse files
authored
Add GoStringer support (#68)
Print values using the `GoString()` method (from `fmt.GoStringer()`) if implemented.
1 parent 3630c7d commit 59b4212

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

formatter.go

+8
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,14 @@ func (p *printer) printValue(v reflect.Value, showType, quote bool) {
9898
return
9999
}
100100

101+
if v.IsValid() && v.CanInterface() {
102+
i := v.Interface()
103+
if goStringer, ok := i.(fmt.GoStringer); ok {
104+
io.WriteString(p, goStringer.GoString())
105+
return
106+
}
107+
}
108+
101109
switch v.Kind() {
102110
case reflect.Bool:
103111
p.printInline(v, v.Bool(), showType)

formatter_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,19 @@ func TestPassthrough(t *testing.T) {
6262
}
6363
}
6464

65+
type StructWithPrivateFields struct {
66+
A string
67+
b string
68+
}
69+
70+
func NewStructWithPrivateFields(a string) StructWithPrivateFields {
71+
return StructWithPrivateFields{a, "fixedb"}
72+
}
73+
74+
func (s StructWithPrivateFields) GoString() string {
75+
return fmt.Sprintf("NewStructWithPrivateFields(%q)", s.A)
76+
}
77+
6578
var gosyntax = []test{
6679
{nil, `nil`},
6780
{"", `""`},
@@ -84,6 +97,7 @@ var gosyntax = []test{
8497
`[]string{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"}`,
8598
},
8699
{F(5), "pretty.F(5)"},
100+
{ NewStructWithPrivateFields("foo"), `NewStructWithPrivateFields("foo")`},
87101
{
88102
SA{&T{1, 2}, T{3, 4}},
89103
`pretty.SA{

0 commit comments

Comments
 (0)