我对更新结构中的值很感兴趣,但我注意到有很多重复的代码。是否可以将 key ID 传递给 func(keyid string)
以使用输入作为选择器来修改结构?我知道 reflect 包存在,但是返回键字段的值很简单,但我不知道如何将它用作键 id 的选择器。
我的重复代码模式:
func (j *items) updatePath(n string, v string) []JSON {
cur := j.find(n)
if cur != -1 {
j.items[cur].Path = v
return j.items
}
return j.items
}
func (j *items) updateArgs(n string, v []string) []JSON {
cur := j.find(n)
if cur != -1 {
j.items[cur].Args = v
return j.items
}
return j.items
}
func (j *items) updateTimes(n string) []JSON {
cur := j.find(n)
if cur != -1 {
j.items[cur].TimesRun++
return j.items
}
return j.items
}
反射(reflection):
func (j *items) returnField(s string) string {
r := reflect.ValueOf(j.items[0])
f := reflect.Indirect(r).FieldByName(s)
return f.String() //i can't use f as `j.items[0].f` selector.
}
最佳答案
解决方法:
func (j *items) updateField(s string, vl string) {
val := reflect.ValueOf(&j.items[0])
(val.Elem()).FieldByName(s).SetString(vl)
}
- 它并不慢
- 并不难理解
我还发现也可以使用 Map() 来实现,但需要付出更多的努力。
关于go - 如何通过匹配的字符串变量在结构中选择键 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397072/