jinzhu / copier

Copier for golang, copy value from struct to struct and more
MIT License
5.58k stars 489 forks source link

Copy with nested pointer struct causes panic #99

Closed andig closed 1 year ago

andig commented 3 years ago

This is a follow-up to https://github.com/jinzhu/copier/issues/31 and https://github.com/jinzhu/copier/pull/72, I'm running v0.3.1-0.20210422135233-8f9e587049b3.

Description

A nil embedded struct still panics:

panic: reflect: indirection through nil pointer to embedded struct

goroutine 12 [running]:
reflect.Value.FieldByIndex(0x103aea5c0, 0x140004186f0, 0x99, 0x1400053c0d0, 0x2, 0x2, 0x0, 0x103c06be8, 0x103992cc0)
    /opt/homebrew/Cellar/go/1.16.3/libexec/src/reflect/value.go:889 +0x2a4
reflect.Value.FieldByName(0x103aea5c0, 0x140004186f0, 0x99, 0x1038d014f, 0x7, 0x1039ea100, 0x14000418708, 0x95)
    /opt/homebrew/Cellar/go/1.16.3/libexec/src/reflect/value.go:905 +0xdc
github.com/jinzhu/copier.copier(0x103a2c020, 0x14000418690, 0x103aea5c0, 0x140004186f0, 0x101, 0x0, 0x0)
    /Users/andig/go/pkg/mod/github.com/jinzhu/copier@v0.3.1-0.20210422135233-8f9e587049b3/copier.go:203 +0x11dc
github.com/jinzhu/copier.CopyWithOption(...)
    /Users/andig/go/pkg/mod/github.com/jinzhu/copier@v0.3.1-0.20210422135233-8f9e587049b3/copier.go:42

This is caused by

type Details struct {
    IP           string
    Port         int
    *ModbusResult
}

while this does no panic:

type Details struct {
    IP           string
    Port         int
    ModbusResult *ModbusResult
}

Will add reproducer.

NicklasWallgren commented 2 years ago

I've implemented a fix in https://github.com/jinzhu/copier/pull/157