I'm interesting in to update value in to struct, but I notice lots of repeated code. Is it possible to pass Key ID in to func(keyid string)
to use input as a selector to modify the struct? I know reflect package exists, but it's simple to return value of key field, but I can't figure out how to use it as selector of key id.
My repeated code pattern:
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
}
Reflect:
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.
}
Solution:
func (j *items) updateField(s string, vl string) {
val := reflect.ValueOf(&j.items[0])
(val.Elem()).FieldByName(s).SetString(vl)
}
Also i'm find out that it's also possible to do with a Map(), but it will took a lot more effort.