summaryrefslogtreecommitdiff
path: root/src/pkg/fmt
diff options
context:
space:
mode:
authorRob Pike <r@golang.org>2010-02-25 17:29:37 +1100
committerRob Pike <r@golang.org>2010-02-25 17:29:37 +1100
commitb5c34b76a8f0b7f161b38ba7c1161659c9d6a805 (patch)
tree2306783ef937875a561f9d5e2f28abc01477c09e /src/pkg/fmt
parente9953c87424e88d8017b33f0576be7e482b3a28f (diff)
downloadgolang-b5c34b76a8f0b7f161b38ba7c1161659c9d6a805.tar.gz
%q in fmt: if the object is a Stringer, use String() to get the value to quote.
R=rsc CC=golang-dev http://codereview.appspot.com/224051
Diffstat (limited to 'src/pkg/fmt')
-rw-r--r--src/pkg/fmt/fmt_test.go3
-rw-r--r--src/pkg/fmt/print.go7
-rw-r--r--src/pkg/fmt/stringer_test.go2
3 files changed, 11 insertions, 1 deletions
diff --git a/src/pkg/fmt/fmt_test.go b/src/pkg/fmt/fmt_test.go
index 9fdf0ddb3..139036eb3 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 b2af9da1c..ffe187a31 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 369f610b2..e4e29bebb 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 {