From e5cf5ca324f16b2a39f7a3239be6187904c43a13 Mon Sep 17 00:00:00 2001 From: Darshan Shaligram Date: Mon, 28 Sep 2015 10:54:29 -0400 Subject: [PATCH 1/2] Test for map with struct pointer value unmarshal. (This panics.) --- yaml_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/yaml_test.go b/yaml_test.go index 0ae0954..505af45 100644 --- a/yaml_test.go +++ b/yaml_test.go @@ -88,6 +88,22 @@ func TestUnmarshal(t *testing.T) { s4 := UnmarshalStringMap{} e4 := UnmarshalStringMap{map[string]string{"b": "1"}} unmarshal(t, y, &s4, &e4) + + y = []byte(` +a: + name: TestA +b: + name: TestB +`) + type NamedThing struct { + Name string `json:"name"` + } + s5 := map[string]*NamedThing{} + e5 := map[string]*NamedThing{ + "a": &NamedThing{Name: "TestA"}, + "b": &NamedThing{Name: "TestB"}, + } + unmarshal(t, y, &s5, &e5) } func unmarshal(t *testing.T, y []byte, s, e interface{}) { From e9369f63027b0fddc9ce405cdab63daa3cb08a32 Mon Sep 17 00:00:00 2001 From: Darshan Shaligram Date: Mon, 28 Sep 2015 10:49:05 -0400 Subject: [PATCH 2/2] Fix map unmarshal with struct pointer values This fixes a panic when unmarshaling YAML where the values of a map are pointers to structs. --- fields.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/fields.go b/fields.go index 0bd3c2b..5860074 100644 --- a/fields.go +++ b/fields.go @@ -45,7 +45,11 @@ func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.Te break } if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) + if v.CanSet() { + v.Set(reflect.New(v.Type().Elem())) + } else { + v = reflect.New(v.Type().Elem()) + } } if v.Type().NumMethod() > 0 { if u, ok := v.Interface().(json.Unmarshaler); ok {