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

exp/template: make index function on maps return zero value when key not present.

R=r
CC=golang-dev
https://golang.org/cl/4808065
This commit is contained in:
Roger Peppe 2011-08-01 09:03:35 -07:00 committed by Rob Pike
parent 5c5ce6d24d
commit 6ed27d4770
2 changed files with 5 additions and 4 deletions

View File

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

View File

@ -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())