func main() {
var m int = 2021
valueOfA := reflect.ValueOf(m)
var getA int = valueOfA.Interface().(int)
var getA2 int = int(valueOfA.Int())
fmt.Println(getA, getA2)
}
func main() {
type Dog struct {
LegCount int
}
valueOfDog := reflect.ValueOf(&Dog{})
valueOfDog = valueOfDog.Elem()
vLegCount := valueOfDog.FieldByName("LegCount")
vLegCount.SetInt(3)
fmt.Println(vLegCount.Int())
}
8、通过类型创建类型
创建了新的类型
go复制代码
func main() {
var a int
typeOfA := reflect.TypeOf(a)
aIns := reflect.New(typeOfA)
fmt.Println(aIns.Type(), aIns.Kind())
}
9、使用反射调用函数
go复制代码
func add(a, b int) int {
return a + b
}
func main() {
funcValue := reflect.ValueOf(add)
paramList := []reflect.Value{reflect.ValueOf(10), reflect.ValueOf(20)}
retList := funcValue.Call(paramList)
fmt.Println(retList[0].Int())
}
10、常用反射API
从实例到Value
go复制代码
func ValueOf(i interface{}) Value
从实例到Type
go复制代码
func TypeOf (i interface{}) Type
从Type到Value
go复制代码
func NewAt (type Type,p unsafe.Pointer) Value
从Value到Type
go复制代码
func (v Value) Type() Type
从Value到实例
go复制代码
func (v Value) Interface() (i interface{})
func (v Value) Bool() bool
func (v Value) Float() float64
func (v Value) Int() int64
func (v Value) Uint() uint64
从Value的指针到值
go复制代码
func (v Value) Elem() Value
func Indirect(v Value) Value
Type指针和值相互转换
go复制代码
t.Elem() Type //指针类型Type到值类型Type
func PtrTo(t Type) Type
Value值的可修改性
go复制代码
func (v Value) CanSet() bool
func (v Value) Set(x Value)