Handle anonymous structs (#281)
Handle anonymous structs during Unmarshal. Fixes #279
This commit is contained in:
committed by
Thomas Pelletier
parent
728039f679
commit
dba45d427f
@@ -604,6 +604,15 @@ func (d *Decoder) valueFromTree(mtype reflect.Type, tval *Tree) (reflect.Value,
|
||||
}
|
||||
mval.Field(i).Set(reflect.ValueOf(val))
|
||||
}
|
||||
|
||||
// save the old behavior above and try to check anonymous structs
|
||||
if !found && opts.defaultValue == "" && mtypef.Anonymous && mtypef.Type.Kind() == reflect.Struct {
|
||||
v, err := d.valueFromTree(mtypef.Type, tval)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
mval.Field(i).Set(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
case reflect.Map:
|
||||
|
||||
@@ -1417,3 +1417,46 @@ func TestUnmarshalDefaultFailureUnsupported(t *testing.T) {
|
||||
t.Fatal("should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalNestedAnonymousStructs(t *testing.T) {
|
||||
type Nested struct {
|
||||
Value string `toml:"nested_field"`
|
||||
}
|
||||
type Deep struct {
|
||||
Nested
|
||||
}
|
||||
type Document struct {
|
||||
Deep
|
||||
Value string `toml:"own_field"`
|
||||
}
|
||||
|
||||
var doc Document
|
||||
|
||||
err := Unmarshal([]byte(`nested_field = "nested value"`+"\n"+`own_field = "own value"`), &doc)
|
||||
if err != nil {
|
||||
t.Fatal("should not error")
|
||||
}
|
||||
if doc.Value != "own value" || doc.Nested.Value != "nested value" {
|
||||
t.Fatal("unexpected values")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmarshalNestedAnonymousStructs_Controversial(t *testing.T) {
|
||||
type Nested struct {
|
||||
Value string `toml:"nested"`
|
||||
}
|
||||
type Deep struct {
|
||||
Nested
|
||||
}
|
||||
type Document struct {
|
||||
Deep
|
||||
Value string `toml:"own"`
|
||||
}
|
||||
|
||||
var doc Document
|
||||
|
||||
err := Unmarshal([]byte(`nested = "nested value"`+"\n"+`own = "own value"`), &doc)
|
||||
if err == nil {
|
||||
t.Fatal("should error")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user