如何使用反射包操纵结构中的地图字段?

We have a structure like:

type S struct {
    M map[string]bool
}

And how can we implement a function like:


// 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)
}

The reflect package support SetInt/SetString/etc, but none SetMap. Any way to solve this problem?

Use 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)
}

Playground