If data is ever invalid, set val to zero value
diff --git a/mapstructure.go b/mapstructure.go
index 7533b2c..83676f2 100644
--- a/mapstructure.go
+++ b/mapstructure.go
@@ -53,6 +53,14 @@
// Decodes an unknown data type into a specific reflection value.
func decode(name string, data interface{}, val reflect.Value) error {
+ dataVal := reflect.ValueOf(data)
+ if !dataVal.IsValid() {
+ // If the data value is invalid, then we just set the value
+ // to be the zero value.
+ val.Set(reflect.Zero(val.Type()))
+ return nil
+ }
+
k := val.Kind()
// Some shortcuts because we treat all ints and uints the same way
@@ -89,12 +97,6 @@
// value to "data" of that type.
func decodeBasic(name string, data interface{}, val reflect.Value) error {
dataVal := reflect.ValueOf(data)
- if !dataVal.IsValid() {
- // If the data isn't valid (the zero type), then we set the
- // value to be the zero type of the field we want to set.
- dataVal = reflect.Zero(val.Type())
- }
-
dataValType := dataVal.Type()
if !dataValType.AssignableTo(val.Type()) {
return fmt.Errorf(
@@ -108,11 +110,6 @@
func decodeInt(name string, data interface{}, val reflect.Value) error {
dataVal := reflect.ValueOf(data)
- if !dataVal.IsValid() {
- // This should never happen
- panic("data is invalid")
- }
-
dataKind := dataVal.Kind()
if dataKind >= reflect.Int && dataKind <= reflect.Int64 {
dataKind = reflect.Int
diff --git a/mapstructure_bugs_test.go b/mapstructure_bugs_test.go
index 28a4940..05d7e3b 100644
--- a/mapstructure_bugs_test.go
+++ b/mapstructure_bugs_test.go
@@ -5,17 +5,21 @@
// GH-1
func TestDecode_NilValue(t *testing.T) {
input := map[string]interface{}{
- "vstring": nil,
+ "vfoo": nil,
+ "vother": nil,
}
- var result Basic
+ var result Map
err := Decode(input, &result)
if err != nil {
t.Fatalf("should not error: %s", err)
}
- if result.Vstring != "" {
- t.Fatalf("value should be default: %s", result.Vstring)
+ if result.Vfoo != "" {
+ t.Fatalf("value should be default: %s", result.Vfoo)
+ }
+
+ if result.Vother != nil {
+ t.Fatalf("Vother should be nil: %s", result.Vother)
}
}
-