Context
In the process of writing a generic diff and patch algorithm I faced a problem with reflection in go.
When I'm trying to patch in a slice I have no problem, reflect.ValueOf(&slice).Elem().Index(0).CanSet()
returns true. This allows me to patch anything inside the slice element, be it a slice of primitive or of structs.
Problem
However when I attempt this with a map reflect.ValueOf(&map).Elem().MapIndex(reflect.ValueOf("key")).CanSet()
returns false. This prevents me from attempting to do anythnin with the content of my map.
Examples
Slice
s := []string{"a", "b", "c"}
v := reflect.ValueOf(&s).Elem()
e := v.Index(1)
println(e.String())
println(e.CanSet())
e.Set(reflect.ValueOf("d"))
for _, v := range s {
print(v, " ")
}
output :
b
true
a d c
Map
m := map[string]string{
"a": "1",
"b": "2",
"c": "3"}
mv := reflect.ValueOf(&m).Elem()
println(mv.MapIndex(reflect.ValueOf("a")).CanSet())
output:
false
How could I get a modifiable value out of a map through reflection?
Thanks for your time.
Aucun commentaire:
Enregistrer un commentaire