当前位置:网站首页>Golang6 reflection
Golang6 reflection
2022-06-29 23:55:00 【A teddy bear】
A basic introduction to reflection
1) Reflection can dynamically obtain various information of variables at runtime , For example, the type of variable (type), Category (kind)
2) If it's a structural variable , You can also get information about the structure itself ( Fields that include structs 、 Method )
3) By reflection , You can change the value of a variable , You can call the associated method .
4) Using reflection , need import (“reflect”)
Reflect important functions and concepts
// Special demonstration of reflection
func reflectTest01(b interface{
}) {
// The value of the passed in variable obtained by reflection type , kind, value
//1. Get it first reflect.Type
rTyp := reflect.TypeOf(b)
fmt.Println("rType=", rTyp)
//2. Get 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)
// Next we will rVal Turn into interface{}
iV := rVal.Interface()
// take interface{} Convert to required type by assertion
num2 := iV.(int)
fmt.Println("num2=", num2)
}
// Special demonstration of reflection [ Reflection on the structure ]
func reflectTest02(b interface{
}) {
// The value of the passed in variable obtained by reflection type , kind, value
//1. Get it first reflect.Type
rTyp := reflect.TypeOf(b)
fmt.Println("rType=", rTyp)
//2. Get reflect.Value
rVal := reflect.ValueOf(b)
//3. obtain Variable corresponding Kind
//(1) rVal.Kind() ==>
kind1 := rVal.Kind()
//(2) rTyp.Kind() ==>
kind2 := rTyp.Kind()
fmt.Printf("kind =%v kind=%v\n", kind1, kind2)
// Next we will rVal Turn into interface{}
iV := rVal.Interface()
fmt.Printf("iv=%v iv type=%T \n", iV, iV)
// take interface{} Convert to required type by assertion
// here , We simply use the type assertion with detection .
// Students can use swtich The assertion form is more flexible
stu, ok := iV.(Student)
if ok {
fmt.Printf("stu.Name=%v\n", stu.Name)
}
}
type Student struct {
Name string
Age int
}
type Monster struct {
Name string
Age int
}
func main() {
// Please write a case ,
// Demo yes ( Basic data type 、interface{}、reflect.Value) The basic operation of reflection
//1. So let's define one int
var num int = 100
reflectTest01(num)
//2. Define a Student Example
stu := Student{
Name : "tom",
Age : 20,
}
reflectTest02(stu)
}
Considerations and details of reflection
1)reflect.Value.Kind, Gets the category of the variable , Returns a constant
2)Type and Kind The difference between Type It's the type , Kind It's a category ,
Type and Kind It could be the same , It could be different .
such as : var num int = 10 num Of Type yes int , Kind It's also int
such as : var stu Student stu Of Type yes pkg1.Student , Kind yes struct
5) Modifying variables through reflection , Pay attention when using SetXxx Method to set, you need to use the corresponding pointer type to complete , This changes the value of the incoming variable , At the same time, we need to use reflect.Value.Elem() Fang
6)reflect.Value.Elem()
Reflection best practices
1) Use reflection to traverse the fields of the structure , Call the method of the struct , And get the value of the structure tag
// Defined a Monster Structure
type Monster struct {
Name string `json:"name"`
Age int `json:"monster_age"`
Score float32 `json:" achievement "`
Sex string
}
// Method , Returns the sum of two numbers
func (s Monster) GetSum(n1, n2 int) int {
return n1 + n2
}
// Method , Receive four values , to s assignment
func (s Monster) Set(name string, age int, score float32, sex string) {
s.Name = name
s.Age = age
s.Score = score
s.Sex = sex
}
// Method , Show s Value
func (s Monster) Print() {
fmt.Println("---start~----")
fmt.Println(s)
fmt.Println("---end~----")
}
func TestStruct(a interface{
}) {
// obtain reflect.Type type
typ := reflect.TypeOf(a)
// obtain reflect.Value type
val := reflect.ValueOf(a)
// Get a Corresponding category
kd := val.Kind()
// If it's not struct, Quit
if kd != reflect.Struct {
fmt.Println("expect struct")
return
}
// It is obtained that the structure has several fields
num := val.NumField()
fmt.Printf("struct has %d fields\n", num) //4
// All fields of variable structure
for i := 0; i < num; i++ {
fmt.Printf("Field %d: The value is =%v\n", i, val.Field(i))
// Get struct label , Note that you need to pass reflect.Type To get tag Value of label
tagVal := typ.Field(i).Tag.Get("json")
// If this field is in tag The label is displayed , Otherwise, it will not show
if tagVal != "" {
fmt.Printf("Field %d: tag by =%v\n", i, tagVal)
}
}
// How many ways to get the structure
numOfMethod := val.NumMethod()
fmt.Printf("struct has %d methods\n", numOfMethod)
//var params []reflect.Value
// Methods are sorted by default Sort function names (ASCII code )
val.Method(1).Call(nil) // Get the second method . Call it
// Call the... Of the structure 1 A way Method(0)
var params []reflect.Value // The statement []reflect.Value
params = append(params, reflect.ValueOf(10))
params = append(params, reflect.ValueOf(40))
res := val.Method(0).Call(params) // The parameter passed in is []reflect.Value, return []reflect.Value
fmt.Println("res=", res[0].Int()) // Return results , The result is []reflect.Value*/
}
func main() {
// Created a Monster example
var a Monster = Monster{
Name: " Yellow rat wolf essence ",
Age: 400,
Score: 30.8,
}
// take Monster Instance passed to TestStruct function
TestStruct(a)
}
边栏推荐
- 西门子低代码平台通过Database Connector 连接Mysql 实现增删改查
- [LeetCode] 只出现一次的数字【136】
- 手机开户一般哪个证券公司好?另外,手机开户安全么?
- The concept and significance of mean, variance, standard deviation and covariance
- Head pressing Amway good-looking and practical dispensing machine SolidWorks model material here
- AI首席架构师9-胡晓光 《飞桨模型库与行业应用》
- 333333333333333333333333333333
- Jetpack之Room的使用,结合Flow
- Use of jetpack's room in combination with flow
- FPGA Development (2) -- IIC communication
猜你喜欢

Construction of module 5 of actual combat Battalion

设置安全组、域名备案、申请ssl证书

Leetcode (76) -- Minimum Covering substring

@Scheduled注解的坑,我替你踩了

FPGA Development (2) -- IIC communication

Sword finger offer 13 Range of motion of robot

FPGA开发(1)——串口通信

这个简单的小功能,半年为我们产研团队省下213个小时

Applet plug-in access, development and precautions

Halcon实用:焊点检出设计思路
随机推荐
Solr基础操作1
@Scheduled注解的坑,我替你踩了
Solr基础操作2
Jetpack之Room的使用,结合Flow
500 error occurred after importing skins folder into solo blog skin
剑指 Offer 14- I. 剪绳子
LC:有效的数独 + 旋转图像
Solr基础操作
[leetcode] a number that appears only once [136]
【微信小程序】认识小程序项目的基本组成结构
二叉搜索树 230. 二叉搜索树中第K小的元素 1038. 从二叉搜索树到更大和树
穿越过后,她说多元宇宙真的存在
[wechat applet] understand the basic composition of the applet project
I wonder if I can open an account today? In addition, is it safe to open an account online now?
Profit distribution and taxation of funds
剑指 Offer 15. 二进制中1的个数
剑指 Offer 14- II. 剪绳子 II
25 interview questions about Apache
6.29 problem solving
How about counting Berry Pie 4? What are the possible ways to play?