博客
关于我
反射的快速入门
阅读量:666 次
发布时间: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/

你可能感兴趣的文章
nginx 常用指令配置总结
查看>>
Nginx 常用配置清单
查看>>
nginx 常用配置记录
查看>>
nginx 开启ssl模块 [emerg] the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的 SSL 模块安装
查看>>
Nginx 的优化思路,并解析网站防盗链
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
nginx 禁止以ip形式访问服务器
查看>>
NGINX 端口负载均衡
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
Nginx 负载均衡配置详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置服务器文件上传与下载
查看>>