Skip to content

Commit

Permalink
Add support for nested interface{} unmarshal (#335)
Browse files Browse the repository at this point in the history
Co-authored-by: jlwang <[email protected]>

Fixes #331
  • Loading branch information
jinleiw authored Mar 16, 2020
1 parent 3503483 commit ad60b7e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
10 changes: 10 additions & 0 deletions marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,16 @@ func (d *Decoder) valueFromToml(mtype reflect.Type, tval interface{}, mval1 *ref
if isTree(mtype) {
return d.valueFromTree(mtype, t, mval11)
}

if mtype.Kind() == reflect.Interface &&
mval1.Elem().Kind() == reflect.Ptr &&
reflect.TypeOf(mval1.Elem()).Kind() == reflect.Struct {

mval111 := reflect.ValueOf(mval1.Interface()).Elem()
mval11 = &mval111
return d.valueFromTree(reflect.TypeOf(mval1.Interface()).Elem(), t, mval11)
}

return reflect.ValueOf(nil), fmt.Errorf("Can't convert %v(%T) to a tree", tval, tval)
case []*Tree:
if isTreeSequence(mtype) {
Expand Down
38 changes: 38 additions & 0 deletions marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,44 @@ var mashalOrderPreserveMapToml = []byte(`title = "TOML Marshal Testing"
j9 = "10"
`)

type Conf struct {
Name string
Age int
Inter interface{}
}

type NestedStruct struct {
FirstName string
LastName string
Age int
}

var doc = []byte(`Name = "rui"
Age = 18
[Inter]
FirstName = "wang"
LastName = "jl"
Age = 100`)

func TestInterface(t *testing.T) {
var config Conf
config.Inter = &NestedStruct{}
err := Unmarshal(doc, &config)
expected := Conf{
Name: "rui",
Age: 18,
Inter: NestedStruct{
FirstName: "wang",
LastName: "jl",
Age: 100,
},
}
if err != nil || !reflect.DeepEqual(config, expected) {
t.Errorf("Bad unmarshal: expected %v, got %v", expected, config)
}
}

func TestBasicMarshal(t *testing.T) {
result, err := Marshal(basicTestData)
if err != nil {
Expand Down

0 comments on commit ad60b7e

Please sign in to comment.