博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
反射的快速入门
阅读量:664 次
发布时间:2019-03-16

本文共 1902 字,大约阅读时间需要 6 分钟。

一 需求

1 编写一个案例,演示对基本数据类型、interface{}、reflect.Value 进行反射的基本操作。

2 编写一个案例,演示对结构体类型、interface{}、reflect.Value 进行反射的基本操作。

二 代码

package mainimport (   "fmt"   "reflect")// 基本数据类型演示反射func reflectTest01(b interface{}) {   // 通过反射获取传入的变量的 type 和 kind 的值。   // 先获取到 reflect.Type   rTyp := reflect.TypeOf(b)   fmt.Println("rType=", rTyp)   // 获取到 reflect.Value   rVal := reflect.ValueOf(b)   n2 := 2 + rVal.Int()   // n3 := rVal.Float()   fmt.Println("n2=", n2)   // fmt.Println("n3=", n3)   fmt.Printf("rVal=%v rVal type=%T\n", rVal, rVal)   // 将 rVal 转成 interface{}   iV := rVal.Interface()   // 将 interface{} 通过断言转成需要的类型   num2 := iV.(int)   fmt.Println("num2=", num2)   // 获取变量对应的 Kind   rkind := rVal.Kind()   fmt.Println("kind=", rkind)}// 结构体演示反射func reflectTest02(b interface{}) {   // 通过反射获取传入的变量的 type 和 kind 的值。   // 先获取到 reflect.Type   rTyp := reflect.TypeOf(b)   fmt.Println("rType=", rTyp)   // 获取到 reflect.Value   rVal := reflect.ValueOf(b)   // 获取变量对应的 Kind   kind1 := rVal.Kind() // reflect.Value 的 Kind()   kind2 := rTyp.Kind() // reflect.Type 的 Kind()   fmt.Printf("kind =%v kind=%v\n", kind1, kind2)   // 将 rVal 转成 interface{}   iV := rVal.Interface()   fmt.Printf("iv=%v iv type=%T \n", iV, iV)   // 将 interface{} 通过断言转成需要的类型   // 简单使用带检测的类型的断言。   // 使用 swtich 的断言形式做得更加灵活   stu, ok := iV.(Student)   if ok {      fmt.Printf("stu.Name=%v\n", stu.Name)   }}type Student struct {   Name string   Age  int}func main() {   // 先定义一个int   var num int = 100   reflectTest01(num)   fmt.Println("--------------------------------------------------------------------")   // 定义一个 Student 的实例   stu := Student{      Name: "tom",      Age:  20,   }   reflectTest02(stu)}

三 测试

rType= int

n2= 102

rVal=100 rVal type=reflect.Value

num2= 100

kind= int

--------------------------------------------------------------------

rType= main.Student

kind =struct kind=struct

iv={tom 20} iv type=main.Student

stu.Name=tom

转载地址:http://arxqz.baihongyu.com/

你可能感兴趣的文章