当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言中使用反射的方法

Go语言中使用反射的方法

2017年12月08日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网