首页 > 解决方案 > 在 Golang 中将值从一个结构复制到另一个结构

问题描述

我有两个结构:

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
}

通过一个活页夹,我将请求数据绑定到 updateableUser 结构,因此我可能有一个只有一个“真实”值的 updateableUser,就像这里的 uu:

uu := UpdateableUser{Lastname: "Smith"}

现在我只想将 UpdateableUser 中的非“emtpy”值设置为 User。你能给我一个提示或更多吗?

标签: gostruct

解决方案


我建议将 Updateable 结构嵌入到更大的结构中:

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
}

这使您可以将UpdateableUser其用作接口,以明确哪些属性可以更新。


推荐阅读