Go语言中使用反射的方法

作者:不吃皮蛋 时间:2023-07-22 22:31:48 

本文实例讲述了Go语言中使用反射的方法。分享给大家供大家参考。具体实现方法如下:

// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}

创建实例如下:

shabushabu = Dish.new
shabushabu.instance_variables # => []
shabushabu.name = "Shabu-Shabu"
shabushabu.instance_variables # => ["@name"]
shabushabu.origin = "Japan"
shabushabu.instance_variables # => ["@name", "@origin"]

完整代码如下:

package main
import(
  "fmt"
  "reflect"
)
 
func main(){
  // iterate through the attributes of a Data Model instance
  for name, mtype := range attributes(&Dish{}) {
    fmt.Printf("Name: %s, Type %s\n", name, mtype.Name())
  }
}
 
// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}
 
// Example of how to use Go's reflection
// Print the attributes of a Data Model
func attributes(m interface{}) (map[string]reflect.Type) {
  typ := reflect.TypeOf(m)
  // if a pointer to a struct is passed, get the type of the dereferenced object
  if typ.Kind() == reflect.Ptr{
    typ = typ.Elem()
  }
 
  // create an attribute data structure as a map of types keyed by a string.
  attrs := make(map[string]reflect.Type)
  // Only structs are supported so return an empty result if the passed object
  // isn't a struct
  if typ.Kind() != reflect.Struct {
    fmt.Printf("%v type can't have attributes inspected\n", typ.Kind())
    return attrs
  }
 
  // loop through the struct's fields and set the map
  for i := 0; i < typ.NumField(); i++ {
    p := typ.Field(i)
      if !p.Anonymous {
        attrs[p.Name] = p.Type
      }
     }
  return attrs
}

希望本文所述对大家的Go语言程序设计有所帮助。

标签:Go语言,反射
0
投稿

猜你喜欢

  • Python实现自动化处理PDF文件的方法详解

    2024-01-02 07:02:21
  • JavaScript事件冒泡

    2009-12-28 13:21:00
  • SQLServer2005 XML数据操作代码

    2024-01-27 11:50:17
  • sql中的常用的字符串处理函数大全

    2024-01-19 21:37:41
  • Python MySQL数据库基本操作及项目示例详解

    2024-01-13 06:15:27
  • Python入门第1/10页

    2023-03-19 19:34:34
  • Python解析pcap文件示例

    2023-05-16 00:08:45
  • 在Django的模型中添加自定义方法的示例

    2021-12-07 17:14:58
  • win10 + anaconda3 + python3.6 安装tensorflow + keras的步骤详解

    2021-05-18 10:22:32
  • mysql随机抽取一定数量的记录实例讲解

    2024-01-21 07:19:38
  • golang 两个go程轮流打印一个切片的实现

    2024-02-12 09:11:29
  • Mysql联合查询UNION和UNION ALL的使用介绍

    2024-01-17 22:14:08
  • Python face_recognition实现AI识别图片中的人物

    2023-08-14 21:34:35
  • python游戏库pygame经典教程(推荐!)

    2022-10-02 06:26:11
  • ASP.NET 2.0中的数据操作之九:跨页面的主/从报表

    2023-07-19 20:28:42
  • Python中文分词工具之结巴分词用法实例总结【经典案例】

    2023-05-05 01:46:30
  • 将mater库中的系统存储过程批量生成*.sql文件 通用且非常实用

    2012-06-06 20:03:43
  • MySQL实现分页查询的方法

    2024-01-17 13:52:32
  • python进程管理工具supervisor使用实例

    2022-08-24 13:47:03
  • mybatis+mysql 使用存储过程生成流水号的实现代码

    2024-01-18 11:09:56
  • asp之家 网络编程 m.aspxhome.com