国产探花免费观看_亚洲丰满少妇自慰呻吟_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語言程序設計有所幫助。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 突泉县| 宁化县| 深州市| 柯坪县| 巴林左旗| 昭平县| 龙南县| 吴堡县| 四子王旗| 鹤山市| 且末县| 柳林县| 旌德县| 莱芜市| 汨罗市| 内江市| 永兴县| 都昌县| 游戏| 麻城市| 旌德县| 兴文县| 北安市| 巴青县| 富阳市| 怀集县| 安多县| 聂拉木县| 静安区| 拜泉县| 法库县| 岳西县| 子洲县| 巴楚县| 略阳县| 潮安县| 建瓯市| 泾源县| 孟津县| 独山县| 师宗县|