当前位置:网站首页>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)
}
边栏推荐
- Leetcode (76) -- Minimum Covering substring
- Xutils3 transfer set
- modelsim的TCL脚本的define incdir命令解析
- AI empowers new retail, the way to win "wisdom" lies in ecological thinking | selected excerpts from digital intelligence night talk live broadcast
- 【微信小程序】认识小程序项目的基本组成结构
- Sword finger offer 14- ii Cutting rope II
- Siemens low code platform connects MySQL through database connector to realize addition, deletion, modification and query
- Virtual machine online migration based on openstack
- 25 interview questions about Apache
- Use of jetpack's room in combination with flow
猜你喜欢

Software testing interface testing JMeter 5.5 installation tutorial

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

Leetcode 1385. Distance value between two arrays

数莓派 4怎么样?可能的玩法有哪些?

Siemens low code platform connects MySQL through database connector to realize addition, deletion, modification and query

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

FPGA Development (1) -- serial port communication

开始“收割”!钉钉调整“钉钉Teambition”免费用人数上限,超十人将无法正常用

Software testing interface testing postman testing tool interface testing process execution interface testing interface associated environment variables and global variables built-in dynamic parameter

333333333333333333333333333333
随机推荐
MetaQ集群安装测试
手机开户一般哪个证券公司好?另外,手机开户安全么?
I wonder if I can open an account today? In addition, is it safe to open an account online now?
Under the epidemic, I left my job for a year, and my income increased 10 times
333333333333333333333333333333
shell-位置参数变量和预定义变量
Cartoon security HIDS, EDR, NDR, XDR
穿越过后,她说多元宇宙真的存在
网上开户选哪个证券公司?还有,在线开户安全么?
【一起上水硕系列】Day 8
Simple understanding of B tree and b+ tree
Et la tarte aux framboises 4? Quels sont les jeux possibles?
LC: effective Sudoku + rotating image
Solr基础操作
Solr basic operation 5
Test d'installation du cluster metaq
Software testing interface testing JMeter 5.5 installation tutorial
matplotlib matplotlib可视化之柱状图plt.bar()
Leetcode(680)——验证回文字符串 Ⅱ
The concept and significance of mean, variance, standard deviation and covariance