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

在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?

图片转代码服务由CSDN问答提供 功能建议

我有两个结构:

  type UpdateableUser结构{  
名字字符串
姓氏字符串
电子邮件字符串
 Tlm float64 
 Dob时间。时间
} 
 
type用户结构{
 ID字符串
名字字符串
姓氏字符串
电子邮件字符串
  DOB time.Time 
 Tlm float64 
创建时间。Time
更新时间。Time
} 
   
 
 

通过绑定器,我将请求数据绑定到updateableUser struct,因此我可能有一个只有一个“真实”值的updateableUser,例如uu:

  uu:= UpdateableUser {姓:“ Smith”} 
   
 
 

现在,我只想将UpdateableUser的非“ emtpy”值设置为User。 您能给我一个提示还是更多?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 评论

相关推荐 更多相似问题