Allocate slice if needed

This commit is contained in:
Thomas Pelletier
2021-03-08 21:41:03 -05:00
parent 87b9d1cf98
commit a1c9b661b4
3 changed files with 15 additions and 14 deletions
@@ -1827,9 +1827,7 @@ type arrayTooSmallStruct struct {
func TestUnmarshalSlice(t *testing.T) {
var actual sliceStruct
err := toml.Unmarshal(sliceTomlDemo, &actual)
if err != nil {
t.Error("shound not err", err)
}
require.NoError(t, err)
expected := sliceStruct{
Slice: []string{"Howdy", "Hey There"},
SlicePtr: &[]string{"Howdy", "Hey There"},
@@ -1838,10 +1836,7 @@ func TestUnmarshalSlice(t *testing.T) {
StructSlice: []basicMarshalTestSubStruct{{"1"}, {"2"}},
StructSlicePtr: &[]basicMarshalTestSubStruct{{"1"}, {"2"}},
}
if !reflect.DeepEqual(actual, expected) {
t.Errorf("Bad unmarshal: expected %v, got %v", expected, actual)
}
assert.Equal(t, expected, actual)
}
func TestUnmarshalSliceFail(t *testing.T) {
+6
View File
@@ -380,6 +380,12 @@ func (b *Builder) SliceNewElem() error {
v := t.get()
if v.Kind() == reflect.Ptr {
// if the pointer is nil we need to allocate the slice
if v.IsNil() {
x := reflect.New(v.Type().Elem())
v.Set(x)
}
// target the slice itself
v = v.Elem()
}