乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      go語言reflect理解

       飲茶仙人 2018-03-24

      不少文章在講解GoLang的反射機(jī)制的時(shí)候都講的比較復(fù)雜,這里簡(jiǎn)單總結(jié)下,做一個(gè)淺顯的入門教程:

      1、TypeOf方法跟ValueOf方法

      TypeOf用來返回變量的類型,ValueOf用來返回變量的方法。

      我們?cè)诔跏蓟粋€(gè)結(jié)構(gòu)體的時(shí)候,有兩種方式,var a Struct跟a :=new(Struct),其中,前者的類型是struct,后者的類型是指針。

      package main
      
      import (
      	"fmt"
      	"reflect"
      )
      
      type MyStruct struct {
      	name string
      }
      
      func (this *MyStruct) GetName() string {
      	return this.name
      }
      
      func main() {
      	a := new(MyStruct)
      	a.name = "yejianfeng"
      	typ := reflect.TypeOf(a)
      	fmt.Println(typ)
      	fmt.Println("-------------------")
      	var b MyStruct
      	b.name = "abc"
      	fmt.Println(reflect.TypeOf(b))
      }

      輸出如下:

      *main.MyStruct

      -------------------

      main.MyStruct

      2、reflect.ValueOf(a).FieldByName方法

      如果a是結(jié)構(gòu)體,reflect.ValueOf(a).FieldByName("name")等價(jià)于a.name。

      如果是指針的話ValueOf返回的是指針的Type,它是沒有Field的,所以也就不能使用FieldByName

      3、CanSet方法

      CanSet當(dāng)Value是可尋址的時(shí)候,返回true,否則返回false。

      當(dāng)前面的CanSet是一個(gè)指針的時(shí)候(p)它是不可尋址的,但是當(dāng)是p.Elem()(實(shí)際上就是*p),它就是可以尋址的

      package main
      
      import (
      	"fmt"
      	"reflect"
      )
      
      type MyStruct struct {
      	name string
      }
      
      func (this *MyStruct) GetName() string {
      	return this.name
      }
      
      func main() {
      	var a MyStruct
      	a.name = "xiangli"
      	fmt.Println(reflect.ValueOf(a).FieldByName("name").CanSet()) //false
      	fmt.Println(reflect.ValueOf(&(a.name)).Elem().CanSet())      //true
      
      	fmt.Println("--------------")
      	var c string = "yejianfeng"
      	p := reflect.ValueOf(&c)
      	fmt.Println(p.CanSet())        //false
      	fmt.Println(p.Elem().CanSet()) //true
      	p.Elem().SetString("newName")
      	fmt.Println(c)
      }

       

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多