Skip to content

fix: recursively convert slices of structs when decoding to map - #211

Open
AdamMagued wants to merge 1 commit into
go-viper:mainfrom
AdamMagued:fix-slice-struct-pointers-deep-map
Open

AdamMagued wants to merge 1 commit into
go-viper:mainfrom
AdamMagued:fix-slice-struct-pointers-deep-map

Conversation

@AdamMagued

Copy link
Copy Markdown

When decoding a struct to a map with deep mapping enabled (either via the deep tag option or DecoderConfig.Deep), fields that are slices of pointers to structs (such as []*MyStruct) were not being converted to []map[string]any. Instead, the original []*MyStruct type was retained in the target map.

Root Cause

In decodeMapFromStruct, v.Type().Elem().Kind() was checked directly without dereferencing pointer types:

switch v.Type().Elem().Kind() {
case reflect.Struct:
    childType = reflect.TypeOf(map[string]any{})
default:
    childType = v.Type().Elem()
}

For slices of struct pointers, v.Type().Elem().Kind() is reflect.Ptr, which fell through to the default branch and preserved the pointer type rather than selecting map[string]any.

Solution

Dereference pointer indirection on v.Type().Elem() when determining childType so that both direct structs and struct pointer elements are handled recursively.

Testing

Added TestDecode_structPtrArrayDeepMap in mapstructure_test.go verifying conversion of []*SourceChild and *[]*SourceChild to []map[string]any via:

  • deep struct tag option
  • DecoderConfig.Deep = true
  • Slices containing nil pointer elements

Fixes #120

When decoding a struct to a map with deep mapping enabled (via the deep tag option or DecoderConfig.Deep), slices whose elements are pointers to structs (such as []*MyStruct) were not being converted to []map[string]any. In decodeMapFromStruct, v.Type().Elem().Kind() returned reflect.Ptr, causing childType to fall back to the pointer type rather than map[string]any.

Dereference pointer types on the slice element type when determining childType so that both slices of structs and slices of pointers to structs are recursively converted to maps.

Fixes go-viper#120
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

struct to map Conversion Does Not Recursively Process Slices of Structs

1 participant