1
0
mirror of https://github.com/golang/go synced 2024-11-25 01:27:56 -07:00

exp/template: don't panic on range of nil interface

This avoids a non-obvious panic when range is used on a
nil interface, and fixes it by behaving as if the range
was empty.

The new behavior is equivalent to the outcome of iterating
on a nil map or slice, and is useful because it allows
generic structures such as used in json (map[string]interface{})
to behave correctly if a key generally set to a list or map
isn't present.

R=golang-dev, r, gustavo
CC=golang-dev
https://golang.org/cl/4876046
This commit is contained in:
Gustavo Niemeyer 2011-08-15 00:22:28 -03:00
parent 8a439334ad
commit e3f3a5411a
2 changed files with 4 additions and 1 deletions

View File

@ -233,8 +233,10 @@ func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
s.pop(mark)
}
return
case reflect.Invalid:
break // An invalid value is likely a nil map, etc. and acts like an empty map.
default:
s.errorf("range can't iterate over value of type %T", val.Interface())
s.errorf("range can't iterate over %v", val)
}
if r.ElseList != nil {
s.walk(dot, r.ElseList)

View File

@ -372,6 +372,7 @@ var execTests = []execTest{
{"range map else", "{{range .MSI | .MSort}}-{{.}}-{{else}}EMPTY{{end}}", "-one--three--two-", tVal, true},
{"range empty map else", "{{range .MSIEmpty}}-{{.}}-{{else}}EMPTY{{end}}", "EMPTY", tVal, true},
{"range empty interface", "{{range .Empty3}}-{{.}}-{{else}}EMPTY{{end}}", "-7--8-", tVal, true},
{"range empty nil", "{{range .Empty0}}-{{.}}-{{end}}", "", tVal, true},
{"range $x SI", "{{range $x := .SI}}<{{$x}}>{{end}}", "<3><4><5>", tVal, true},
{"range $x $y SI", "{{range $x, $y := .SI}}<{{$x}}={{$y}}>{{end}}", "<0=3><1=4><2=5>", tVal, true},
{"range $x MSIone", "{{range $x := .MSIone}}<{{$x}}>{{end}}", "<1>", tVal, true},