Three Laws of Golang reflection and reflection

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

listening to reflection is a mechanism for checking the type of a variable when the Golang program is running. This is also considered to be the basis for Golang meta-programming, since reflection can draw data about the structure of variables (" data about Data ") . Beginner reflex, will feel some "iffy". I am here to explore the meaning of reflection, and interpret the three principles of reflection (http://blog.golang.org/laws-of-reflection).


0 Understanding reflection connotation from types and methods

Listen at a basic level, reflection is just an algorithm that examines the types and values stored in an interface variable. Using the reflection mechanism, you first need to import the reflect package, Reflect reflect. Type and reflect. Value These two types make it possible to access the contents of a variable. In relation to this, there are two simple functions, reflect. Typeof and reflect. Valueof reflect separately from the interface values. Type and reflect. Value

Listening to beginners may think reflect. Type and reflect. Value is a side-by -side relationship, but in fact they are a containment relationship, and we understand this by combining a piece of code.

Import Listen (Listen to "FMT" listen to "reflect") listen to Func listen to main () listen {Listen to the var listen x listen to float64 listen = Listen to the 1.1 listen to listen to the FMT.PRINTLN ("reflect. Value: "Listen to reflect. ValueOf (x)) listen and listen to the FMT. Println ("reflect. Type: "Listen to reflect. TypeOf (x)) listen to V listen: = Listen to the reflect. ValueOf (x) Listen and listen to the FMT. Println ("reflect. Type: ", V.type ()) Listen and listen to the FMT. Println ("Actual Listen to Value:", listen to V. Float ()) Listen and listen to the FMT. Println ("Kind listen to is listen to float64?", listen to V. Kind () Listen = = listen to reflect. Float64)}

Its output is:

listening to the program and its results, we can find:Golanguage, each value contains two content: the type and the actual value. From a type point of view,Reflect. Valueis a about<type,the actual value>the two-tuple, whileReflect. Typeis the type of the value, and both contain the relationship. From a methodological point of view,Reflect. TypeOfand the(Reflect. ValueOf (x)). Typecan all go backReflect. Type;(Reflect. ValueOf (x)). Floatyou can return the actual value (a similar method also includes(Reflect. ValueOf (x)). Int,(Reflect. ValueOf (x)). Bool, etc.);(Reflect. ValueOf (x)). Kindyou can return a constant-defined type.

Listen to the above analysis, we can draw a more intuitive image of the value, type, the actual value of the relationship.

listen also,Golang takes a static type mechanism,TypeOf Returns a static type, butKind returns the underlying type. We also validate this passage with a piece of code.

Import Listen (Listen to "FMT" listen to "reflect") listen to the type listen to myint listen int listen to Func listen to the main () hear {listen to hear Var listen x listen to Myint listen = Listen to listen to the 1 listen to the V listen: = Listen to the reflect. ValueOf (x) Listen and listen to the FMT. Println ("reflect. Type: ", listen v. Type ()) Listen and listen to the FMT. Println ("Kind listen to is listen int?", listen to V. Kind () Listen = = listen to reflect. INT)}

Output:



1 Rule one: Reflection from the interface value to the Reflection object (Reflection goes from interface value Toreflection object)

listening to the previous article is actually the reflection from the interface value to the reflection object, representing the method as reflect. ValueOf and reflect. TypeOf. Maybe someone would ask, interface? Where is the interface? Let's take a look at some of the previous references to the declaration of these two functions, the parameters of the function are NULL interfaces, the interface is actually there. for a golang interface, you can see my other blog post, "Interfaces in Golang".

Func Listen valueof (I listen to interface{}) listen to Valuefunc listen to typeof (I listen to interface{}) listen to type


2 Law Two: Reflection from the reflected object to the interface value (Reflection goes from Reflection object to interface value)

Listen, listen. from reflect. Value can be used to restore the interface value using the Interface method, which efficiently packages the type and value information into the interface expression and returns the result. Method declaration:

Func Listen (v Listen value) listen to interface () listen to interface{}

Listen , you can print the expression value of the float64 by reflecting the object v.

Y listen: =v.interface (). (float64) Listen/Listen y listen to float64 for type. Fmt. Println (y)

there is a more concise implementation of listening. FMT. Println,fmt. Printf, among other functions that pass an empty interface value as a parameter, is unpacked inside the FMT package in the same way as in the previous example. So the correct print reflect. The content of Value is formatted to print the results of the Interface method (formatted print routine). Listen

Fmt. Println (V.interface ())

listen to why not FMT. Println (v)? Because v is a reflect. Value; This is what you want to get is the actual value it holds.

Listen to our edit the previous code is also validated:

Func listen to Main () listen {Listen to the var listen x listen float64 listen = Listen to the 1.1 listen to listen to the FMT.PRINTLN ("reflect. Value: "Listen to reflect. ValueOf (x)) listen and listen to the FMT. Println ("reflect. Type: "Listen to reflect. TypeOf (x)) listen and listen to V listen: = Listen (reflect. ValueOf (x)) listen and listen to the FMT. Println ("reflect. Type: ", listen v. Type ()) Listen and listen to the FMT. Println ("Actual listen Value (interface):", listen v. Interface ()) Listen and listen to the FMT. Println ("Kind listen to is listen to float64?", listen to V. Kind () Listen = = listen to reflect. Float64)}

Its output:

Listen further, we can modify the above relationship, the new diagram is more concise and elegant:


3. In order to modify the reflected object, its value must be set (toModify a reflectionobject, the value must is settable)

Listen to reflective objects by setfloat and other methods to set the value by Canset judgment can be set. But there is a hole in it, and some values are not set. We still look at it through a piece of code.

Import Listen (listen to listen to "FMT" listen to listen to "reflect") listen to Func listen to main () hear {listen to hear the Var listen x listen to float64 listen = Listen to listen to the 1.1 listen to hear V listen: = Listen to the reflect. ValueOf (x) Listen and listen to the FMT. Println ("Settability Listen V:", V.canset ()) Listen and Hear v. SetFloat (1.2)}

Its output


listen to the results show that the reflective object v is not set, if hard to set, there will be Panic exception.

Listen, why can't you set it up? We can think of this problem from the perspective of function transfer. v: = Reflect. ValueOf (x) itself. As we all know, the parameters of the value pass cannot be really modified.

Listen, I had this idea at first: v and x Span style= "font-family: ' The song Body '; > is not a variable, cannot be modified, but Should be able to be modified AH. Completely from the formal point of view, this seems to make sense. But think of one more layer, if allowed to execute, although v can be modified, but cannot update x x x

Listen let's think about it again in terms of function transfer. If the passing copy cannot be modified, then we pass the pointer through it. Let's try it out:

Func listen to Main () listen {Listen and listen to the Var listen x listen to float64 listen = Listen to listen to 1.1 listen to hear P listen: = Listen to the reflect. ValueOf (&x) Listen and listen to the FMT. Println ("Type listens to P:", P.type ()) Listen and listen to the FMT. Println ("Settability Listen to P:", P.canset ())}

listen or not. Because The actual type of P is *float64, not float64, this modification is equivalent to modifying the address directly.

Listen, we can use Elem method to modify the specific value that the pointer points to by using a pointer.

Func Listen (v Listen value) Elem () Listen value// Elem listen to returns listen to the value listen to the listen to the interface listen to the V listen to the contains listen to or listen to the listen to the pointer listen to the vpoints listen to. Listen to it listen to panics listen if listen V ' s listen to kind listen to is listen to interface listen to or listen to PTR. Listen to it listen to returns listen to the Zerovalue listen to the If listen V listen to nil.
Func listen to Main () listen {Listen and listen to the Var listen x listen to float64 listen = Listen to listen to 1.1 listen to hear P listen: = Listen to the reflect. ValueOf (&x) Listen and listen to the FMT. Println ("Type Listen to P:", P.type ()) Listen and listen to the V-listen: = Listen p. Elem () Listen and listen to the FMT. Println ("Type Listen V:", V.type ()) Listen and listen to the FMT. Println ("Settability Listen V:", V.canset ())}

Its output

Listen and listen so you can make changes. Although P is not modifiable, v can be modified. This approach is similar to referring to the reference, the incoming address, modify the address point to the specific value.


Reference

Http://blog.golang.org/laws-of-reflection

Http://www.tuicool.com/articles/VFj6ze

http://studygolang.com/articles/1468

This article from "Talking Cabbage" blog, declined reprint!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.