Skip to content

Commit 2ecaaf1

Browse files
committed
fmt: always handle special methods if print operand is a reflect.Value
Check for and call the special printing and format methods such as String at printing depth 0 when printing the concrete value of a reflect.Value. Fixes: #16015 Change-Id: I23bd2927255b60924e5558321e98dd4a95e11c4c Reviewed-on: https://go-review.googlesource.com/30753 Reviewed-by: Russ Cox <[email protected]> Run-TryBot: Martin Möhrmann <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent faf882d commit 2ecaaf1

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

src/fmt/fmt_test.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,10 @@ var fmtTests = []struct {
605605
{"%x", I(23), `3c32333e`},
606606
{"%#x", I(23), `0x3c32333e`},
607607
{"%# x", I(23), `0x3c 0x32 0x33 0x3e`},
608-
{"%d", I(23), `23`}, // Stringer applies only to string formats.
608+
// Stringer applies only to string formats.
609+
{"%d", I(23), `23`},
610+
// Stringer applies to the extracted value.
611+
{"%s", reflect.ValueOf(I(23)), `<23>`},
609612

610613
// go syntax
611614
{"%#v", A{1, 2, "a", []int{1, 2}}, `fmt_test.A{i:1, j:0x2, s:"a", x:[]int{1, 2}}`},

src/fmt/print.go

+8
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,14 @@ func (p *pp) printArg(arg interface{}, verb rune) {
659659
case []byte:
660660
p.fmtBytes(f, verb, "[]byte")
661661
case reflect.Value:
662+
// Handle extractable values with special methods
663+
// since printValue does not handle them at depth 0.
664+
if f.IsValid() && f.CanInterface() {
665+
p.arg = f.Interface()
666+
if p.handleMethods(verb) {
667+
return
668+
}
669+
}
662670
p.printValue(f, verb, 0)
663671
default:
664672
// If the type is not simple, it might have methods.

0 commit comments

Comments
 (0)