In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on the "Golang language reflection sample tutorial", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn the "Golang language reflection sample tutorial"!
1. Brief introduction to reflection 1.1 what is reflection?
The Go language provides a mechanism to update and check the values of variables, the methods of calling variables, and the inherent operations supported by variables at run time, but the specific types of these variables are not known at compile time. This mechanism is called reflection. Reflection also allows us to treat the type itself as a value type of the first type.
Reflection refers to the ability to access and modify the program itself when the program is running, the variable is converted to the memory address when the program is compiled, the variable name is not written to the executable part by the compiler, and the program cannot get its own information when running the program.
For instance
Usually we define variables as orthophoto.
Var an int
Define the variable an as an int type
Now I don't know what type variable an is, but I can also know where variable a comes from through reflection! What type is it?!
Type FanOne struct {name string} func main () {var an int = 1 var d FanOne fmt.Println (reflect.TypeOf (a)) / / int / / here you get the type of a! Pay attention to the type! Not a category! Although this type and category are the same / / I'll talk about the difference between Type and Kind later. Fmt.Println (reflect.ValueOf (a). Kind ()) / / int / / so you get the category of a It is judged by the value of a that the category fmt.Println (reflect.TypeOf (d)) / / main.FanOne / / type is main.FanOne is the FanOne fmt.Println (reflect.ValueOf (d) .Kind ()) / / struct / / category is the type name and type of struct / / output d defined in main The type name is FanOne / / and FanOne belongs to a structure category, so the category is struct}
So this category and type are sometimes the same and sometimes different.
1.2 Why do I need reflection?
In development, when we deal with the value of a function, but in order to ensure that this function can accept more types of values, because go is a strongly typed language, although interface can accept all data types, when dealing with data, the code will be very redundant when dealing with different types. So we can use reflection to judge and process the incoming parameters.
See the example for details.
2. Reflect package 2.1 basic reflection reflect.TypeOf () / / gets the type of variable, returns reflect.Type type reflect.ValueOf () / / gets the value of variable, returns reflect.Value type reflect.Value.Kind () / / gets the category of variable Returns a constant reflect.Value.Interface () / / converted to interface {} type 2.2 reflection and pointer
When you get a reflection object from a pointer in a Go language program, you can get the element type that the pointer points to through the reflect.Elem () method. This process is called fetching the element, which is equivalent to doing a * operation on the pointer type variable.
Reflect.ValueOf (xxx) .Elem () 2.3Reflections and objects
You can use reflect.new (xxx) or reflect.zero (xxx) to reflect and create objects of the original type.
Func CreatePrimitiveObjects (t reflect.Type) reflect.Value {return reflect.Zero (t)}
You can also use the
Reflect.New ()
To create the original object.
2.4 reflection and function
If the type of the value in the reflected value object (reflect.Value) is a function, you can call the function through reflect.Value. When calling a function with reflection, you need to pass the parameters into the Call () method after being constructed using the slice [] reflect.Value of the reflection value object. When the call is completed, the return value of the function is returned through [] reflect.Value.
The type (Type) of both functions and methods in reflection is reflect.Func. If you want to call a function, you can use the Call () method of Value, for example:
Package mainimport ("fmt"reflect") func FanOne () string {return "one button three links"} func FanOneWoW (a string) string {return fmt.Sprintf ("% s want to give FanOne one button three links oh ~" A)} func main () {FanOneNotArgs: = reflect.ValueOf (FanOne). Call ([] reflect.Value {}) / / No parameter FanOneHaveArgs: = reflect.ValueOf (FanOneWoW) .Call ([] reflect.Value {reflect.ValueOf ("I")}) / / reflection example with parameters fmt.Println (FanOneNotArgs [0]) fmt.Println (FanOneHaveArgs [0])} 2.5
Fill in the fn function so that the output is
Do not use any switch or if or other select statements.
Func fn (callback interface {}, bytes [] byte) {/ / coding} type aaa struct {Name string `json: "name" `Age int `json: "age" `} func Test (t * testing.T) {fn (func (a [] * aaa) string {aaas: = a for i Item: = range aaas {fmt.Println (I, item)} fmt.Println ("12312312,", aaas) return "xxxx"}, [] byte ("[{\" name\ ":\" 111\ ",\" age\ ": 1}, {\" name\ ":\" gsjk\ " \ "age\": 2}] ") fn (func (a [] aaa) string {aaas: = a for i, item: = range aaas {fmt.Println (I, item)} fmt.Println (" 12312312, "aaas [0]) return" xxxx "} [] byte ("[{\" name\ ":\" 1111\ ",\" age\ ": 1}, {\" name\ ":\" gsjk\ ",\" age\ ": 2}]") fn (func (a * aaa) string {fmt.Println ("12312312,", a) aaas: = a fmt.Println ("12312312,") Aaas) return "xxxx"}, [] byte ("{\" name\ ":\" gsjk\ ",\" age\ ": 2}") fn (func (a string) string {fmt.Println ("12312312,", a) aaas: = a fmt.Println ("12312312,", aaas) return "xxxx"} [] byte ("\" sss\ ") fn (func (an int) string {fmt.Println (" -, ", a) aaas: = a fmt.Println (" -, ", aaas) return" xxxx "}, [] byte (" 123"))}
(1) the first is the knowledge of test:
The name must have _ test, otherwise it seems to make an error, that's what I am.
Go test xxx_test.gogo test-v xxx_test.go
(2) the second is to understand the anonymous function in fn ().
Take it out alone.
Func (a [] * aaa) string {aaas: = a for i, item: = range aaas {fmt.Println (I, item)} fmt.Println ("12312312,", aaas) return "xxxx"}, [] byte ("[{\" name\ ":\" 111\ " \ "age\": 1}, {\ "name\":\ "gsjk\",\ "age\": 2}] "))
You can see that this is an array of type * aaa. So our task is to reflect the anonymous function in the fn function, and then call the reflected anonymous function and pass the parameters into it.
The following is the first one as an example
(3) well, let's first ValueOf and TypeOf this interface {}, and then look at the various values of this anonymous function.
Func fn (callback interface {}, bytes [] byte) {v: = reflect.ValueOf (callback) / / 0xbaff40 t: = reflect.TypeOf (callback) / / func ([] * main.aaa) string}
We can see that the Type of the input function is func ([] * main.aaa) string, so we can use the
ParamsValue: = t.In (0) / / [] * main.aaa
Get the incoming parameters of the anonymous function
(4) key points!
The paramsValue we got is just [] * main.aaa name, and this value is of type reflect.type! 、
We want the type [] * main.aaa, not the name!
So we need to create an object of this type, and then switch to the corresponding type.
Val: = reflect.New (paramsValue) newT: = val.Interface () fmt.Printf ("valValue:%v, valType:% T\ n", val,val) / / valValue:& [], valType: reflect.Value fmt.Printf ("newTValue:%v, newTType:% T\ n", newT,newT) / / newTValue:& [], newTType: * [] * main.aaa
We are going to create such a category of objects, although go is not object-oriented programming, but it can be understood this way.
Why do you want this type?
Because later, the bytes slice is deserialized into this type of variable, which is passed into the anonymous function!
If v.IsValid () {/ / function valid or not _ = json.Unmarshal (bytes, newT) / / byte to json}
So here's the problem again. The value passed in is of type [] * main.aaa, but we've got the type of * [] * main.aaa, which is obviously wrong.
Fmt.Printf ("call callback ends callback ret =% s\ n", v.Call ([] reflect.Value {reflect.ValueOf (newT)})) fmt.Printf ("*\ n")
Wrong report! Wrong type!
Then we have to go to * operation. In reflection, it is not directly added * removed! The following is not good in reflection.
Package mainimport ("fmt"reflect") func main () {var an int = 1 var b * int = & a var c * * int = & b fmt.Println (a, * b, c) fmt.Println (reflect.TypeOf (a)) fmt.Println (reflect.TypeOf (* b)) fmt.Println (reflect.TypeOf (b))}
So we can remove this with reflect.Elem () *
Fmt.Printf ("call callback ends callback ret =% s\ n", v.Call ([] reflect.Value {reflect.ValueOf (newT). Elem ()}) fmt.Printf ("*\ n")
It's done!
At this point, I believe you have a deeper understanding of the "Golang language reflection sample tutorial". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.