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.