Skip to content

Commit d82c25e

Browse files
authored
Make dst slice consistent with the empty src slice. (#30)
1 parent 3225841 commit d82c25e

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

copy.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,10 @@ func structToMap(filter FieldFilter, src interface{}, dst map[string]interface{}
361361
continue
362362
}
363363
var newValue []map[string]interface{}
364+
if srcField.Kind() == reflect.Slice && !srcField.IsNil() {
365+
// If the source slice is not nil then the dst should not be nil either even if the src slice is empty.
366+
newValue = make([]map[string]interface{}, 0, srcField.Len())
367+
}
364368
existingValue, ok := dst[dstName]
365369
if ok {
366370
v := reflect.ValueOf(existingValue)

copy_test.go

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package fieldmask_utils_test
22

33
import (
4+
"encoding/json"
45
"fmt"
56
"reflect"
67
"testing"
@@ -1990,7 +1991,7 @@ func TestStructToStruct_WithMultiTagComma(t *testing.T) {
19901991
}, dst)
19911992
}
19921993

1993-
func TestStructToMap_DiffentTypeWithSameDstKey(t *testing.T) {
1994+
func TestStructToMap_DifferentTypeWithSameDstKey(t *testing.T) {
19941995
type BB struct {
19951996
Field int
19961997
}
@@ -2015,6 +2016,40 @@ func TestStructToMap_DiffentTypeWithSameDstKey(t *testing.T) {
20152016
require.Error(t, err)
20162017
}
20172018

2019+
func TestStructToMap_EmptySrcSlice_JsonEncode(t *testing.T) {
2020+
type A struct{}
2021+
type B struct {
2022+
As []*A
2023+
}
2024+
2025+
src := &B{[]*A{}}
2026+
dst := make(map[string]interface{})
2027+
2028+
mask := fieldmask_utils.MaskFromString("As")
2029+
err := fieldmask_utils.StructToMap(mask, src, dst)
2030+
require.NoError(t, err)
2031+
2032+
jsonStr, _ := json.Marshal(dst)
2033+
assert.Equal(t, string(jsonStr), "{\"As\":[]}")
2034+
}
2035+
2036+
func TestStructToMap_NilSrcSlice_JsonEncode(t *testing.T) {
2037+
type A struct{}
2038+
type B struct {
2039+
As []*A
2040+
}
2041+
2042+
src := &B{}
2043+
dst := make(map[string]interface{})
2044+
2045+
mask := fieldmask_utils.MaskFromString("As")
2046+
err := fieldmask_utils.StructToMap(mask, src, dst)
2047+
require.NoError(t, err)
2048+
2049+
jsonStr, _ := json.Marshal(dst)
2050+
assert.Equal(t, string(jsonStr), "{\"As\":null}")
2051+
}
2052+
20182053
func TestStructToStruct_CopySlice_WithDiffentAddr_WithDifferentFieldName(t *testing.T) {
20192054
type A struct {
20202055
Field1 []int

0 commit comments

Comments
 (0)