[英]copy data from one golang slice struct to another slice strcut
[英]Copy values from one struct to another in 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。 你能给我一个提示或更多吗?
我建议将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
用作接口,以明确表明可以更新哪些属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.