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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!