Go语言中如何使用反射的方法

初秋的风似一支七彩的画笔,走到哪里,哪里就披上秋的盛装,五光十色的鲜花和着七彩的蝴蝶,迎着丰收的景象。五彩缤纷的鲜花撒满大地,丰收的果园一派欣欣向荣的景象,金黄色的稻谷堆满仓,大地一片喜气洋洋。

本文实例讲述了Go语言中使用反射的方法。分享给大家供大家参考。具体实现方法如下:

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

创建实例如下:

shabushabu = Dish.new
shabushabu.instance_variables # => []
shabushabu.name = "Shabu-Shabu"
shabushabu.instance_variables # => ["@name"]
shabushabu.origin = "Japan"
shabushabu.instance_variables # => ["@name", "@origin"]

完整代码如下:

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 is 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 types keyed by a string.
attrs := make(map[string]reflect.Type)
// Only structs are supported so return an 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
}

希望本文所述对大家的Go语言程序设计有所帮助。

本文Go语言中如何使用反射的方法到此结束。欲望得不到满足痛苦;欲望一旦满足就无聊,生命就是在痛苦和无聊之间摇摆。小编再次感谢大家对我们的支持!

标签: 如何使用