From 39fcca60cb5a13d2836d5d92cf1ed9aea07f6366 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Fri, 4 Nov 2011 23:45:38 +1100 Subject: [PATCH] template: format error with pointer receiver. This is a continuation of 982d70c6d5d6. R=golang-dev, rsc CC=golang-dev https://golang.org/cl/5348042 --- src/pkg/text/template/exec.go | 2 +- src/pkg/text/template/exec_test.go | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/pkg/text/template/exec.go b/src/pkg/text/template/exec.go index 540fb72c8e8..8ebd52bf3f8 100644 --- a/src/pkg/text/template/exec.go +++ b/src/pkg/text/template/exec.go @@ -660,7 +660,7 @@ func (s *state) printValue(n parse.Node, v reflect.Value) { } if !v.Type().Implements(errorType) && !v.Type().Implements(fmtStringerType) { - if v.CanAddr() && reflect.PtrTo(v.Type()).Implements(fmtStringerType) { + if v.CanAddr() && (reflect.PtrTo(v.Type()).Implements(errorType) || reflect.PtrTo(v.Type()).Implements(fmtStringerType)) { v = v.Addr() } else { switch v.Kind() { diff --git a/src/pkg/text/template/exec_test.go b/src/pkg/text/template/exec_test.go index 2199e440bcc..57216676410 100644 --- a/src/pkg/text/template/exec_test.go +++ b/src/pkg/text/template/exec_test.go @@ -32,6 +32,9 @@ type T struct { // Struct with String method. V0 V V1, V2 *V + // Struct with Error method. + W0 W + W1, W2 *W // Slices SI []int SIEmpty []int @@ -77,6 +80,17 @@ func (v *V) String() string { return fmt.Sprintf("<%d>", v.j) } +type W struct { + k int +} + +func (w *W) Error() string { + if w == nil { + return "nilW" + } + return fmt.Sprintf("[%d]", w.k) +} + var tVal = &T{ True: true, I: 17, @@ -85,6 +99,8 @@ var tVal = &T{ U: &U{"v"}, V0: V{6666}, V1: &V{7777}, // leave V2 as nil + W0: W{888}, + W1: &W{999}, // leave W2 as nil SI: []int{3, 4, 5}, SB: []bool{true, false}, MSI: map[string]int{"one": 1, "two": 2, "three": 3}, @@ -251,6 +267,11 @@ var execTests = []execTest{ {"&V{7777}.String()", "-{{.V1}}-", "-<7777>-", tVal, true}, {"(*V)(nil).String()", "-{{.V2}}-", "-nilV-", tVal, true}, + // Type with Error method. + {"W{888}.Error()", "-{{.W0}}-", "-[888]-", tVal, true}, + {"&W{999}.Error()", "-{{.W1}}-", "-[999]-", tVal, true}, + {"(*W)(nil).Error()", "-{{.W2}}-", "-nilW-", tVal, true}, + // Pointers. {"*int", "{{.PI}}", "23", tVal, true}, {"*[]int", "{{.PSI}}", "[21 22 23]", tVal, true},