在编写通用差异和补丁算法的过程中,我遇到了反射问题。
当我尝试修补切片时,我没有问题,reflect.ValueOf(&slice).Elem().Index(0).CanSet()返回true。这使我可以对slice元素内的任何内容进行修补,无论是原始元素还是结构的切片。
但是,当我尝试使用地图reflect.ValueOf(&map).Elem().MapIndex(reflect.ValueOf("key")).CanSet()返回false时。这样可以防止我尝试对地图内容做任何事情。
切片
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
Run Code Online (Sandbox Code Playgroud)
地图
m := map[string]string{
"a": "1",
"b": "2",
"c": "3"}
mv := reflect.ValueOf(&m).Elem()
println(mv.MapIndex(reflect.ValueOf("a")).CanSet())
output:
false
Run Code Online (Sandbox Code Playgroud)
如何通过反射从地图中获得可修改的价值?
谢谢你的时间。