jinzhu / copier

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

Non existent fields on source struct is still over ridden in destination struct #204

Open Roccoriu opened 11 months ago

Roccoriu commented 11 months ago

Reproducible Example

Description

I use gorm for managing my db schema in my application. I need to copy fields from a dto to the model. The id fields are not present in the dto and should not be overriden since it only exists in the destination struct. Why are they set to a zero value? It makes absolutely no sense and should not happen


type HostnameConfig struct {
    database.Model

    OrderConfigurationID *uint `json:"-"`

    OrderConfiguration OrderConfiguration `json:"-"`
    NetworkConfigs     []NetworkConfig    `json:"networkConfigs" gorm:"constraint:OnUpdate:CASCADE,OnDelete:CASCADE;foreignkey:HostnameConfigID"`
}

type OrderHostnameDTO struct {
    OrderConfigurationID *uint              `json:"orderConfigurationID"`
    NetworkConfigs       []NetworkConfigDTO `json:"networkConfigs"`
}

log.Printf("%v", exists[0].ID)
if err := copier.Copy(&exists, &hostnameConfigDTO); err != nil {
    return nil, err
}

log.Printf("%v", exists[0].ID)

image

This does not behave as expected. The ID field of exists gets set to after it's overridden, even if the DTO does not contain any ID fields what so ever. I tried the CopyWithOptions method, none of the options changed the described behaviour what so ever.

Roccoriu commented 11 months ago

I've noticed that it breaks if you make use of struct embedding. Is something that can be implemented in the future?