golang 反射 reflect 设置 struct 字段

目录

说明1 reflect.Value区分CanSet和Can not Set

说明2 将值转成reflect.Value类型

说明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)

 

 

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...