佳木斯湛栽影视文化发展公司

主頁 > 知識(shí)庫 > Go語言中使用反射的方法

Go語言中使用反射的方法

熱門標(biāo)簽:服務(wù)外包 網(wǎng)站排名優(yōu)化 呼叫中心市場(chǎng)需求 鐵路電話系統(tǒng) Linux服務(wù)器 地方門戶網(wǎng)站 AI電銷 百度競(jìng)價(jià)排名

本文實(shí)例講述了Go語言中使用反射的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

復(fù)制代碼 代碼如下:
// Data Model
type Dish struct {
  Id  int
  Name string
  Origin string
  Query func()
}

創(chuàng)建實(shí)例如下:

復(fù)制代碼 代碼如下:
shabushabu = Dish.new
shabushabu.instance_variables # => []
shabushabu.name = "Shabu-Shabu"
shabushabu.instance_variables # => ["@name"]
shabushabu.origin = "Japan"
shabushabu.instance_variables # => ["@name", "@origin"]

完整代碼如下:

復(fù)制代碼 代碼如下:
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
}

希望本文所述對(duì)大家的Go語言程序設(shè)計(jì)有所幫助。

您可能感興趣的文章:
  • golang之反射和斷言的具體使用
  • 詳解Golang利用反射reflect動(dòng)態(tài)調(diào)用方法
  • 淺談Go語言中的結(jié)構(gòu)體struct & 接口Interface & 反射
  • Go語言學(xué)習(xí)筆記之反射用法詳解
  • Go語言中反射的正確使用
  • 談?wù)凣o語言的反射三定律
  • go語言通過反射獲取和設(shè)置結(jié)構(gòu)體字段值的方法
  • 圖文詳解go語言反射實(shí)現(xiàn)原理

標(biāo)簽:崇左 仙桃 衡水 銅川 蘭州 黃山 湘潭 湖南

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Go語言中使用反射的方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    五家渠市| 三明市| 内乡县| 绥阳县| 营山县| 本溪| 旬邑县| 泽普县| 大化| 庆元县| 宜宾市| 灵石县| 元阳县| 阳山县| 巴林左旗| 洛川县| 邯郸县| 察隅县| 建始县| 武川县| 巧家县| 郴州市| 巴彦淖尔市| 瑞丽市| 禄丰县| 凤冈县| 靖边县| 镇巴县| 高州市| 桓仁| 漳浦县| 凤台县| 柘城县| 五指山市| 甘孜县| 祁门县| 芜湖市| 四会市| 治多县| 上饶县| 宁化县|