我在路由器处理程序中有这段代码 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 来说有可能吗?
1 回答
万千封印
TA贡献1891条经验 获得超3个赞
为此使用反射包:
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)
- 1 回答
- 0 关注
- 129 浏览
添加回答
举报
0/150
提交
取消