阅读Go源码时,发现很多库都离不开reflect包提供的强大的反射技术,但在基础学习时对这部分一闪而过,现在重新全面学习了一遍,主要使用方法都总结在下面的代码中,自以为应该是比较详细的,后期学习过程中如发现疏漏,再做补充。
可以看到reflect包让我们获得了对于一个空接口中包含的值充分了解的能力,让我们的程序能够在运行时检查类型和变量,解析出一个未知类型背后的结构,对于以指针传递的结构,还可以得到修改字段和动态调用函数的权利,net/rpc就大量使用了reflect技术来进行服务的存储和动态调用。
不再多说,代码如下:
package main
import (
"fmt"
"reflect"
"time"
)
type OutType struct { // tags
field1 bool "This is field1's tag"
Field2 string "This is field2's tag"
Field3 int "This is field3's tag"
field4 *InType "This is field4's tag"
}
type InType struct {
a int "this is tag of a"
b int "this is tag of b"
}
func (o OutType)Function1(){
fmt.Println("this is function1,it's unexported.")
}
func (o OutType)Function2(arg1 string,arg2 *int)(res1 int,res *string){
fmt.Println("this is function2,it's exported.")
return 0,nil
}
func (o *OutType)Function3(a,b int)(InType){
fmt.Println("this is function2,it's exported.")
return InType{a,b}
}
func main() {
var obj interface{}=OutType{true,"hello",1,&InType{1,2}}
var objPtr interface{}=&OutType{true,"hello",1,&InType{1,2}}
/
//1、Type类型:包含了一个结构的类型信息(各数据成员和方法信息),不包含实际值,接口中包含了大量类型信息读取方法
fmt.Println(reflect.TypeOf(obj)) //main.OutType
fmt.Println(reflect.TypeOf(objPtr)) //*main.OutType
objType:=reflect.TypeOf(obj)
fmt.Println(objType.Size()) //40
fmt.Println(objType.Kind()) //struct kind()总显示底层类型
fmt.Println(objType.Name()) //OutType
//用指针初始化Type实例
objPtrType:=reflect.TypeOf(objPtr)
fmt.Println(objPtrType.Size()) //8
fmt.Println(objPtrType.K