From e77e7bb842499e58a9f4b53631bb3ce9c72d6d5a Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 23 Jun 2020 09:09:46 +0800 Subject: [PATCH] Fix nested embedded field with pointer, close #3071 --- schema/field.go | 12 +++++++----- tests/embedded_struct_test.go | 5 +++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/schema/field.go b/schema/field.go index 737f56c4..a8328367 100644 --- a/schema/field.go +++ b/schema/field.go @@ -397,11 +397,11 @@ func (field *Field) setupValuerAndSetter() { default: field.ReflectValueOf = func(value reflect.Value) reflect.Value { v := reflect.Indirect(value) - for _, idx := range field.StructField.Index { - if idx >= 0 { - v = v.Field(idx) + for idx, fieldIdx := range field.StructField.Index { + if fieldIdx >= 0 { + v = v.Field(fieldIdx) } else { - v = v.Field(-idx - 1) + v = v.Field(-fieldIdx - 1) } if v.Kind() == reflect.Ptr { @@ -436,7 +436,9 @@ func (field *Field) setupValuerAndSetter() { fieldValue := field.ReflectValueOf(value) if reflectV.Type().AssignableTo(field.FieldType.Elem()) { - if fieldValue.IsNil() { + if !fieldValue.IsValid() { + fieldValue = reflect.New(field.FieldType.Elem()) + } else if fieldValue.IsNil() { fieldValue.Set(reflect.New(field.FieldType.Elem())) } fieldValue.Elem().Set(reflectV) diff --git a/tests/embedded_struct_test.go b/tests/embedded_struct_test.go index 8536b605..7f40a0a4 100644 --- a/tests/embedded_struct_test.go +++ b/tests/embedded_struct_test.go @@ -10,10 +10,15 @@ import ( ) func TestEmbeddedStruct(t *testing.T) { + type ReadOnly struct { + ReadOnly *bool + } + type BasePost struct { Id int64 Title string URL string + ReadOnly } type Author struct {