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 }

 

posted on 2013-09-02 17:35  笔记吧... 可能只有自己看得懂  阅读(917)  评论(0编辑  收藏  举报