Commit 24ee7f79 authored by Rob Pike's avatar Rob Pike

%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
parent d5248c4a
......@@ -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"},
......
......@@ -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 {
......
......@@ -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 {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment