本文实例讲述了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
更新日志
- 高胜美《经典金选》1991-1994 4CD[WAV整轨][1.9G]
- 【迷幻电音】AstralWaves-2023-Singles,RemixesandRaritiesII(FLAC)
- 中唱唱片群星《好歌珍藏-游子情深》2CDWAV
- 张国荣.2011-极品天碟LPCD45II(雨果版)【环球】【WAV+CUE】
- 张学友《醒着做梦》[DFF][1.1G]
- 刘惜君 《如我》[WAV分轨][403M]
- 白玛多吉《梦》限量1:1母盘直刻[低速原抓WAV+CUE][508M]
- 魏金栋-金歌新曲-梦里全是桂花香2CD[天凡之音][WAV+CUE]
- 鲛岛有美子-樱花赋HQCD[天龙][WAV+CUE]
- [In-Akustik7506]ReferenceSoundEdition-GreatWomenOfSong(2014)HQCD[WAV+CUE]
- 日本EMI超级名盘TOGE-11035-36BeethovenFidelio-Furtwngler
- 宝丽金50周年2010《古典篇》3CD限定盘[低速原抓WAV+CUE]
- 华纳群星.1992-永远新一天华纳15周年金钻群星演唱会2CD【华纳】【WAV+CUE】
- 原声《功夫熊猫4 OST》[FLAC][545M]
- 陈奕迅《酝酿》[WAV分轨][502M]