本文实例讲述了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语言,反射,方法
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
更新日志
- 梁汉文《不愿一个人》华星40金唱片[WAV分轨]
- 李宗盛《李宗盛精选滚石香港黄金十年》[WAV/分轨][670MB]
- 群星 模拟之声慢刻CD《发烧宝丽金35周年》[WAV+CUE][640MB]
- 《古惑仔系列电影合集1996-1998》[FLAC/分轨][780MB]
- 鸣潮自选4星武器推荐攻略 4星自选武器哪个最好
- 鸣潮自选5星武器怎么获取 五星自选武器哪个最好
- 鸣潮联觉等级怎么提升 联觉等级升级攻略
- 甄妮《皆因你的爱》华星40金唱片[WAV分轨]
- 陈奕迅《时代曲》华星40金唱片)[WAV分轨]
- 蔡依林《2004BornToBeAStar(超级珍藏世纪精选2CD)》[WAV整轨]
- 《碧海黑帆》新赛季预告公布 又有免费试玩生怕你不玩
- 刘德华《天王巨星经典情歌典藏2CD》[WAV+CUE][1.3GB]
- 斯琴格日乐《强烈直接的音乐方式 姿态》[WAV+CUE][500MB]
- 王菲《收录12首 只爱陌生人》[WAV+CUE][540MB]
- 鸣潮清芬鱼汤制作材料是什么 清芬鱼汤制作攻略分享