本文实例讲述了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语言程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 群星《狂潮》夜店中文爆嗨重低音 黑胶碟2CD[低速原抓WAV+CUE]
- TraditionalMusicEnsembleofTheBNMA-BuddhistMusicoftheMingDynasty(JVC-Japan)[FLAC]
- [中国唱片]中央乐团交响乐队《绝烧HIFI典范》[WAV+CUE]
- 群星《2024好听新歌41》AI调整音效【WAV分轨】
- 张学友《吻别》MQA-UHQCD 日本压碟[原抓WAV+CUE][1G]
- 许嵩《寻宝游戏》[WAV+CUE][951M]
- 李玉刚《刚好遇见你》[WAV+CUE][970M]
- 罗文《国语精选》24K金碟限量版英皇娱乐[WAV+CUE][955M]
- 证声音乐图书馆《摇滚乐 海滩假期》[320K/MP3][50.75MB]
- 证声音乐图书馆《摇滚乐 海滩假期》[FLAC/分轨][273.06MB]
- 群星《情系民歌LP黑胶》2CD[WAV+CUE]
- 串烧歌曲《台语发烧热唱1国语发烧热唱2》2CD日版[WAV+CUE]
- 珍藏金碟《杭天琪演唱专辑》[WAV+CUE]
- 证声音乐图书馆《花火 日系爵士会》[320K/MP3][2024]
- 证声音乐图书馆《花火 日系爵士会》[FLAC/分轨][343.98MB]