to avoid a crash on a nil pointer as an embedded field.
Fixes #48215
Change-Id: I214faa6e3cf08cdec1c01035e4bbca0900c6a408
Reviewed-on: https://go-review.googlesource.com/c/go/+/357963
Trust: Rob Pike <r@golang.org>
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
case reflect.Struct:
tField, ok := receiver.Type().FieldByName(fieldName)
if ok {
- field := receiver.FieldByIndex(tField.Index)
+ field, err := receiver.FieldByIndexErr(tField.Index)
if !tField.IsExported() {
s.errorf("%s is an unexported field of struct type %s", fieldName, typ)
}
+ if err != nil {
+ s.errorf("%v", err)
+ }
// If it's a function, we must call it.
if hasArgs {
s.errorf("%s has arguments but cannot be invoked as function", fieldName)
wg.Wait()
}
+
+// Issue 48215: embedded nil pointer causes panic.
+// Fixed by adding FieldByIndexErr to the reflect package.
+func TestIssue48215(t *testing.T) {
+ type A struct {
+ S string
+ }
+ type B struct {
+ *A
+ }
+ tmpl, err := New("").Parse(`{{ .S }}`)
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = tmpl.Execute(io.Discard, B{})
+ // We expect an error, not a panic.
+ if err == nil {
+ t.Fatal("did not get error for nil embedded struct")
+ }
+ if !strings.Contains(err.Error(), "reflect: indirection through nil pointer to embedded struct field A") {
+ t.Fatal(err)
+ }
+}