type: User
Fields:
Id:int = 1
Name:string = bgops
Age:int = 25
Hello:func(main.User)
Hello xuxuebiao
if k := t.Kind();k != reflect.Struct {
fmt.Println("非值类型的反射")
return
}
//根据指定索引返回对应的嵌套字段
FieldByIndex(index []int) StructField
type StructField struct {
Name string
PkgPath string
Type Type
Tag StructTag
Offset uintptr
Index []int
Anonymous bool //是否为匿名字段
}
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
type Manager struct {
User
title string
}
func main() {
//注意匿名字段的初始化操作
m := Manager{User: User{1, "biaoge", 24}, title: "hello biao"}
t := reflect.TypeOf(m)
fmt.Printf("%#v\n", t.FieldByIndex([]int{0}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{1}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 0}))
fmt.Printf("%#v\n", t.FieldByIndex([]int{0, 1}))
}
reflect.StructField{Name:"User", PkgPath:"", Type:(*reflect.rtype)(0x4ac660), Tag:"", Offset:0x0, Index:[]int{0}, Anonymous:true}
reflect.StructField{Name:"title", PkgPath:"main", Type:(*reflect.rtype)(0x49d820), Tag:"", Offset:0x20, Index:[]int{1}, Anonymous:false}
reflect.StructField{Name:"Id", PkgPath:"", Type:(*reflect.rtype)(0x49d1a0), Tag:"", Offset:0x0, Index:[]int{0}, Anonymous:false}
reflect.StructField{Name:"Name", PkgPath:"", Type:(*reflect.rtype)(0x49d820), Tag:"", Offset:0x8, Index:[]int{1}, Anonymous:false}
package main
import (
"fmt"
"reflect"
)
func main() {
x := 123
v := reflect.ValueOf(&x)
v.Elem().SetInt(5256)
fmt.Println(x)
}
v.FieldByName("Name");f.Kind() == reflect.String {
f.SetString("test string")
}
f := v.FieldByName("Name1")
//判断反射对象Value中是否找到Name1字段
if !f.IsValid() {
fmt.Println("bad field")
return
}
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Age int
}
//使用反射方式对结构体对象的修改有两个条件
//1.通过指针
//2.必须是可set的方法
func main() {
num := 123
numv := reflect.ValueOf(&num)
//通过Value的Elem()和SetX()方法可直接对相关的对象进行修改
numv.Elem().SetInt(666)
fm