Go语言(三)反射机制

 1 package main
 2  
 3 import(
 4   "fmt"
 5   "reflect"
 6 )
 7  
 8 func main(){
 9   // iterate through the attributes of a Data Model instance
10   for name, mtype := range attributes(&Dish{}) {
11     fmt.Printf("Name: %s, Type %s\n", name, mtype.Name())
12   }
13 }
14  
15 // Data Model
16 type Dish struct {
17   Id  int
18   Name string
19   Origin string
20   Query func()
21 }
22  
23 // Example of how to use Go's reflection
24 // Print the attributes of a Data Model
25 func attributes(m interface{}) (map[string]reflect.Type) {
26   typ := reflect.TypeOf(m)
27   // if a pointer to a struct is passed, get the type of the dereferenced object
28   if typ.Kind() == reflect.Ptr{
29     typ = typ.Elem()
30   }
31  
32   // create an attribute data structure as a map of types keyed by a string.
33   attrs := make(map[string]reflect.Type)
34   // Only structs are supported so return an empty result if the passed object
35   // isn't a struct
36   if typ.Kind() != reflect.Struct {
37     fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
38     return attrs
39   }
40  
41   // loop through the struct's fields and set the map
42   for i := 0; i < typ.NumField(); i++ {
43     p := typ.Field(i)
44       if !p.Anonymous {
45         attrs[p.Name] = p.Type
46       }
47      }
48  
49   return attrs
50 }

 

转载于:https://www.cnblogs.com/xuxu8511/p/3296945.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值