共计 2601 个字符,预计需要花费 7 分钟才能阅读完成。
导读 | 这篇文章主要为大家介绍了 Go 语言开发框架反射机制及常见函数示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪 |
基本介绍
示意图
反射中常见函数和概念
reflect.TypeOf(变量名)
获取变量的类型, 返回 reflect.Type 类型
reflect.ValueOf(变量名)
获取变量的值, 返回 reflect.Value 类型 reflect.Value 是一个结构体类型, 通过 reflect.Value, 可以获取到关于该变量的很多信息
变量.interface{} 和 reflect.Value 是可以相互转换的
基本使用
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
/* | |
1. 编写案例, 对基本数据类型,interface{},reflect.Value 进行反射 | |
2. 编写案例, 对结构体,interface{},reflect.Value 进行反射 | |
*/ | |
func reflectTest(b interface{}){ | |
// 打印出传参的 type,kind,value | |
fmt.Printf("b 的类型为 %v,b 的 kind 为 %v,value 为 %v\n",reflect.TypeOf(b),reflect.ValueOf(b).Kind(),reflect.ValueOf(b)) // b 的类型为 int,b 的 kind 为 int,value 为 100 | |
//reflect.TypeOf(),reflect.ValueOf() 返回的类型 | |
fmt.Printf("reflect.TypeOf() 返回类型为 %T,reflect.ValueOf() 返回类型为 %T\n",reflect.TypeOf(b),reflect.ValueOf(b)) //reflect.TypeOf() 返回类型为 *reflect.rtype,reflect.ValueOf() 返回类型为 reflect.Value | |
} | |
type Student struct { | |
Name string | |
age int | |
} | |
func reflectTest2(b interface{}){rTyp:=reflect.TypeOf(b) | |
fmt.Println(rTyp) //main.Student | |
rVal:=reflect.ValueOf(b) | |
// 将 rVal 转换成 interface{} | |
iV:=rVal.Interface() | |
fmt.Printf("iv=%v type=%T\n",iV,iV) //iv={张三 18} type=main.Student | |
// 因为 Go 语言是静态语言, 所以不能直接获取结构体中指定的值, 所以我需要将其断言成需要的类型 | |
stu,ok:=iV.(Student) | |
if ok{fmt.Printf(stu.Name,stu.age) // 张三 %!(EXTRA int=18) | |
} | |
} | |
func main() {//1. 编写案例, 对基本数据类型,interface{},reflect.Value 进行反射 | |
var num int =100 | |
reflectTest(num) | |
//2. 编写案例, 对结构体,interface{},reflect.Value 进行反射 | |
stu:=Student{ | |
Name: "张三", | |
age: 18, | |
} | |
reflectTest2(stu) | |
} |
反射注意事项
反射的最佳实践
使用反射来遍历结构体的字段, 调用结构体的方法, 并获取结构体标签的值
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
// 定义了一个 Monster 结构体 | |
type Monster struct { | |
Name string `json:"name"` | |
Age int `json:"monster_age"` | |
Score float32 `json:"成绩"` | |
Sex string | |
} | |
// 方法,返回两个数的和 | |
func (s Monster) GetSum(n1, n2 int) int {return n1 + n2} | |
// 方法,接收四个值,给 s 赋值 | |
func (s Monster) Set(name string, age int, score float32, sex string) { | |
s.Name = name | |
s.Age = age | |
s.Score = score | |
s.Sex = sex | |
} | |
// 方法,显示 s 的值 | |
func (s Monster) Print() {fmt.Println("---start~----") | |
fmt.Println(s) | |
fmt.Println("---end~----") | |
} | |
func TestStruct(a interface{}) { | |
// 获取 reflect.Type 类型 | |
typ := reflect.TypeOf(a) | |
// 获取 reflect.Value 类型 | |
val := reflect.ValueOf(a) | |
// 获取到 a 对应的类别 | |
kd := val.Kind() | |
// 如果传入的不是 struct,就退出 | |
if kd != reflect.Struct {fmt.Println("expect struct") | |
return | |
} | |
// 获取到该结构体有几个字段 | |
num := val.NumField() | |
fmt.Printf("struct has %d fields\n", num) //4 | |
// 变量结构体的所有字段 | |
for i := 0; i | |
以上就是 Go 语言开发框架反射机制及常见函数示例详解的详细内容 | |
阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配 | |
腾讯云新客低至 82 元 / 年,老客户 99 元 / 年 | |
代金券:在阿里云专用满减优惠券 |
正文完
星哥玩云-微信公众号
