From 24ee7f799c734cf07b98bab672f5feb4ad0c6862 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Thu, 25 Feb 2010 17:29:37 +1100 Subject: [PATCH] %q in fmt: if the object is a Stringer, use String() to get the value to quote. R=rsc CC=golang-dev https://golang.org/cl/224051 --- src/pkg/fmt/fmt_test.go | 3 +++ src/pkg/fmt/print.go | 7 +++++++ src/pkg/fmt/stringer_test.go | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/pkg/fmt/fmt_test.go b/src/pkg/fmt/fmt_test.go index 9fdf0ddb36..139036eb37 100644 --- a/src/pkg/fmt/fmt_test.go +++ b/src/pkg/fmt/fmt_test.go @@ -217,6 +217,9 @@ var fmttests = []fmtTest{ fmtTest{"%+v", B{1, 2}, `{i:<1> j:2}`}, fmtTest{"%+v", C{1, B{2, 3}}, `{i:1 B:{i:<2> j:3}}`}, + // q on Stringable items + fmtTest{"%q", I(23), `"<23>"`}, + // %p on non-pointers fmtTest{"%p", make(chan int), "PTR"}, fmtTest{"%p", make(map[int]int), "PTR"}, diff --git a/src/pkg/fmt/print.go b/src/pkg/fmt/print.go index b2af9da1cb..ffe187a313 100644 --- a/src/pkg/fmt/print.go +++ b/src/pkg/fmt/print.go @@ -912,6 +912,13 @@ func (p *pp) doprintf(format string, a []interface{}) { goto badtype } case 'q': + if field != nil { + // if object implements String, use the result. + if stringer, ok := field.(Stringer); ok { + p.fmt.fmt_q(stringer.String()) + break + } + } if v, ok := getString(field); ok { p.fmt.fmt_q(v) } else { diff --git a/src/pkg/fmt/stringer_test.go b/src/pkg/fmt/stringer_test.go index 369f610b2b..e4e29bebb8 100644 --- a/src/pkg/fmt/stringer_test.go +++ b/src/pkg/fmt/stringer_test.go @@ -41,7 +41,7 @@ func (v TF) String() string { return Sprintf("F: %f", v) } func (v TF32) String() string { return Sprintf("F32: %f", v) } func (v TF64) String() string { return Sprintf("F64: %f", v) } func (v TB) String() string { return Sprintf("B: %t", v) } -func (v TS) String() string { return Sprintf("S: %q", v) } +func (v TS) String() string { return Sprintf("S: %q", string(v)) } func check(t *testing.T, got, want string) { if got != want {