go - 在 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
其用作接口,以明确哪些属性可以更新。
推荐阅读
- node.js - 获取访问令牌有效性
- string - How does std.string.toStringz work in dlang?
- git - 如何正确初始化远程 git 存储库
- php - 替换花括号内字符串中的所有空格
- javascript - Highcharts 可拖动点与极坐标图
- xamarin - 如何在不获取路径空异常的情况下获取 Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default
- pandas - 熊猫选择列不同的帧
- android - 使用 cordova 播放用户选择的音频
- android - 如何使用 Retrofit/Gson 反序列化 JSON 中相同类型但具有不同字段名称的对象列表?
- menu - 断点后响应式导航栏出现问题