1
0
mirror of https://github.com/golang/go synced 2024-11-23 05:50:05 -07:00

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
This commit is contained in:
Russ Cox 2014-02-21 13:51:22 -05:00
parent 4fb19d6a19
commit 59847321a7
2 changed files with 28 additions and 1 deletions

View File

@ -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")
}

View File

@ -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()
}
}