How to use reflection in go language _golang

Source: Internet
Author: User
Tags reflection

The example in this article tells you how to use reflection in the go language. Share to everyone for your reference. The implementation methods are as follows:

Copy Code code as follows:
Data Model
Type Dish struct {
Id int
Name string
Origin string
Query func ()
}

Create an instance as follows:

Copy Code code as follows:
Shabushabu = Dish.new
Shabushabu.instance_variables # => []
Shabushabu.name = "Shabu-shabu"
Shabushabu.instance_variables # => ["@name"]
Shabushabu.origin = "Japan"
Shabushabu.instance_variables # => ["@name", "@origin"]

The complete code is as follows:

Copy Code code as follows:
Package Main
Import
"FMT"
"Reflect"
)

Func Main () {
Iterate through the attributes of a Data Model instance
For name, Mtype: = Range attributes (&dish{}) {
Fmt. Printf ("Name:%s, Type%s\n", Name, Mtype.) Name ())
}
}

Data Model
Type Dish struct {
Id int
Name string
Origin string
Query func ()
}

Example of how to use go ' s reflection
Print the attributes of a Data Model
Func attributes (M interface{}) (Map[string]reflect. Type) {
Typ: = reflect. TypeOf (M)
If a pointer to a struct be passed, get the type of the Dereferenced object
If Typ. Kind () = = reflect. ptr{
Typ = Typ. Elem ()
}

Create an attribute data structure as a map of the types keyed by a string.
Attrs: = Make (Map[string]reflect. Type)
Only structs are supported I return a empty result if the passed object
isn ' t a struct
If Typ. Kind ()!= reflect. Struct {
Fmt. Printf ("%v type can ' t have attributes inspected\n", Typ. Kind ())
Return Attrs
}

Loop through the struct ' s fields and set the map
For I: = 0; I < Typ. Numfield (); i++ {
P: = Typ. Field (i)
If!p.anonymous {
Attrs[p.name] = P.type
}
}
Return Attrs
}

Hopefully this article will help you with your go language program.

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.