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 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错