golang 反射机制

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}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • golang反射机制介绍 Go语言提供了一种机制,在编译时不知道类型的情况下,可更新变量、在运行时查看值、调用方法...
    发仔很忙阅读 6,669评论 0 0
  • Notes Section 2, Program Structure nested block in if-els...
    keysaim阅读 4,865评论 0 1
  • 01.{ 换行: Opening Brace Can't Be Placed on a Separate Lin...
    码农不器阅读 6,988评论 0 14
  • 第一次知道反射的时候还是许多年前在学校里玩 C# 的时候。那时总是弄不清楚这个复杂的玩意能有什么实际用途……然后发...
    勿以浮沙筑高台阅读 4,783评论 0 9
  • fmt格式化字符串 格式:%[旗标][宽度][.精度][arg索引]动词旗标有以下几种:+: 对于数值类型总是输出...
    皮皮v阅读 4,776评论 0 3