Skip to content

Commit ba76560

Browse files
committed
[release-branch.go1] fmt: set p.field before nil check
««« backport 5f13e0662e38 fmt: set p.field before nil check Fixes #3752. R=golang-dev, rsc CC=golang-dev https://golang.org/cl/6331062 »»»
1 parent 025324f commit ba76560

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/pkg/fmt/fmt_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,3 +842,15 @@ func TestIsSpace(t *testing.T) {
842842
}
843843
}
844844
}
845+
846+
func TestNilDoesNotBecomeTyped(t *testing.T) {
847+
type A struct{}
848+
type B struct{}
849+
var a *A = nil
850+
var b B = B{}
851+
got := Sprintf("%s %s %s %s %s", nil, a, nil, b, nil)
852+
const expect = "%!s(<nil>) %!s(*fmt_test.A=<nil>) %!s(<nil>) {} %!s(<nil>)"
853+
if got != expect {
854+
t.Errorf("expected:\n\t%q\ngot:\n\t%q", expect, got)
855+
}
856+
}

src/pkg/fmt/print.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,9 @@ func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString
712712
}
713713

714714
func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
715+
p.field = field
716+
p.value = reflect.Value{}
717+
715718
if field == nil {
716719
if verb == 'T' || verb == 'v' {
717720
p.buf.Write(nilAngleBytes)
@@ -721,8 +724,6 @@ func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth
721724
return false
722725
}
723726

724-
p.field = field
725-
p.value = reflect.Value{}
726727
// Special processing considerations.
727728
// %T (the value's type) and %p (its address) are special; we always do them first.
728729
switch verb {

0 commit comments

Comments
 (0)