欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go语言中使用反射的方法

程序员文章站 2022-03-21 10:22:24
本文实例讲述了go语言中使用反射的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下:// data model type dish struct {...

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