文章目录
前言
反射是Go语言中的一种高级特性,它可以在程序运行时动态地获取和修改变量的类型和值,从而实现很多有用的功能,本博客首先介绍接口类型,为介绍反射打基础,然后从反射的三大法则、底层原理和性能三个方面来介绍Go语言的反射
一、接口类型
空接口底层是由runtime.eface结构体实现,而非空接口底层是由runtime.iface结构体实现。
1、空接口
空接口eface:_type 指向具体数据类型信息的指针 data 指向具体数据的指针。
type eface struct {
_type *_type
data unsafe.Pointer
}
_type可以认为是Go语言中所有类型的公共描述,Go语言中几乎所有的数据结构都可以抽象成_type,是所有类型的表现,可以说是万能类型。
对于将不同类型转化成type万能结构的方法,是运行时的convT2E方法,在runtime包中。
2、_type类型
_type是Go类型的运行时表示。它包含了很多类型的元信息,例如:类型的大小、哈希、对齐以及种类等。
type _type struct {
size uintptr
ptrdata uintptr // size of memory prefix holding all pointers
hash uint32
tflag tflag
align uint8
fieldAlign uint8
kind uint8
// function for comparing objects of this type
// (ptr to object A, ptr to object B) -> ==?
equal func(unsafe.Pointer, unsafe.Pointer) bool
// gcdata stores the GC type data for the garbage collector.
// If the KindGCProg bit is set in kind, gcdata is a GC program.
// Otherwise it is a ptrmask bitmap. See mbitmap.go for det