Просмотр исходного кода

Fix map initialization.

R=rog
CC=
https://codereview.appspot.com/5503044
Gustavo Niemeyer 14 лет назад
Родитель
Сommit
7002636de4
2 измененных файлов с 10 добавлено и 13 удалено
  1. 6 3
      decode.go
  2. 4 10
      decode_test.go

+ 6 - 3
decode.go

@@ -213,9 +213,9 @@ func newDecoder() *decoder {
 //
 // It's a slightly convoluted case to handle properly:
 //
-// - Nil pointers should be zeroed out, unless being set to nil
-// - We don't know at this point yet what's the value to SetYAML() with.
-// - We can't separate pointer deref/init and setter checking, because
+// - nil pointers should be initialized, unless being set to nil
+// - we don't know at this point yet what's the value to SetYAML() with.
+// - we can't separate pointer deref/init and setter checking, because
 //   a setter may be found while going down a pointer chain.
 //
 // Thus, here is how it takes care of it:
@@ -421,6 +421,9 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) {
 	kt := outt.Key()
 	et := outt.Elem()
 
+	if out.IsNil() {
+		out.Set(reflect.MakeMap(outt))
+	}
 	l := len(n.children)
 	for i := 0; i < l; i += 2 {
 		k := reflect.New(kt).Elem()

+ 4 - 10
decode_test.go

@@ -81,16 +81,10 @@ var unmarshalTests = []struct {
 
 	// Structs and type conversions.
 	{"hello: world", &struct{ Hello string }{"world"}},
-	{"a: {b: c}", &struct {
-		A struct {
-			B string
-		}
-	}{struct{ B string }{"c"}}},
-	{"a: {b: c}", &struct {
-		A *struct {
-			B string
-		}
-	}{&struct{ B string }{"c"}}},
+	{"a: {b: c}", &struct{ A struct{ B string } }{struct{ B string }{"c"}}},
+	{"a: {b: c}", &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}},
+	{"a: {b: c}", &struct{ A map[string]string }{map[string]string{"b": "c"}}},
+	{"a: {b: c}", &struct{ A *map[string]string }{&map[string]string{"b": "c"}}},
 	{"a: 1", &struct{ A int }{1}},
 	{"a: [1, 2]", &struct{ A []int }{[]int{1, 2}}},
 	{"a: 1", &struct{ B int }{0}},