极为重要的两篇文章
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 data
jaeger := Jaeger{Name: "Cherno Alpha", Country: "RU", Status: "Active"}
kaiju := Kaiju{Alias: "Scissure", Origin: "Sydney", Status: "Unknown"}
shatterdome := Shatterdome{Location: "Lima"}
// Destroy everything
Destroy(&jaeger)
Destroy(&kaiju)
Destroy(&shatterdome)
// Check the result
if 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:
本文详细解析了Go语言中的反射机制,并通过实际代码示例展示了如何使用反射来修改结构体字段,包括如何获取和设置字段值,以及如何在不同场景下灵活运用反射特性。此外,文章还介绍了反射机制在处理复杂数据结构和对象操作中的优势。
1196

被折叠的 条评论
为什么被折叠?



