承德网站建设规划,苏州大写的网站建设,南京 郑州网站建设公司 网络服务,石河建设技校网站这个是为了接上之前的语法篇的。按照我的学习计划#xff0c;这里此时应该有一个小项目来做一个统合。但是吧#xff0c;突然觉得#xff0c;似乎也没必要。能学go的大部分肯定都是有其他语言的基础的。
接下来说反射 文章目录 反射介绍reflect包TypeOftype name和type kin…这个是为了接上之前的语法篇的。按照我的学习计划这里此时应该有一个小项目来做一个统合。但是吧突然觉得似乎也没必要。能学go的大部分肯定都是有其他语言的基础的。
接下来说反射 文章目录 反射介绍reflect包TypeOftype name和type kindtype kindtype name ValueOf通过反射设置变量的值isNil()和isValid() 结构体反射StructField类型例子双刃剑 反射介绍
变量机制
Go语言中的变量是分为两部分的:
类型信息预先定义好的元信息。值信息程序运行过程中可动态变化的。
程序运行
反射是指在程序运行期间对程序本身进行访问和修改的能力。
程序在编译时变量被转换为内存地址变量名不会被编译器写入到可执行部分。
在运行程序时程序无法获取自身的信息。
解决这个问题
支持反射的语言可以在程序编译期间将变量的反射信息如字段名称、类型信息、结构体信息等整合到可执行文件中并给程序提供接口访问反射信息这样就可以在程序运行期间获取类型的反射信息并且有能力修改它们。
Go程序在运行期间使用reflect包访问程序的反射信息. reflect包
空接口可以存储任意类型的变量那我们如何知道这个空接口保存的数据是什么呢
反射就是在运行时动态的获取一个变量的类型信息和值信息。
在接口那一章说任何接口值都由是一个具体类型和具体类型的值两部分组成的。而这个接口值是在Go语言的反射机制中。
在Go语言中反射的相关功能由内置的reflect包提供任意接口值在反射中都可以理解为由reflect.Type和reflect.Value两部分组成并且reflect包提供了reflect.TypeOf和reflect.ValueOf两个函数来获取任意对象的Value和Type。
TypeOf
在Go语言中使用reflect.TypeOf()函数可以获得任意值的类型对象reflect.Type程序通过类型对象可以访问任意值的类型信息
import (fmtreflect
)func reflectType(x interface{}) {v : reflect.TypeOf(x)fmt.Printf(type:%v\n, v)
}
func main() {var a float32 3.14reflectType(a) // type:float32var b int64 100reflectType(b) // type:int64
}type name和type kind
type kind
在反射中关于类型还划分为两种类型Type 和 种类Kind
在Go语言中可以使用type关键字构造很多自定义类型而种类Kind就是指底层的类型但在反射中当需要区分指针、结构体等大品种的类型时就会用到种类Kind
type myInt int64func reflectType(x interface{}) {t : reflect.TypeOf(x)fmt.Printf(type:%v kind:%v\n, t.Name(), t.Kind())
}func main() {var a *float32 // 指针var b myInt // 自定义类型var c rune // 类型别名reflectType(a) // type: kind:ptrreflectType(b) // type:myInt kind:int64reflectType(c) // type:int32 kind:int32type person struct {name stringage int}type book struct{ title string }var d person{name: 小王子,age: 18,}var e book{title: 天气正好}reflectType(d) // type:person kind:structreflectType(e) // type:book kind:struct
}简单而言就是我们需要函数名的时候用type需要定义的指针还是结构体就用kind
type name
Go语言的反射中像数组、切片、Map、指针等类型的变量它们的.Name()都是返回空。
ValueOf
reflect.ValueOf()返回的是reflect.Value类型其中包含了原始值的值信息。reflect.Value与原始值之间可以互相转换。
reflect.Value类型提供的获取原始值的方法:
func reflectValue(x interface{}) {v : reflect.ValueOf(x)k : v.Kind()switch k {case reflect.Int64:// v.Int()从反射中获取整型的原始值然后通过int64()强制类型转换fmt.Printf(type is int64, value is %d\n, int64(v.Int()))case reflect.Float32:// v.Float()从反射中获取浮点型的原始值然后通过float32()强制类型转换fmt.Printf(type is float32, value is %f\n, float32(v.Float()))case reflect.Float64:// v.Float()从反射中获取浮点型的原始值然后通过float64()强制类型转换fmt.Printf(type is float64, value is %f\n, float64(v.Float()))}
}
func main() {var a float32 3.14var b int64 100reflectValue(a) // type is float32, value is 3.140000reflectValue(b) // type is int64, value is 100// 将int类型的原始值转换为reflect.Value类型c : reflect.ValueOf(10)fmt.Printf(type c :%T\n, c) // type c :reflect.Value
}通过反射设置变量的值
在函数中通过反射修改变量的值需要注意函数参数传递的是值拷贝必须传递变量地址才能修改变量值。而反射中使用专有的Elem()方法来获取指针对应的值。
package mainimport (fmtreflect
)func reflectSetValue1(x interface{}) {v : reflect.ValueOf(x)if v.Kind() reflect.Int64 {v.SetInt(200) //修改的是副本reflect包会引发panic}
}
func reflectSetValue2(x interface{}) {v : reflect.ValueOf(x)// 反射中使用 Elem()方法获取指针对应的值if v.Elem().Kind() reflect.Int64 {v.Elem().SetInt(200)}
}
func main() {var a int64 100// reflectSetValue1(a) //panic: reflect: reflect.Value.SetInt using unaddressable valuereflectSetValue2(a)fmt.Println(a)
}isNil()和isValid()
isNil() func (v Value) IsNil() bool 注意IsNil()报告v持有的值是否为nil。v持有的值的分类必须是通道、函数、接口、映射、指针、切片之一否则IsNil函数会导致panic。
isValid() func (v Value) IsValid() bool 注意IsValid()返回v是否持有一个值。如果v是Value零值会返回假此时v除了IsValid、String、Kind之外的方法都会导致panic。
IsNil()常被用于判断指针是否为空IsValid()常被用于判定返回值是否有效。
结构体反射
任意值通过reflect.TypeOf()获得反射对象信息后如果它的类型是结构体可以通过反射值对象reflect.Type的NumField()和Field()方法获得结构体成员的详细信息
reflect.Type中与获取结构体成员相关的的方法。
StructField类型
StructField类型用来描述结构体中的一个字段的信息
type StructField struct {// Name是字段的名字。PkgPath是非导出字段的包路径对导出字段该字段为。// Name stringPkgPath stringType Type // 字段的类型Tag StructTag // 字段的标签Offset uintptr // 字段在结构体中的字节偏移量Index []int // 用于Type.FieldByIndex时的索引切片Anonymous bool // 是否匿名字段
}参见http://golang.org/ref/spec#Uniqueness_of_identifiers
例子
当我们使用反射得到一个结构体数据之后可以通过索引依次获取其字段信息也可以通过字段名去获取指定的字段信息。
type student struct {Name string json:nameScore int json:score
}func main() {stu1 : student{Name: 小王子,Score: 90,}t : reflect.TypeOf(stu1)fmt.Println(t.Name(), t.Kind()) // student struct// 通过for循环遍历结构体的所有字段信息for i : 0; i t.NumField(); i {field : t.Field(i)fmt.Printf(name:%s index:%d type:%v json tag:%v\n, field.Name, field.Index, field.Type, field.Tag.Get(json))}// 通过字段名获取指定结构体字段信息if scoreField, ok : t.FieldByName(Score); ok {fmt.Printf(name:%s index:%d type:%v json tag:%v\n, scoreField.Name, scoreField.Index, scoreField.Type, scoreField.Tag.Get(json))}
}编写一个函数printMethod(s interface{})来遍历打印s包含的方法
/ 给student添加两个方法 Study和Sleep(注意首字母大写)
func (s student) Study() string {msg : 好好学习天天向上。fmt.Println(msg)return msg
}func (s student) Sleep() string {msg : 好好睡觉快快长大。fmt.Println(msg)return msg
}func printMethod(x interface{}) {t : reflect.TypeOf(x)v : reflect.ValueOf(x)fmt.Println(t.NumMethod())for i : 0; i v.NumMethod(); i {methodType : v.Method(i).Type()fmt.Printf(method name:%s\n, t.Method(i).Name)fmt.Printf(method:%s\n, methodType)// 通过反射调用方法传递的参数必须是 []reflect.Value 类型var args []reflect.Value{}v.Method(i).Call(args)}
}双刃剑
反射是一个强大并富有表现力的工具能让我们写出更灵活的代码。但是反射不应该被滥用原因有以下三个。
基于反射的代码是极其脆弱的反射中的类型错误会在真正运行的时候才会引发panic那很可能是在代码写完的很长时间之后。大量使用反射的代码通常难以理解。反射的性能低下基于反射实现的代码通常比正常代码运行速度慢一到两个数量级。 文章转载自: http://www.morning.wzyfk.cn.gov.cn.wzyfk.cn http://www.morning.mfsxd.cn.gov.cn.mfsxd.cn http://www.morning.nwpnj.cn.gov.cn.nwpnj.cn http://www.morning.hsrpr.cn.gov.cn.hsrpr.cn http://www.morning.znqztgc.cn.gov.cn.znqztgc.cn http://www.morning.btsls.cn.gov.cn.btsls.cn http://www.morning.rdkt.cn.gov.cn.rdkt.cn http://www.morning.rmqlf.cn.gov.cn.rmqlf.cn http://www.morning.btlmb.cn.gov.cn.btlmb.cn http://www.morning.rkypb.cn.gov.cn.rkypb.cn http://www.morning.mpyry.cn.gov.cn.mpyry.cn http://www.morning.rywr.cn.gov.cn.rywr.cn http://www.morning.yhjrc.cn.gov.cn.yhjrc.cn http://www.morning.rfxg.cn.gov.cn.rfxg.cn http://www.morning.hqzmz.cn.gov.cn.hqzmz.cn http://www.morning.pumali.com.gov.cn.pumali.com http://www.morning.wjlhp.cn.gov.cn.wjlhp.cn http://www.morning.hjssh.cn.gov.cn.hjssh.cn http://www.morning.yqpzl.cn.gov.cn.yqpzl.cn http://www.morning.hwbf.cn.gov.cn.hwbf.cn http://www.morning.yppln.cn.gov.cn.yppln.cn http://www.morning.nqlx.cn.gov.cn.nqlx.cn http://www.morning.krdb.cn.gov.cn.krdb.cn http://www.morning.xqbgm.cn.gov.cn.xqbgm.cn http://www.morning.gfpyy.cn.gov.cn.gfpyy.cn http://www.morning.vvdifactory.com.gov.cn.vvdifactory.com http://www.morning.knrgb.cn.gov.cn.knrgb.cn http://www.morning.bplqh.cn.gov.cn.bplqh.cn http://www.morning.cypln.cn.gov.cn.cypln.cn http://www.morning.cqwb25.cn.gov.cn.cqwb25.cn http://www.morning.hncrc.cn.gov.cn.hncrc.cn http://www.morning.nswcw.cn.gov.cn.nswcw.cn http://www.morning.wxccm.cn.gov.cn.wxccm.cn http://www.morning.sgrdp.cn.gov.cn.sgrdp.cn http://www.morning.qcztm.cn.gov.cn.qcztm.cn http://www.morning.ckhpg.cn.gov.cn.ckhpg.cn http://www.morning.fmqw.cn.gov.cn.fmqw.cn http://www.morning.lmcrc.cn.gov.cn.lmcrc.cn http://www.morning.crqbt.cn.gov.cn.crqbt.cn http://www.morning.trffl.cn.gov.cn.trffl.cn http://www.morning.rqlzz.cn.gov.cn.rqlzz.cn http://www.morning.nqpy.cn.gov.cn.nqpy.cn http://www.morning.tsynj.cn.gov.cn.tsynj.cn http://www.morning.kcwkt.cn.gov.cn.kcwkt.cn http://www.morning.qsctt.cn.gov.cn.qsctt.cn http://www.morning.dmwbs.cn.gov.cn.dmwbs.cn http://www.morning.bkcnq.cn.gov.cn.bkcnq.cn http://www.morning.jmllh.cn.gov.cn.jmllh.cn http://www.morning.51meihou.cn.gov.cn.51meihou.cn http://www.morning.mhybs.cn.gov.cn.mhybs.cn http://www.morning.rnfn.cn.gov.cn.rnfn.cn http://www.morning.ylqb8.cn.gov.cn.ylqb8.cn http://www.morning.gdpai.com.cn.gov.cn.gdpai.com.cn http://www.morning.qnbgk.cn.gov.cn.qnbgk.cn http://www.morning.nlmm.cn.gov.cn.nlmm.cn http://www.morning.jxpwr.cn.gov.cn.jxpwr.cn http://www.morning.crdtx.cn.gov.cn.crdtx.cn http://www.morning.hxwrs.cn.gov.cn.hxwrs.cn http://www.morning.c7627.cn.gov.cn.c7627.cn http://www.morning.pwzzk.cn.gov.cn.pwzzk.cn http://www.morning.qcdtzk.cn.gov.cn.qcdtzk.cn http://www.morning.qczjc.cn.gov.cn.qczjc.cn http://www.morning.jqmqf.cn.gov.cn.jqmqf.cn http://www.morning.jtmrx.cn.gov.cn.jtmrx.cn http://www.morning.ygztf.cn.gov.cn.ygztf.cn http://www.morning.ccjhr.cn.gov.cn.ccjhr.cn http://www.morning.hxfrd.cn.gov.cn.hxfrd.cn http://www.morning.gchqy.cn.gov.cn.gchqy.cn http://www.morning.wkmyt.cn.gov.cn.wkmyt.cn http://www.morning.yhplt.cn.gov.cn.yhplt.cn http://www.morning.slfkt.cn.gov.cn.slfkt.cn http://www.morning.bfgpn.cn.gov.cn.bfgpn.cn http://www.morning.ydtdn.cn.gov.cn.ydtdn.cn http://www.morning.mqwnp.cn.gov.cn.mqwnp.cn http://www.morning.slwfy.cn.gov.cn.slwfy.cn http://www.morning.trffl.cn.gov.cn.trffl.cn http://www.morning.xxzjb.cn.gov.cn.xxzjb.cn http://www.morning.kndst.cn.gov.cn.kndst.cn http://www.morning.dwmmf.cn.gov.cn.dwmmf.cn http://www.morning.cwkcq.cn.gov.cn.cwkcq.cn