如何正確的使用Go反射機(jī)制

這篇文章將為大家詳細(xì)講解有關(guān)如何正確的使用Go反射機(jī)制,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

創(chuàng)新互聯(lián)建站自2013年起,先為銅山等服務(wù)建站,銅山等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為銅山企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。

什么是反射

大多數(shù)時(shí)候,Go中的變量,類型和函數(shù)非常簡(jiǎn)單直接。當(dāng)需要一個(gè)類型、變量或者是函數(shù)時(shí),可以直接定義它們:

type Foo struct {
 A int
 B string
}

var x Foo

func DoSomething(f Foo) {
 fmt.Println(f.A, f.B)
}

但是有時(shí)你希望在運(yùn)行時(shí)使用變量的在編寫(xiě)程序時(shí)還不存在的信息。比如你正在嘗試將文件或網(wǎng)絡(luò)請(qǐng)求中的數(shù)據(jù)映射到變量中?;蛘吣阆霕?gòu)建一個(gè)適用于不同類型的工具。在這種情況下,你需要使用反射。反射使您能夠在運(yùn)行時(shí)檢查類型。它還允許您在運(yùn)行時(shí)檢查,修改和創(chuàng)建變量,函數(shù)和結(jié)構(gòu)體。

Go中的反射是基于三個(gè)概念構(gòu)建的:類型,種類和值(Types Kinds Values)。標(biāo)準(zhǔn)庫(kù)中的reflect包提供了 Go 反射的實(shí)現(xiàn)。

反射變量類型

首先讓我們看一下類型。你可以使用反射來(lái)調(diào)用函數(shù)varType := reflect.TypeOf(var)來(lái)獲取變量var的類型。這將返回類型為reflect.Type的變量,該變量具有獲取定義時(shí)變量的類型的各種信息的方法集。下面我們來(lái)看一下常用的獲取類型信息的方法。

我們要看的第一個(gè)方法是Name()。這將返回變量類型的名稱。某些類型(例如切片或指針)沒(méi)有名稱,此方法會(huì)返回空字符串。

下一個(gè)方法,也是我認(rèn)為第一個(gè)真正非常有用的方法是Kind()。Type是由Kind組成的---Kind 是切片,映射,指針,結(jié)構(gòu),接口,字符串,數(shù)組,函數(shù),int或其他某種原始類型的抽象表示。要理解Type和Kind之間的差異可能有些棘手,但是請(qǐng)你以這種方式來(lái)思考。如果定義一個(gè)名為Foo的結(jié)構(gòu)體,則Kind為struct,類型為Foo。

使用反射時(shí)要注意的一件事:反射包中的所有內(nèi)容都假定你知道自己在做什么,并且如果使用不正確,許多函數(shù)和方法調(diào)用都會(huì)引起 panic。例如,如果你在reflect.Type上調(diào)用與當(dāng)前類型不同的類型關(guān)聯(lián)的方法,您的代碼將會(huì)panic。

如果變量是指針,映射,切片,通道或數(shù)組變量,則可以使用varType.Elem()找出指向或包含的值的類型。

如果變量是結(jié)構(gòu)體,則可以使用反射來(lái)獲取結(jié)構(gòu)體中的字段數(shù),并從每個(gè)字段上獲取reflect.StructField結(jié)構(gòu)體。 reflection.StructField為您提供了字段的名稱,標(biāo)號(hào),類型和結(jié)構(gòu)體標(biāo)簽。其中標(biāo)簽信息對(duì)應(yīng)reflect.StructTag類型的字符串,并且它提供了Get方法用于解析和根據(jù)特定key提取標(biāo)簽信息中的子串。

下面是一個(gè)簡(jiǎn)單的示例,用于輸出各種變量的類型信息:

type Foo struct {
  A int `tag1:"First Tag" tag2:"Second Tag"`
  B string
}

func main() {
  sl := []int{1, 2, 3}
  greeting := "hello"
  greetingPtr := &greeting
  f := Foo{A: 10, B: "Salutations"}
  fp := &f

  slType := reflect.TypeOf(sl)
  gType := reflect.TypeOf(greeting)
  grpType := reflect.TypeOf(greetingPtr)
  fType := reflect.TypeOf(f)
  fpType := reflect.TypeOf(fp)

  examiner(slType, 0)
  examiner(gType, 0)
  examiner(grpType, 0)
  examiner(fType, 0)
  examiner(fpType, 0)
}

func examiner(t reflect.Type, depth int) {
  fmt.Println(strings.Repeat("\t", depth), "Type is", t.Name(), "and kind is", t.Kind())
  switch t.Kind() {
  case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice:
    fmt.Println(strings.Repeat("\t", depth+1), "Contained type:")
    examiner(t.Elem(), depth+1)
  case reflect.Struct:
    for i := 0; i < t.NumField(); i++ {
      f := t.Field(i)
      fmt.Println(strings.Repeat("\t", depth+1), "Field", i+1, "name is", f.Name, "type is", f.Type.Name(), "and kind is", f.Type.Kind())
      if f.Tag != "" {
        fmt.Println(strings.Repeat("\t", depth+2), "Tag is", f.Tag)
        fmt.Println(strings.Repeat("\t", depth+2), "tag1 is", f.Tag.Get("tag1"), "tag2 is", f.Tag.Get("tag2"))
      }
    }
  }
}

變量的類型輸出如下:

Type is and kind is slice
   Contained type:
   Type is int and kind is int
 Type is string and kind is string
 Type is and kind is ptr
   Contained type:
   Type is string and kind is string
 Type is Foo and kind is struct
   Field 1 name is A type is int and kind is int
     Tag is tag1:"First Tag" tag2:"Second Tag"
     tag1 is First Tag tag2 is Second Tag
   Field 2 name is B type is string and kind is string
 Type is and kind is ptr
   Contained type:
   Type is Foo and kind is struct
     Field 1 name is A type is int and kind is int
       Tag is tag1:"First Tag" tag2:"Second Tag"
       tag1 is First Tag tag2 is Second Tag
     Field 2 name is B type is string and kind is string

Run in go playground: https://play.golang.org/p/lZ97yAUHxX

使用反射創(chuàng)建新實(shí)例

除了檢查變量的類型外,還可以使用反射來(lái)讀取,設(shè)置或創(chuàng)建值。首先,需要使用refVal := reflect.ValueOf(var) 為變量創(chuàng)建一個(gè)reflect.Value實(shí)例。如果希望能夠使用反射來(lái)修改值,則必須使用refPtrVal := reflect.ValueOf(&var);獲得指向變量的指針。如果不這樣做,則可以使用反射來(lái)讀取該值,但不能對(duì)其進(jìn)行修改。

一旦有了reflect.Value實(shí)例就可以使用Type()方法獲取變量的reflect.Type。

如果要修改值,請(qǐng)記住它必須是一個(gè)指針,并且必須首先對(duì)其進(jìn)行解引用。使用refPtrVal.Elem().Set(newRefVal)來(lái)修改值,并且傳遞給Set()的值也必須是reflect.Value。

如果要?jiǎng)?chuàng)建一個(gè)新值,可以使用函數(shù)newPtrVal := reflect.New(varType)來(lái)實(shí)現(xiàn),并傳入一個(gè)reflect.Type。這將返回一個(gè)指針值,然后可以像上面那樣使用Elem().Set()對(duì)其進(jìn)行修改。

最后,你可以通過(guò)調(diào)用Interface()方法從reflect.Value回到普通變量值。由于Go沒(méi)有泛型,因此變量的原始類型會(huì)丟失;該方法返回類型為interface{}的值。如果創(chuàng)建了一個(gè)指針以便可以修改該值,則需要使用Elem().Interface()解引用反射的指針。在這兩種情況下,都需要將空接口轉(zhuǎn)換為實(shí)際類型才能使用它。

下面的代碼來(lái)演示這些概念:

type Foo struct {
  A int `tag1:"First Tag" tag2:"Second Tag"`
  B string
}

func main() {
  greeting := "hello"
  f := Foo{A: 10, B: "Salutations"}

  gVal := reflect.ValueOf(greeting)
  // not a pointer so all we can do is read it
  fmt.Println(gVal.Interface())

  gpVal := reflect.ValueOf(&greeting)
  // it's a pointer, so we can change it, and it changes the underlying variable
  gpVal.Elem().SetString("goodbye")
  fmt.Println(greeting)

  fType := reflect.TypeOf(f)
  fVal := reflect.New(fType)
  fVal.Elem().Field(0).SetInt(20)
  fVal.Elem().Field(1).SetString("Greetings")
  f2 := fVal.Elem().Interface().(Foo)
  fmt.Printf("%+v, %d, %s\n", f2, f2.A, f2.B)
}

他們的輸出如下:

hello
goodbye
{A:20 B:Greetings}, 20, Greetings

Run in go playground https://play.golang.org/p/PFcEYfZqZ8

反射創(chuàng)建引用類型的實(shí)例

除了生成內(nèi)置類型和用戶定義類型的實(shí)例之外,還可以使用反射來(lái)生成通常需要make函數(shù)的實(shí)例。可以使用reflect.MakeSlice,reflect.MakeMap和reflect.MakeChan函數(shù)制作切片,Map或通道。在所有情況下,都提供一個(gè)reflect.Type,然后獲取一個(gè)reflect.Value,可以使用反射對(duì)其進(jìn)行操作,或者可以將其分配回一個(gè)標(biāo)準(zhǔn)變量。

func main() {
 // 定義變量
  intSlice := make([]int, 0)
  mapStringInt := make(map[string]int)

 // 獲取變量的 reflect.Type
  sliceType := reflect.TypeOf(intSlice)
  mapType := reflect.TypeOf(mapStringInt)

  // 使用反射創(chuàng)建類型的新實(shí)例
  intSliceReflect := reflect.MakeSlice(sliceType, 0, 0)
  mapReflect := reflect.MakeMap(mapType)

  // 將創(chuàng)建的新實(shí)例分配回一個(gè)標(biāo)準(zhǔn)變量
  v := 10
  rv := reflect.ValueOf(v)
  intSliceReflect = reflect.Append(intSliceReflect, rv)
  intSlice2 := intSliceReflect.Interface().([]int)
  fmt.Println(intSlice2)

  k := "hello"
  rk := reflect.ValueOf(k)
  mapReflect.SetMapIndex(rk, rv)
  mapStringInt2 := mapReflect.Interface().(map[string]int)
  fmt.Println(mapStringInt2)
}

使用反射創(chuàng)建函數(shù)

反射不僅僅可以為存儲(chǔ)數(shù)據(jù)創(chuàng)造新的地方。還可以使用reflect.MakeFunc函數(shù)使用reflect來(lái)創(chuàng)建新函數(shù)。該函數(shù)期望我們要?jiǎng)?chuàng)建的函數(shù)的reflect.Type,以及一個(gè)閉包,其輸入?yún)?shù)為[]reflect.Value類型,其返回類型也為[] reflect.Value類型。下面是一個(gè)簡(jiǎn)單的示例,它為傳遞給它的任何函數(shù)創(chuàng)建一個(gè)定時(shí)包裝器:

func MakeTimedFunction(f interface{}) interface{} {
  rf := reflect.TypeOf(f)
  if rf.Kind() != reflect.Func {
    panic("expects a function")
  }
  vf := reflect.ValueOf(f)
  wrapperF := reflect.MakeFunc(rf, func(in []reflect.Value) []reflect.Value {
    start := time.Now()
    out := vf.Call(in)
    end := time.Now()
    fmt.Printf("calling %s took %v\n", runtime.FuncForPC(vf.Pointer()).Name(), end.Sub(start))
    return out
  })
  return wrapperF.Interface()
}

func timeMe() {
  fmt.Println("starting")
  time.Sleep(1 * time.Second)
  fmt.Println("ending")
}

func timeMeToo(a int) int {
  fmt.Println("starting")
  time.Sleep(time.Duration(a) * time.Second)
  result := a * 2
  fmt.Println("ending")
  return result
}

func main() {
  timed := MakeTimedFunction(timeMe).(func())
  timed()
  timedToo := MakeTimedFunction(timeMeToo).(func(int) int)
  fmt.Println(timedToo(2))
}

你可以在goplayground運(yùn)行代碼https://play.golang.org/p/QZ8ttFZzGx并看到輸出如下:

starting
ending
calling main.timeMe took 1s
starting
ending
calling main.timeMeToo took 2s
4

關(guān)于如何正確的使用Go反射機(jī)制就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

網(wǎng)站名稱:如何正確的使用Go反射機(jī)制
URL標(biāo)題:http://bm7419.com/article48/gijjhp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開(kāi)發(fā)、App設(shè)計(jì)、搜索引擎優(yōu)化、建站公司響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

微信小程序開(kāi)發(fā)