Skip to content

Commit f15292f

Browse files
authored
Merge pull request mitchellh#127 from larstore/master
A map of len > 0 will now be converted to slice if a slice result is …
2 parents bb74f1d + a698288 commit f15292f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

mapstructure.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -762,6 +762,9 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value)
762762
val.Set(reflect.MakeSlice(sliceType, 0, 0))
763763
return nil
764764
}
765+
// Create slice of maps of other sizes
766+
return d.decodeSlice(name, []interface{}{data}, val)
767+
765768
case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8:
766769
return d.decodeSlice(name, []byte(dataVal.String()), val)
767770
// All other types we try to convert to the slice type

mapstructure_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,6 +1139,37 @@ func TestSliceOfStruct(t *testing.T) {
11391139
}
11401140
}
11411141

1142+
func TestSliceCornerCases(t *testing.T) {
1143+
t.Parallel()
1144+
1145+
// Input with a map with zero values
1146+
input := map[string]interface{}{}
1147+
var resultWeak []Basic
1148+
1149+
err := WeakDecode(input, &resultWeak)
1150+
if err != nil {
1151+
t.Fatalf("got unexpected error: %s", err)
1152+
}
1153+
1154+
if len(resultWeak) != 0 {
1155+
t.Errorf("length should be 0")
1156+
}
1157+
// Input with more values
1158+
input = map[string]interface{}{
1159+
"Vstring": "foo",
1160+
}
1161+
1162+
resultWeak = nil
1163+
err = WeakDecode(input, &resultWeak)
1164+
if err != nil {
1165+
t.Fatalf("got unexpected error: %s", err)
1166+
}
1167+
1168+
if resultWeak[0].Vstring != "foo" {
1169+
t.Errorf("value does not match")
1170+
}
1171+
}
1172+
11421173
func TestSliceToMap(t *testing.T) {
11431174
t.Parallel()
11441175

0 commit comments

Comments
 (0)