主页 > 知识库 > Go语言中使用反射的方法

Go语言中使用反射的方法

热门标签:服务外包 网站排名优化 呼叫中心市场需求 铁路电话系统 Linux服务器 地方门户网站 AI电销 百度竞价排名

本文实例讲述了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语言程序设计有所帮助。

您可能感兴趣的文章:
  • golang之反射和断言的具体使用
  • 详解Golang利用反射reflect动态调用方法
  • 浅谈Go语言中的结构体struct & 接口Interface & 反射
  • Go语言学习笔记之反射用法详解
  • Go语言中反射的正确使用
  • 谈谈Go语言的反射三定律
  • go语言通过反射获取和设置结构体字段值的方法
  • 图文详解go语言反射实现原理

标签:崇左 仙桃 衡水 铜川 兰州 黄山 湘潭 湖南

巨人网络通讯声明:本文标题《Go语言中使用反射的方法》,本文关键词  ;如发现本文内容存在版权问题,烦请提供相关信息告之我们,我们将及时沟通与处理。本站内容系统采集于网络,涉及言论、版权与本站无关。
  • 相关文章
  • 收缩
    • 微信客服
    • 微信二维码
    • 电话咨询

    • 400-1100-266