Golang Type Assertion and reflection

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

The session ("user") is set on another page and stores a models. struct of user type
var user models. User

U: = this. GetSession ("user") gets session user, where U is a interface

user = U. (Models. User) Type assertion, I assert that the type of U is models.user type, and then I assign him to another models.user type of variable

Fmt. Println (user. ID) Here I can access the value of the session user


U: = this. GetSession ("user")//Get a interface
V: = reflect. ValueOf (U)//Reflection get the type of this variable
Fmt. Println (V.field (0). Int ())//Fetch the value stored in the No. 0 grid
Fmt. Println (V.elem (). Field (1). String ())//Fetch the value stored in the 1th grid
T: = reflect. TypeOf (U)//Get the type of this variable
Fmt. Println (t)


var acc models. Account
Acc. Username = "Hello"
Val: = reflect. VALUEOF (ACC). Fieldbyname ("Username")//Please take the Username field in the reflection


var acc models. Account
Acc. Username = "Hello"
P: = reflect. ValueOf (&ACC. Username)//Reflection value
V: = P.elem ()//Reflection object P is not addressable, but does not want to set p, (in fact) is *p. To get the contents of P, call the Elem method on the value, point to it indirectly from the pointer, and then save the reflection value as the result of the V
V.setstring ("WORLDV. SetString ("World")//reflection to assign values to an object
Fmt. PRINTLN (ACC)

Func Test (a string) string {return A}func main () {a: = "sssssss" args: = []reflect. Value{reflect. ValueOf (a)}//obtained a []reflect. VALUEC: = reflect. ValueOf (Test). Call (args)//The value of the reflection function and calls FMT. Println (c)}


Get a type of reflection
V: = reflect. ValueOf (user)
Fmt. Println (V.type (). String ())//Get a type of reflection

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.