当前位置:网站首页>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)
}
边栏推荐
- 招商证券靠谱吗?开股票账户安全吗?
- 剑指 Offer 13. 机器人的运动范围
- [wechat applet] understand the basic composition of the applet project
- Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
- 【一起上水硕系列】Day 8
- Cacti关于spine轮询的设置
- Bee common configuration
- Halcon实用:焊点检出设计思路
- Matplotlib histogram of Matplotlib visualization plt bar()
- Is China Merchants Securities reliable? Is it safe to open a stock account?
猜你喜欢

Head on Amway! Good looking and practical motor SolidWorks model material see here

Set up security groups, record domain names, and apply for SSL certificates

Et la tarte aux framboises 4? Quels sont les jeux possibles?

FPGA Development (2) -- IIC communication

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

LC: maximum subarray and

Create an API rapid development platform, awesome!

This simple little function saves 213 hours for our production research team in half a year

Yunhe enmo, gaiguoqiang, identify it and grasp it before the domestic database boils

333333333333333333333333333333
随机推荐
Xutils3 transfer set
手机开户一般哪个证券公司好?另外,手机开户安全么?
FPGA开发(1)——串口通信
Solr basic operation 1
Leetcode(680)——验证回文字符串 Ⅱ
6.29日刷题题解
Leetcode (76) -- Minimum Covering substring
FPGA开发(2)——IIC通信
LC: effective Sudoku + rotating image
Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
What is flush software? Is it safe to open an account online?
Cartoon security HIDS, EDR, NDR, XDR
HPE launched ARM CPU general server product
[Shangshui Shuo series] day 8
设置安全组、域名备案、申请ssl证书
Under the epidemic, I left my job for a year, and my income increased 10 times
C pointer advanced 1-- > character pointer, array pointer, pointer and array parameter transfer, function pointer
【微信小程序】认识小程序项目的基本组成结构
Et la tarte aux framboises 4? Quels sont les jeux possibles?
LC:最大子数组和