国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Golang > 正文

Go語言中使用反射的方法

2020-04-01 19:21:33
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了Go語言中使用反射的方法,實例分析了Go語言實現反射的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
 

本文實例講述了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語言程序設計有所幫助。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 二手房| 诸暨市| 柳江县| 邹平县| 安宁市| 大安市| 徐汇区| 墨江| 航空| 牡丹江市| 灵石县| 重庆市| 邹城市| 军事| 铁力市| 义马市| 奉节县| 丹棱县| 年辖:市辖区| 云霄县| 泸定县| 磐安县| 英吉沙县| 永福县| 香格里拉县| 澳门| 罗江县| 甘洛县| 宣化县| 永康市| 株洲县| 松潘县| 仪陇县| 德州市| 盘山县| 盐津县| 女性| 青冈县| 九寨沟县| 漠河县| 平南县|