When the input is nil, don't set the zero value
diff --git a/mapstructure.go b/mapstructure.go index 7b4b125..e7765be 100644 --- a/mapstructure.go +++ b/mapstructure.go
@@ -131,6 +131,11 @@ // Decodes an unknown data type into a specific reflection value. func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { + if data == nil { + // If the data is nil, then we don't set anything. + return nil + } + dataVal := reflect.ValueOf(data) if !dataVal.IsValid() { // If the data value is invalid, then we just set the value
diff --git a/mapstructure_test.go b/mapstructure_test.go index de2374c..3ac1dda 100644 --- a/mapstructure_test.go +++ b/mapstructure_test.go
@@ -2,6 +2,7 @@ import ( "reflect" + "sort" "testing" ) @@ -195,6 +196,24 @@ } } +func TestDecode_Nil(t *testing.T) { + t.Parallel() + + var input interface{} = nil + result := Basic{ + Vstring: "foo", + } + + err := Decode(input, &result) + if err != nil { + t.Fatalf("err: %s", err) + } + + if result.Vstring != "foo" { + t.Fatalf("bad: %#v", result.Vstring) + } +} + func TestDecode_NonStruct(t *testing.T) { t.Parallel() @@ -625,7 +644,9 @@ t.Fatalf("err: %s", err.Error()) } - expectedKeys := []string{"Vunique", "Vstring"} + expectedKeys := []string{"Vstring", "Vunique"} + + sort.Strings(md.Keys) if !reflect.DeepEqual(md.Keys, expectedKeys) { t.Fatalf("bad keys: %#v", md.Keys) }