Commit 59847321 authored by Russ Cox's avatar Russ Cox

reflect: better error for walking through nil embedded struct pointer

The old error was "call of reflect.Value.Field on ptr Value".

http://play.golang.org/p/Zm-ZbQaPeR

LGTM=r
R=golang-codereviews, r
CC=golang-codereviews
https://golang.org/cl/67020043
parent 4fb19d6a
......@@ -15,6 +15,7 @@ import (
. "reflect"
"runtime"
"sort"
"strings"
"sync"
"testing"
"time"
......@@ -3692,3 +3693,26 @@ func TestBigZero(t *testing.T) {
}
}
}
func TestFieldByIndexNil(t *testing.T) {
type P struct {
F int
}
type T struct {
*P
}
v := ValueOf(T{})
v.FieldByName("P") // should be fine
defer func() {
if err := recover(); err == nil {
t.Fatalf("no error")
} else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
}
}()
v.FieldByName("F") // should panic
t.Fatalf("did not panic")
}
......@@ -889,7 +889,10 @@ func (v Value) FieldByIndex(index []int) Value {
v.mustBe(Struct)
for i, x := range index {
if i > 0 {
if v.Kind() == Ptr && v.Elem().Kind() == Struct {
if v.Kind() == Ptr && v.typ.Elem().Kind() == Struct {
if v.IsNil() {
panic("reflect: indirection through nil pointer to embedded struct")
}
v = v.Elem()
}
}
......
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