From 80f8b7660b8fe0461e88bbe600e145f7bbcdab8c Mon Sep 17 00:00:00 2001 From: Nicolas Bedos <33371440+nbedos@users.noreply.github.com> Date: Mon, 13 Jan 2020 15:39:27 +0100 Subject: [PATCH] Support default values for inner structs (#326) --- marshal.go | 4 ++-- marshal_test.go | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/marshal.go b/marshal.go index 2a6cfba..37d6bbd 100644 --- a/marshal.go +++ b/marshal.go @@ -624,8 +624,8 @@ func (d *Decoder) valueFromTree(mtype reflect.Type, tval *Tree, mval1 *reflect.V 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 { + // save the old behavior above and try to check structs + if !found && opts.defaultValue == "" && mtypef.Type.Kind() == reflect.Struct { v, err := d.valueFromTree(mtypef.Type, tval, nil) if err != nil { return v, err diff --git a/marshal_test.go b/marshal_test.go index 17a1418..793fce5 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -1483,12 +1483,20 @@ func TestUnmarshalCamelCaseKey(t *testing.T) { } func TestUnmarshalDefault(t *testing.T) { + type EmbeddedStruct struct { + StringField string `default:"c"` + } + var doc struct { StringField string `default:"a"` BoolField bool `default:"true"` IntField int `default:"1"` Int64Field int64 `default:"2"` Float64Field float64 `default:"3.1"` + NonEmbeddedStruct struct { + StringField string `default:"b"` + } + EmbeddedStruct } err := Unmarshal([]byte(``), &doc) @@ -1510,6 +1518,12 @@ func TestUnmarshalDefault(t *testing.T) { if doc.Float64Field != 3.1 { t.Errorf("Float64Field should be 3.1, not %f", doc.Float64Field) } + if doc.NonEmbeddedStruct.StringField != "b" { + t.Errorf("StringField should be \"b\", not %s", doc.NonEmbeddedStruct.StringField) + } + if doc.EmbeddedStruct.StringField != "c" { + t.Errorf("StringField should be \"c\", not %s", doc.EmbeddedStruct.StringField) + } } func TestUnmarshalDefaultFailureBool(t *testing.T) {