Golang反射获得变量类型和值


1. 什么是反射

反射是程序在运行期间获取变量的类型和值、或者执行变量的方法的能力。

Golang反射包中有两对非常重要的函数和类型,两个函数分别是:

reflect.TypeOf 能获取类型信息reflect.Type

reflect.ValueOf 能获取数据的运行时表示reflect.Value

3. reflect.Type

Golang是一门静态类型的语言,反射是建立在类型之上的。

通过reflect.TypeOf() 函数可以获得任意值的类型信息。

3.1 类型Type和种类Kind

诸如int32, slice, map以及通过type关键词自定义的类型。

种类Kind可以理解为类型的具体分类。如int32type MyInt32 int32是两种不同类型,但都属于int32这个种类。

使用 reflect.TypeOf()获取变量类型以及种类。

func main() {
	type MyInt32 int32
	a := MyInt32(1)
	b := int32(1)
	fmt.Printf("reflect.TypeOf(a):%v Kind:%v\n", reflect.TypeOf(a), reflect.TypeOf(a).Kind())
	fmt.Printf("reflect.TypeOf(b):%v Kind:%v\n", reflect.TypeOf(b), reflect.TypeOf(b).Kind())
}

代码输出如下,由此可以看出int32type MyInt32 int32是两种不同类型,但都属于int32这个种类。

$ go run main.go
reflect.TypeOf(a):main.MyInt32 Kind:int32
reflect.TypeOf(b):int32 Kind:int32
种类定义点击查看
// A Kind represents the specific kind of type that a Type represents.
// The zero Kind is not a valid kind.
type Kind uint
const (
	Invalid Kind = iota
	Bool
	Int
	Int8
	Int16
	Int32
	Int64
	Uint
	Uint8
	Uint16
	Uint32
	Uint64
	Uintptr
	Float32
	Float64
	Complex64
	Complex128
	Array
	Chan
	Func
	Interface
	Map
	Pointer
	Slice
	String
	Struct
	UnsafePointer
)

3.2 引用指向元素的类型

// Elem returns a type's element type.
// It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.
Elem() Type

部分情况我们需要获取指针指向元素的类型、或者slice元素的类型,可以reflect.Elem()函数获取。

func main() {
	type myStruct struct {
	}
	a := &myStruct{}
	typeA := reflect.TypeOf(a)
	fmt.Printf("TypeOf(a):%v Kind:%v\n", typeA, typeA.Kind())
	fmt.Printf("TypeOf(a).Elem():%v Elem().Kind:%v\n", typeA.Elem(), typeA.Elem().Kind())
	s := []int64{}
	typeS := reflect.TypeOf(s)
	fmt.Printf("TypeOf(s):%v Kind:%v\n", typeS, typeS.Kind())
	fmt.Printf("TypeOf(s).Elem():%v Elem().Kind:%v\n", typeS.Elem(), typeS.Elem().Kind())
}

代码输出如下,由此可以看出,通过reflect.Elem()函数可以获取引用指向数据的类型。

$ go run main.go
TypeOf(a):*main.myStruct Kind:ptr
TypeOf(a).Elem():main.myStruct Elem().Kind:struct
TypeOf(s):[]int64 Kind:slice
TypeOf(s).Elem():int64 Elem().Kind:int64

laws-of-reflection

interface

Go