go - 如何使用反射包操作结构中的地图字段?
问题描述
我们有这样的结构:
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。有什么办法可以解决这个问题?
解决方案
利用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)
}
推荐阅读
- unity3d - 超出着色器全局关键字的最大数量 (256),关键字 Unity
- typescript - 在 Svelte 应用程序上编译期间一切正常时,运行时出现未定义的模块错误
- android - 如何从 android studio 项目中的 JsonObject 中提取数据
- javascript - 网页设计:透明图像旋转和放大/缩小
- python - 数据库:每次都更快地转储列表或查询?
- vb.net - 我如何将 /xfe\xff\x8bE\xfc\x8b\xdf\x8b}\ 等字符存储在变量 -Vb.net 中
- python - tsfresh 中 select_features 的有限值目标向量
- sql - 用于优化数据库性能的单列与多列索引
- gitlab - 使用 gitlab-ci.yml 管道自动合并代码
- mobx - mobx-state-tree 和 mobx-keystone 之间的混淆。什么时候用哪个?