其他分享
首页 > 其他分享> > Go-反射

Go-反射

作者:互联网

反射的示意图

image

案例1

image

package main

import (
	"fmt"
	"reflect"
)

func reflectTest01(b interface{}) {
	//通过反射获取传入变量的type kind value
	rTyp := reflect.TypeOf(b)
	fmt.Println("rTye=", rTyp)
	rVal := reflect.ValueOf(b)
	fmt.Printf("rTye=%v rVal=%T\n", rVal, rVal)
	n2 := 2 + rVal.Int()
	fmt.Println(n2)
	iv := rVal.Interface()
	num2 := iv.(int)
	fmt.Println(num2)
}

func main() {
	var num int = 100
	reflectTest01(num)
}

image

对结构体的反射

package main

import (
	"fmt"
	"reflect"
)

type Student struct {
	Name string
	Age  int
}

func reflectTest02(b interface{}) {
	//通过反射获取传入变量的type kind value
	rTyp := reflect.TypeOf(b)
	fmt.Println("rTye=", rTyp)
	rVal := reflect.ValueOf(b)
	iv := rVal.Interface()
	fmt.Printf("rTye=%v rVal=%T\n", iv, iv)

	fmt.Printf("kind=%v kind=%v\n", rTyp.Kind(), rVal.Kind())

	stu, ok := iv.(Student)
	if ok {
		fmt.Printf("stu.Name=%v\n", stu.Name)
	}

}

func main() {
	stu := Student{
		Name: "tmo",
		Age:  20,
	}
	reflectTest02(stu)
}

image

标签:反射,rTyp,fmt,rVal,iv,reflect,stu,Go
来源: https://www.cnblogs.com/jgg54335/p/15858143.html