在Golang中动态更新结构体属性的值
时间:2024-03-18
浏览:228
作者:佚名
在 Go 语言中,使用 reflect 包可以动态更新结构体属性的值。此方法允许您根据输入数据有选择地更新特定字段,而无需编写大量 if 语句。通过使用反射,您可以获取结构体的字段并检查其值,仅在需要时才更新目标结构体。这种方法提供了代码的可维护性和可扩展性,使您能够轻松地更新复杂结构体。
问题内容
我在路由器处理程序中有此代码
decoder := json.newdecoder(r.body)
var t person.model
err := decoder.decode(&t). // t is a struct value
item, ok := v.people[params["id"]]. // ok is a struct value
if t.handle != "" {
item.handle = t.handle
}
if t.work != "" {
item.work = t.work
}
if t.image != "" {
item.image = t.image
}
if t.firstname != "" {
item.firstname = t.firstname
}
if t.lastname != "" {
item.lastname = t.lastname
}
if t.email != "" {
item.email = t.email
}
但我想让这种动态,像这样:
["Handle", "Work", "Image", "Firstname", "Lastname", "Email"].forEach(v => {
if t[v] != "" {
item[v] = t[v]
}
});
golang 可以实现这一点吗?
解决方案
为此使用 reflect 包:
func setfields(dst, src interface{}, names ...string) {
d := reflect.valueof(dst).elem()
s := reflect.valueof(src).elem()
for _, name := range names {
df := d.fieldbyname(name)
sf := s.fieldbyname(name)
switch sf.kind() {
case reflect.string:
if v := sf.string(); v != "" {
df.setstring(v)
}
// handle other kinds
}
}
}
使用指向值的指针调用它:
setfields(&item, &t, "firstname", "lastname", "email", "handle")
如果您的实际目标是仅覆盖 json 中存在的字段,那么就这样做:
item, ok := v.People[params["id"]]. decoder := json.NewDecoder(r.Body) err := decoder.Decode(&item)
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
12.01
热门专题
