Skip to content

Commit

Permalink
Add GoStringer support (kr#68)
Browse files Browse the repository at this point in the history
Print values using the `GoString()` method (from `fmt.GoStringer()`) if implemented.
  • Loading branch information
2opremio authored Aug 31, 2020
1 parent 3630c7d commit 59b4212
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
8 changes: 8 additions & 0 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,14 @@ func (p *printer) printValue(v reflect.Value, showType, quote bool) {
return
}

if v.IsValid() && v.CanInterface() {
i := v.Interface()
if goStringer, ok := i.(fmt.GoStringer); ok {
io.WriteString(p, goStringer.GoString())
return
}
}

switch v.Kind() {
case reflect.Bool:
p.printInline(v, v.Bool(), showType)
Expand Down
14 changes: 14 additions & 0 deletions formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,19 @@ func TestPassthrough(t *testing.T) {
}
}

type StructWithPrivateFields struct {
A string
b string
}

func NewStructWithPrivateFields(a string) StructWithPrivateFields {
return StructWithPrivateFields{a, "fixedb"}
}

func (s StructWithPrivateFields) GoString() string {
return fmt.Sprintf("NewStructWithPrivateFields(%q)", s.A)
}

var gosyntax = []test{
{nil, `nil`},
{"", `""`},
Expand All @@ -84,6 +97,7 @@ var gosyntax = []test{
`[]string{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"}`,
},
{F(5), "pretty.F(5)"},
{ NewStructWithPrivateFields("foo"), `NewStructWithPrivateFields("foo")`},
{
SA{&T{1, 2}, T{3, 4}},
`pretty.SA{
Expand Down

0 comments on commit 59b4212

Please sign in to comment.