1
0
mirror of https://github.com/golang/go synced 2024-11-21 13:14:40 -07:00

%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
This commit is contained in:
Rob Pike 2010-02-25 17:29:37 +11:00
parent d5248c4a96
commit 24ee7f799c
3 changed files with 11 additions and 1 deletions

View File

@ -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"},

View File

@ -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 {

View File

@ -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 {