Test a couple error cases
diff --git a/mapstructure.go b/mapstructure.go index eaf505d..d4a49ed 100644 --- a/mapstructure.go +++ b/mapstructure.go
@@ -9,7 +9,12 @@ // MapToStruct takes a map and uses reflection to convert it into the // given Go native structure. val must be a pointer to a struct. func MapToStruct(m map[string]interface{}, rawVal interface{}) error { - val := reflect.ValueOf(rawVal).Elem() + val := reflect.ValueOf(rawVal) + if val.Kind() != reflect.Ptr { + return errors.New("val must be a pointer") + } + + val = val.Elem() if !val.CanAddr() { return errors.New("val must be addressable (a pointer)") }
diff --git a/mapstructure_test.go b/mapstructure_test.go index 593ba06..ec47e70 100644 --- a/mapstructure_test.go +++ b/mapstructure_test.go
@@ -36,3 +36,32 @@ t.Errorf("vbool value should be true: %#v", result.Vbool) } } + +func TestNonPtrValue(t *testing.T) { + t.Parallel() + + err := MapToStruct(map[string]interface{}{}, Basic{}) + if err == nil { + t.Error("error should exist") + t.FailNow() + } + + if err.Error() != "val must be a pointer" { + t.Errorf("got unexpected error: %s", err) + } +} + +func TestNontStructValue(t *testing.T) { + t.Parallel() + + result := 42 + err := MapToStruct(map[string]interface{}{}, &result) + if err == nil { + t.Error("error should exist") + t.FailNow() + } + + if err.Error() != "val must be an addressable struct" { + t.Errorf("got unexpected error: %s", err) + } +}