目录
说明1 reflect.Value区分CanSet和Can not Set
说明3 reflect.ValueOf 参数必须是一个 指针 或 interface Elem()才可以正常调用
说明1 reflect.Value区分CanSet和Can not Set
所以,必须要返回成Can set的reflect.Value
如:
s := reflect.ValueOf(&t).Elem()
然后就可以happy的设值了,可是不能随便设值的,一个通用的方法就是使用Set(v Value)方法,
说明2 将值转成reflect.Value类型
下面的这段代码就是转成Value类型
sliceValue := reflect.ValueOf([]int{1,2,3}) // 这里将slice转成reflect.Value类型
说明3 reflect.ValueOf 参数必须是一个 指针 或 interface Elem()才可以正常调用
func (Value) Elem
func (v Value) Elem() Value
Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Ptr. It returns the zero Value if v is nil.
Elem返回接口v包含的值或指针v指向的值。 如果v的Kind不是Interface或Ptr,它会感到恐慌。 如果v为零,它将返回零值。
实例代码
代码1:
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:
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,3}) // 这里将slice转成reflect.Value类型
s.FieldByName("Children").Set(sliceValue)