zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    nginx:配置详细说明
    linux:/etc/rc.local 不能自动启动问题
    nginx:403 forbidden 二种原因
    nginx:虚拟主机配置
    linux:lnmp环境搭建
    php:mysqli扩展
    linux:磁盘的分割、检验、格式化与挂载
    webpack
    js的window.onscroll事件兼容各大浏览器
    js window事件解析(转载)
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/3296945.html
Copyright © 2011-2022 走看看