mitchellh / mapstructure

Go library for decoding generic map values into native Go structures and vice versa.
https://gist.github.com/mitchellh/90029601268e59a29e64e55bab1c5bdc
MIT License
7.93k stars 677 forks source link

Decoding Struct to Map with Embedded pointer to Struct #267

Closed ghost closed 2 years ago

ghost commented 2 years ago

I'm trying to decode a struct into a map[string]interface{} using the RecursiveStructToMapHookFunc. If the struct contains an embedded struct, then per the first case in TestStructToMapHookFuncTabled we have

type b struct {
    TestKey string
}

type a struct {
    Sub b
}

testStruct := a{
    Sub: b{
        TestKey: "testval",
    },
}

testMap := map[string]interface{}{
    "Sub": map[string]interface{}{
        "TestKey": "testval",
    },
}

var result map[string]interface{}

d, _ := NewDecoder(&DecoderConfig{
    DecodeHook: RecursiveStructToMapHookFunc,
    Result:     &result,
})

and d.decode(testStruct) produces the equivalent of testMap. However, if we change the Sub field in struct a to be a pointer to a struct of type b, setup testStruct accordingly, and finally decode then the recursive decoding from struct to map does not apply.

type b struct {
    TestKey string
}

type a struct {
    Sub *b
}

testStruct := a{
    Sub: &b{
        TestKey: "testval",
    },
}

var result map[string]interface{}

d, _ := NewDecoder(&DecoderConfig{
    DecodeHook: RecursiveStructToMapHookFunc,
    Result:     &result,
})

Decode produces map[Sub:0xc000700010] or similar. I'm looking for a way to achieve the same result as testMap above, so essentially structs containing pointers to structs are treated as structs with embedded structs.

vlanse commented 2 years ago

Hope #271 will help

mitchellh commented 2 years ago

Fixed