duanche2007 2018-12-05 08:50
浏览 2091
已采纳

在Golang中将值从一个结构复制到另一个

I've two structs:

type UpdateableUser struct {
    FirstName string
    LastName string
    Email string
    Tlm float64
    Dob time.Time
}

type User struct {
    Id string
    FirstName string
    LastName string
    Email string
    DOB time.Time
    Tlm float64
    created time.Time
    updated time.Time
}

Through a binder I bind request data to the updateableUser struct, therefore I might have an updateableUser with only one "real" value, like uu here:

uu := UpdateableUser{Lastname: "Smith"}

Now I want to set only the not "emtpy" values from UpdateableUser to User. Can you please give me a hint or more?

  • 写回答

1条回答 默认 最新

  • douhuiyan2772 2018-12-05 09:15
    关注

    I would recommend embedding the Updateable struct into the larger struct:

    type UpdateableUser struct {
        FirstName string
        LastName  string
        Email     string
        Tlm       float64
        Dob       time.Time
    }
    
    type User struct {
        UpdateableUser
        ID      string
        created time.Time
       updated time.Time
    }
    
    func (u *User) UpdateFrom(src *UpdateableUser) {
        if src.FirstName != "" {
            u.FirstName = src.FirstName
        }
        if src.LastName != "" {
            u.LastName = src.LastName
        }
        // ... And other properties. Tedious, but simple and avoids Reflection
    }
    

    This allows you to use UpdateableUser as an interface to make it explicit which properties can be updated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥15 C#字典调用时报错,有关文件加载
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 关于PHP中POST获取数据的问题
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Python实现hog特征图可视化
  • ¥30 德飞莱51单片机实现C4炸弹