]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: better error for walking through nil embedded struct pointer
authorRuss Cox <rsc@golang.org>
Fri, 21 Feb 2014 18:51:22 +0000 (13:51 -0500)
committerRuss Cox <rsc@golang.org>
Fri, 21 Feb 2014 18:51:22 +0000 (13:51 -0500)
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

src/pkg/reflect/all_test.go
src/pkg/reflect/value.go

index 23e4e235f262d12643176030773883c90e9fffa3..c1f95d6049cee3bc39ee03b40955f7ec15c78a31 100644 (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")
+}
index 1edb1f04659b340cd1c1bbcf3ae020daf3283020..fba0e1ef68c2ed2e3915908c5a12beddc64ddedc 100644 (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()
                        }
                }