golang 反射機制

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go語言也有反射機制,今天自學到go的反射,發現還是很值得記錄一些這個知識點的。go語言它是通過 reflect 包的兩個介面方法完成的,分別是:

reflect.TypeOf(i interface{}) 和 reflect.ValueOf(i interface{}) ,這時候我們發現 參數是空的介面,也就是說可以接收任何參數,因為所有變數都是預設實現了interface{},這有點類似java所有的類的父類都是Object。在擷取當前參數某一類型時候分為type 和 value。type就是在靜態聲明時候的類型,value就是在代碼付的值。go 反射很強大,每個type或者value下面還有個kind,這個kind表示的是運行時當前參數或者對象狀態的底層真正的資料類型。舉個例子:type X int var count X reflect.TypeOf(count) 得到的就是 main.X 。 reflect.TypeOf(count).kind 得到的就是int。reflect.ValueOf(count) 得到的是 0。 reflect.ValueOf(count).kind 得到的就是 int。 kind函數就是表示type 或者 value 底層運行時具體的資料類型是什麼!!!下面是我做練習的例子:

package main

import (

"reflect"

"fmt"

)

type People struct {

name string

age int

height int

}

type Student struct {

people People

}

var people People = People{"Julian", 26, 175}

var mStudent Student = Student{people}

type LoadingView interface {

loadSucceed()

loadFailure()

}

func (people People) loadSucceed() {

}

func (people People) loadFailure() {

}

func testLoad(load LoadingView) {

loadType := reflect.TypeOf(load)

fmt.Print("load的type是:--", loadType)

fmt.Print("\n")

loadTypeKind := loadType.Kind()

fmt.Print("loadType的Kind是:--", loadTypeKind)

fmt.Print("\n")

loadValue := reflect.ValueOf(load)

fmt.Print("load的value是:--", loadValue)

fmt.Print("\n")

loadValueKind := loadValue.Kind()

fmt.Print("load的value的Kind是:--", loadValueKind)

fmt.Print("\n")

switch value := load.(type) {

case People:

fmt.Print(value)

}

}

func main() {

peopleType := reflect.TypeOf(mStudent)

fmt.Print("people的type是:--", peopleType)

fmt.Print("\n")

peopleTypeKind := peopleType.Kind()

fmt.Print("peopleType的Kind是:--", peopleTypeKind)

fmt.Print("\n")

peopleValue := reflect.ValueOf(mStudent)

fmt.Print("people的value是:--", peopleValue)

fmt.Print("\n")

peopleValueKind := peopleValue.Kind()

fmt.Print("people的value的Kind是:--", peopleValueKind)

fmt.Print("\n")

testLoad(people)

}

下面是列印結果:

people的type是:--main.People

peopleType的Kind是:--struct

people的value是:--{Julian 26 175}

people的value的Kind是:--struct

load的type是:--main.People

loadType的Kind是:--struct

load的value是:--{Julian 26 175}

load的value的Kind是:--struct

{Julian 26 175}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.