我有两个结构:
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
}
通过 Binder ,我将请求数据绑定(bind)到 updateableUser 结构,因此我可能有一个只有一个“真实”值的 updateableUser,就像这里的 uu:
uu := UpdateableUser{Lastname: "Smith"}
现在我只想将 UpdateableUser 中的非“emtpy”值设置为 User。你能给我一个提示或更多吗?
最佳答案
我建议将 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
作为接口(interface)来明确哪些属性可以更新。
关于go - 在 Golang 中将值从一个结构复制到另一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53628362/