Go语言反射解析结构体字段值教程
reflect.ValueOf()
Go语言反射解析结构体字段值语法
personNameValue := reflect.ValueOf(&person.Name) personNameValue.Elem().SetString("haicoder")
通过 reflect.ValueOf 获取结构体的值信息,再次使用结构体值信息的 Elem 获取对应的字段信息,最后使用字段信息对应的类型函数,设置结构体字段的值。
案例
Go语言反射修改结构体字段值
通过反射设置结构体的字段值
package main import ( "fmt" "reflect" ) type Person struct { Name string `json:name` Age int `json:age` } func main() { fmt.Println("嗨客网(www.haicoder.net)") person := Person{ Name:"HaiCoder", Age:109, } personNameValue := reflect.ValueOf(&person.Name) personAgeValue := reflect.ValueOf(&person.Age) personNameValue.Elem().SetString("haicoder") personAgeValue.Elem().SetInt(100) fmt.Println("Name Value =", person.Name, "Age Value =", person.Age) }
程序运行后,控制台输出如下:

首先,我们定义了一个 Person 结构体,结构体含有两个字段,一个 类型的 Name 和一个 类型的 Age。
reflect.ValueOf
Go语言反射解析结构体字段值总结
reflect.ValueOf()
personNameValue := reflect.ValueOf(&person.Name) personNameValue.Elem().SetString("haicoder")