• 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
    ", 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
    ", 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 }
  • 相关阅读:
    纸牌游戏
    万圣节派对
    士兵杀敌(三)简单线段树
    百度之星2016资格赛之部分题解
    hdu Simpsons’Hidden Talents(kmp)
    滑梯理论
    PAP认证方式原理和实现
    Google的Protobuf协议分析
    HMac基本介绍
    为Tcl编写C的扩展库
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/3296945.html
Copyright © 2020-2023  润新知