我们有一个像这样的结构:
type S struct {
M map[string]bool
}
以及我们如何实现这样的功能:
// this function modify field by name to a new map
func Modify(s *S, name string, val map[string]bool){
...
}
func Test() {
s := S{
M: map[string]bool{"Hello":true},
}
m := map[string]bool{"World":false}
Modify(&s, "M", m)
}
反射包支持SetInt / SetString / etc,但不支持SetMap。有什么办法解决这个问题?
用 reflect.Set()
func Modify(s *S, name string, val interface{}) {
rv := reflect.ValueOf(val)
if !rv.IsValid() {
rv = reflect.Zero(reflect.ValueOf(s).Elem().FieldByName(name).Type())
}
reflect.ValueOf(s).Elem().FieldByName(name).Set(rv)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句