利用reflect设置struct的字段
来源:互联网 发布:美国阿富汗战争知乎 编辑:程序博客网 时间:2024/05/22 10:47
极为重要的两篇文章
1. http://speakmy.name/2014/09/14/modifying-interfaced-go-struct/
Combining it all together, this is the final function:
func Destroy(subj interface{}) {stype := reflect.ValueOf(subj).Elem()field := stype.FieldByName("Status")if field.IsValid() {field.SetString("Destroyed")}}
func TestDestroy(t *testing.T) {// Initialize datajaeger := Jaeger{Name: "Cherno Alpha", Country: "RU", Status: "Active"}kaiju := Kaiju{Alias: "Scissure", Origin: "Sydney", Status: "Unknown"}shatterdome := Shatterdome{Location: "Lima"}// Destroy everythingDestroy(&jaeger)Destroy(&kaiju)Destroy(&shatterdome)// Check the resultif jaeger.Status != "Destroy" {t.Error("jaeger was not destroyed")}if kaiju.Status != "Destroy" {t.Error("kaiju was not destroyed")}}
2.
参考golang反射三大规则
reflect.Value区分CanSet和Can not Set的, 所以, 必须要返回成Can set的reflect.Value
如:
然后就可以happy的设值了, 可是不能随便设值的, 一个通用的方法就是使用Set(v Value)方法, 所以之前必须将值转成reflect.Value类型, 下面的这段代码就是转成Value类型
完整参考:
如:
s := reflect.ValueOf(&t).Elem()
sliceValue := reflect.ValueOf([]int{1, 2, 3}) // 这里将slice转成reflect.Value类型
type T struct { Age int Name string Children []int}t := T{12, "someone-life", nil}s := reflect.ValueOf(&t).Elem()s.Field(0).SetInt(123) // 内置常用类型的设值方法sliceValue := reflect.ValueOf([]int{1, 2, 3}) // 这里将slice转成reflect.Value类型s.FieldByName("Children").Set(sliceValue)
###############
How to use Reflect to set a struct field
http://samwize.com/2015/03/20/how-to-use-reflect-to-set-a-struct-field/In short, if you want to set a struct foo
object when you know the field name to set, this is the code:
If you want to print all the fields of foo
, this is the code:
0 0
- 利用reflect设置struct的字段
- 含有对象字段的struct变量被memset设置成0带来的bug
- Golang 验证 struct 字段的数据格式
- 时间字段的利用
- Golang 使用reflect 更改struct内容
- 利用反射通用的设置某个对象的某个字段为指定的值
- 利用Reflect显示bean数据
- 利用函数进行汉字首字母辨别,对字段设置需要的值
- [Java] 利用Java反射机制批量获取和设置字段的值
- C语言 - 结构体(struct)的位字段(:) 详解
- c 查看struct各字段的偏移值
- Go的reflect机制和reflect包
- GridView 显示设置的字段
- 设置金额字段的格式
- 【反射】Reflect的使用
- Java的reflect
- java的reflect
- Reflect反射的基础知识
- C++ map的基本操作和使用 (2009-09-23 14:58:21)
- 浅谈CSRF攻击方式
- useradd添加用户无法进入可视化界面
- android studio使用技巧
- Windows8下安装win7VHD deepinVHD
- 利用reflect设置struct的字段
- jquery之交付序列化表单(serialize)及乱码处理
- 65536 "DexIndexOverflowException"问题官方解决方案
- 欢迎使用CSDN-markdown编辑器
- 2522A simple problem
- Codeforces Round #337 (Div. 2) E. Alphabet Permutations (线段树lazy 或 set)
- XAML那些事儿
- 详细分析推荐系统和搜索引擎的差异陈运文
- 树