本文实例讲述了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打包二进制文件的实现
背景众所周知,go语言可打包成目标平台二进制文件是其一大优势,如此go项目在服务器不需要配置go环境和依赖就可跑起来。操作需求:打包部署到centos7笔者打包...
[阅读全文]
-
-
-
-
golang语言编码规范的实现
本规范旨在为日常go项目开发提供一个代码的规范指导,方便团队形成一个统一的代码风格,提高代码的可读性,规范性和统一性。本规范将从命名规范,注释规范,代码风格和 ...
[阅读全文]
-
-
-
网友评论