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

Tho*_*ach 2 struct go

我有两个结构:

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
}
Run Code Online (Sandbox Code Playgroud)

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

uu := UpdateableUser{Lastname: "Smith"}
Run Code Online (Sandbox Code Playgroud)

现在我只想设置从 UpdateableUser 到 User 的非“空”值。你能给我一个提示或更多吗?

Vin*_*ent 6

我建议将 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
}
Run Code Online (Sandbox Code Playgroud)

这允许您用作UpdateableUser接口来明确哪些属性可以更新。