Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Only consider pointer to structs when checking for embedded fields #161

Merged
merged 1 commit into from Dec 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion funk_test.go
Expand Up @@ -129,8 +129,14 @@ type EmbeddedStruct struct {
EmbeddedField *string
}

type RootStruct struct {
type RootStructPointer struct {
*EmbeddedStruct

RootField *string
}

type RootStructNotPointer struct {
EmbeddedStruct

RootField *string
}
13 changes: 3 additions & 10 deletions retrieve.go
Expand Up @@ -110,14 +110,11 @@ func isNilIndirection(v reflect.Value, name string) bool {
vType := v.Type()
for i := 0; i < vType.NumField(); i++ {
field := vType.Field(i)
if !isEmbeddedStructField(field) {
if !isEmbeddedStructPointerField(field) {
return false
}

fieldType := field.Type
if fieldType.Kind() == reflect.Ptr {
fieldType = field.Type.Elem()
}
fieldType := field.Type.Elem()

_, found := fieldType.FieldByName(name)
if found {
Expand All @@ -128,14 +125,10 @@ func isNilIndirection(v reflect.Value, name string) bool {
return false
}

func isEmbeddedStructField(field reflect.StructField) bool {
func isEmbeddedStructPointerField(field reflect.StructField) bool {
if !field.Anonymous {
return false
}

if field.Type.Kind() == reflect.Struct {
return true
}

return field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct
}
11 changes: 9 additions & 2 deletions retrieve_test.go
Expand Up @@ -102,10 +102,17 @@ func TestGetOrElse(t *testing.T) {
})
}

func TestEmbeddedStruct(t *testing.T) {
func TestEmbeddedStructPointer(t *testing.T) {
is := assert.New(t)

root := RootStruct{}
root := RootStructPointer{}
is.Equal(Get(root, "EmbeddedField"), nil)
is.Equal(Get(root, "EmbeddedStruct.EmbeddedField"), nil)
}

func TestEmbeddedStructNotPointer(t *testing.T) {
is := assert.New(t)

root := RootStructNotPointer{}
is.Equal(Get(root, "EmbeddedField"), nil)
}