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 }
  • 相关阅读:
    css 水平垂直居中总结
    计算机网络之应用层详解
    WPF 中 InitializeComponent 不存在解决方案
    [翻译]lithium 快速上手(QuickStart)
    [翻译]lithium 安装
    [翻译]lithium介绍
    [模板]离散化
    [总结]中位数及带权中位数问题
    [总结]Floyd算法及其应用
    [模板]SPFA判负环
  • 原文地址:https://www.cnblogs.com/xuxu8511/p/3296945.html
Copyright © 2011-2022 走看看