首页 > 解决方案 > 如何使用反射包操作结构中的地图字段?

问题描述

我们有这样的结构:

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

reflect 包支持 SetInt/SetString/etc,但不支持 SetMap。有什么办法可以解决这个问题?

标签: goreflection

解决方案


利用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)
}

操场


推荐阅读