diff options
author | Roger Peppe <rogpeppe@gmail.com> | 2011-08-01 09:03:35 -0700 |
---|---|---|
committer | Rob Pike <r@golang.org> | 2011-08-01 09:03:35 -0700 |
commit | 6ed27d4770c8141e31c665089772090117c32b97 (patch) | |
tree | 8bf415c01334d044f4b1cb18191e9c3a4ffbd875 | |
parent | 5c5ce6d24d766b47791cb4066748e8ef26ecae9a (diff) | |
download | go-6ed27d4770c8141e31c665089772090117c32b97.tar.gz go-6ed27d4770c8141e31c665089772090117c32b97.zip |
exp/template: make index function on maps return zero value when key not present.
R=r
CC=golang-dev
https://golang.org/cl/4808065
-rw-r--r-- | src/pkg/exp/template/exec_test.go | 2 | ||||
-rw-r--r-- | src/pkg/exp/template/funcs.go | 7 |
2 files changed, 5 insertions, 4 deletions
diff --git a/src/pkg/exp/template/exec_test.go b/src/pkg/exp/template/exec_test.go index ed27e71223..4a13825bdb 100644 --- a/src/pkg/exp/template/exec_test.go +++ b/src/pkg/exp/template/exec_test.go @@ -297,7 +297,7 @@ var execTests = []execTest{ {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false}, {"map[one]", "{{index .MSI `one`}}", "1", tVal, true}, {"map[two]", "{{index .MSI `two`}}", "2", tVal, true}, - {"map[NO]", "{{index .MSI `XXX`}}", "", tVal, false}, + {"map[NO]", "{{index .MSI `XXX`}}", "", tVal, true}, {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false}, {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true}, diff --git a/src/pkg/exp/template/funcs.go b/src/pkg/exp/template/funcs.go index 58b2bafd84..1de44fcb2c 100644 --- a/src/pkg/exp/template/funcs.go +++ b/src/pkg/exp/template/funcs.go @@ -109,9 +109,10 @@ func index(item interface{}, indices ...interface{}) (interface{}, os.Error) { if !index.Type().AssignableTo(v.Type().Key()) { return nil, fmt.Errorf("%s is not index type for %s", index.Type(), v.Type()) } - v = v.MapIndex(index) - if !v.IsValid() { - return nil, fmt.Errorf("index %v not present in map", index.Interface()) + if x := v.MapIndex(index); x.IsValid() { + v = x + } else { + v = reflect.Zero(v.Type().Key()) } default: return nil, fmt.Errorf("can't index item of type %s", index.Type()) |