Commit ce274339 authored by Rob Pike's avatar Rob Pike

text/template: fix bug in map indexing

If the key is not present, return value of the type of the element
not the type of the key. Also fix a test that should have caught this case.

Fixes #3850.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/6405078
parent 7b73251d
...@@ -390,7 +390,7 @@ var execTests = []execTest{ ...@@ -390,7 +390,7 @@ var execTests = []execTest{
{"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false}, {"slice[WRONG]", "{{index .SI `hello`}}", "", tVal, false},
{"map[one]", "{{index .MSI `one`}}", "1", tVal, true}, {"map[one]", "{{index .MSI `one`}}", "1", tVal, true},
{"map[two]", "{{index .MSI `two`}}", "2", tVal, true}, {"map[two]", "{{index .MSI `two`}}", "2", tVal, true},
{"map[NO]", "{{index .MSI `XXX`}}", "", tVal, true}, {"map[NO]", "{{index .MSI `XXX`}}", "0", tVal, true},
{"map[WRONG]", "{{index .MSI 10}}", "", tVal, false}, {"map[WRONG]", "{{index .MSI 10}}", "", tVal, false},
{"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true}, {"double index", "{{index .SMSI 1 `eleven`}}", "11", tVal, true},
......
...@@ -128,7 +128,7 @@ func index(item interface{}, indices ...interface{}) (interface{}, error) { ...@@ -128,7 +128,7 @@ func index(item interface{}, indices ...interface{}) (interface{}, error) {
if x := v.MapIndex(index); x.IsValid() { if x := v.MapIndex(index); x.IsValid() {
v = x v = x
} else { } else {
v = reflect.Zero(v.Type().Key()) v = reflect.Zero(v.Type().Elem())
} }
default: default:
return nil, fmt.Errorf("can't index item of type %s", index.Type()) return nil, fmt.Errorf("can't index item of type %s", index.Type())
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment