]> Cypherpunks repositories - gostls13.git/commitdiff
exp/template: make index function on maps return zero value when key not present.
authorRoger Peppe <rogpeppe@gmail.com>
Mon, 1 Aug 2011 16:03:35 +0000 (09:03 -0700)
committerRob Pike <r@golang.org>
Mon, 1 Aug 2011 16:03:35 +0000 (09:03 -0700)
R=r
CC=golang-dev
https://golang.org/cl/4808065

src/pkg/exp/template/exec_test.go
src/pkg/exp/template/funcs.go

index ed27e71223500cbbdd43f64c8285b4903350c47f..4a13825bdb579ad910ddae111ea32de30405ce6f 100644 (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},
 
index 58b2bafd843e8dcf6cc11e1c46266625f1f5a0d8..1de44fcb2c6cba040037d2b20746d35fff4b4dbc 100644 (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())