Nil Slice Becomes Empty Slice After Copying
Closed this issue · 0 comments
helloqiu commented
Reproducible Example
Check https://go.dev/play/p/wIwXSvhuj4j
package main
import (
"fmt"
"reflect"
"github.com/jinzhu/copier"
)
type A struct {
SomeField []string
}
type B struct {
SomeField []uint
}
func main() {
a := A{}
b := B{}
if err := copier.Copy(&b, &a); err != nil {
panic(err)
}
anotherB := B{}
if !reflect.DeepEqual(b, anotherB) {
fmt.Println("b and anotherB should be equal")
}
fmt.Printf("a.SomeField : len(%d), is-nil:(%t)\n", len(a.SomeField), a.SomeField == nil)
fmt.Printf("b.SomeField : len(%d), is-nil:(%t)\n", len(b.SomeField), b.SomeField == nil)
fmt.Printf("anotherB.SomeField : len(%d), is-nil:(%t)\n", len(anotherB.SomeField), anotherB.SomeField == nil)
}
Result:
b and anotherB should be equal
a.SomeField : len(0), is-nil:(true)
b.SomeField : len(0), is-nil:(false)
anotherB.SomeField : len(0), is-nil:(true)
Description
If two struts have two fields with the same name but they are slice of different types, the value on the target struct would be assigned to an empty slice rather than a nil slice.