乔克视界 乔克视界
首页
  • 运维
  • 开发
  • 监控
  • 安全
  • 随笔
  • Docker
  • Golang
  • Python
  • AIOps
  • 心情杂货
  • 读书笔记
  • 面试
  • 实用技巧
  • 博客搭建
友链
关于
收藏
  • 分类
  • 标签
  • 归档

乔克

云原生爱好者
首页
  • 运维
  • 开发
  • 监控
  • 安全
  • 随笔
  • Docker
  • Golang
  • Python
  • AIOps
  • 心情杂货
  • 读书笔记
  • 面试
  • 实用技巧
  • 博客搭建
友链
关于
收藏
  • 分类
  • 标签
  • 归档
  • Docker

  • Golang

    • Golang基础知识

      • 开发环境搭建
      • 常量与变量
      • 基本数据类型
      • 复合数据类型
      • 流程控制
      • 运算符
      • 位运算符详解
      • 指针
      • map
      • 函数
      • defer
      • 类型别名与自定义类型
      • 结构体
      • 接口
      • 包
      • 文件操作
      • 反射
        • reflect 包
          • Typeof
          • type kind 和 type name
          • Valueof
          • 通过反射获取值
          • 通过反射设置值
          • isNil()和 isValid()
          • isNil()
          • isValid()
        • 结构体反射
          • 与结构体相关的方法
          • StructField 类型
          • 结构体反射示例
          • call 方法
      • 并发
      • socket网络编程
      • HTTP网络编程
      • 单元测试
      • 基准测试
      • 并发测试
      • 示例函数
      • 性能优化
      • go module
      • 在Go中使用Makefile
      • 部署Go项目
    • Golang进阶知识

    • Golang常用包

  • AIOps

  • 专栏
  • Golang
  • Golang基础知识
乔克
2025-07-13
目录

反射

反射是指在程序运行期对程序本身进行访问和修改的能力。程序在编译时,变量被转换为内存地址,变量名不会被编译器写入到可执行部分。在运行程序时,程序无法获取自身的信息。

支持反射的语言可以在程序编译期将变量的反射信息,如字段名称、类型信息、结构体信息等整合到可执行文件中,并给程序提供接口访问反射信息,这样就可以在程序运行期获取类型的反射信息,并且有能力修改它们。

Go 程序在运行期使用 reflect 包访问程序的反射信息。

# reflect 包

在 Go 语言的反射机制中,任何接口值都由是一个具体类型和具体类型的值两部分组成的。 在 Go 语言中反射的相关功能由内置的 reflect 包提供,任意接口值在反射中都可以理解为由reflect.Type和reflect.Value两部分组成,并且 reflect 包提供了reflect.TypeOf和reflect.ValueOf两个函数来获取任意对象的 Value 和 Type。

# Typeof

在 Go 语言中,使用reflect.TypeOf()函数可以获得任意值的类型对象(reflect.Type),程序通过类型对象可以访问任意值的类型信息。

package main

import (
	"fmt"
	"reflect"
)

func reflectType(x interface{}) {
	v := reflect.TypeOf(x)
	fmt.Printf("%T,%v\n", v, v)
}

func main() {
	a := 10
	reflectType(a) //*reflect.rtype,int
	b := float64(1.234)
	reflectType(b) //*reflect.rtype,float64
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# type kind 和 type name

在反射中关于类型还划分为两种:类型(Type)和种类(Kind)。因为在 Go 语言中我们可以使用 type 关键字构造很多自定义类型,而种类(Kind)就是指底层的类型,但在反射中,当需要区分指针、结构体等大品种的类型时,就会用到种类(Kind)。 举个例子,我们定义了两个指针类型和两个结构体类型,通过反射查看它们的类型和种类。

package main

import (
	"fmt"
	"reflect"
)

type cat struct {
	name string
}

type dog struct {
	name string
}

func reflectType(x interface{}) {
	v := reflect.TypeOf(x)
	fmt.Printf("类型名:%s,类型的种类:%s\n", v.Name(), v.Kind())
}

func main() {
	c := cat{
		name: "咖啡",
	}
	reflectType(c) // *类型名:cat,类型的种类:struct
	d := dog{
		name: "大黄",
	}
	reflectType(d) // 类型名:dog,类型的种类:struct
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Go 语言的反射中像数组、切片、Map、指针等类型的变量,它们的.Name()都是返回空。

在reflect包中定义的 Kind 类型如下:

type Kind uint
const (
    Invalid Kind = iota  // 非法类型
    Bool                 // 布尔型
    Int                  // 有符号整型
    Int8                 // 有符号8位整型
    Int16                // 有符号16位整型
    Int32                // 有符号32位整型
    Int64                // 有符号64位整型
    Uint                 // 无符号整型
    Uint8                // 无符号8位整型
    Uint16               // 无符号16位整型
    Uint32               // 无符号32位整型
    Uint64               // 无符号64位整型
    Uintptr              // 指针
    Float32              // 单精度浮点数
    Float64              // 双精度浮点数
    Complex64            // 64位复数类型
    Complex128           // 128位复数类型
    Array                // 数组
    Chan                 // 通道
    Func                 // 函数
    Interface            // 接口
    Map                  // 映射
    Ptr                  // 指针
    Slice                // 切片
    String               // 字符串
    Struct               // 结构体
    UnsafePointer        // 底层指针
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

# Valueof

reflect.ValueOf()返回的是reflect.Value类型,其中包含了原始值的值信息。reflect.Value与原始值之间可以互相转换。

reflect.Value类型提供的获取原始值的方法如下:

方法 说明
Interface() interface {} 将值以 interface{} 类型返回,可以通过类型断言转换为指定类型
Int() int64 将值以 int 类型返回,所有有符号整型均可以此方式返回
Uint() uint64 将值以 uint 类型返回,所有无符号整型均可以此方式返回
Float() float64 将值以双精度(float64)类型返回,所有浮点数(float32、float64)均可以此方式返回
Bool() bool 将值以 bool 类型返回
Bytes() []bytes 将值以字节数组 []bytes 类型返回
String() string 将值以字符串类型返回

# 通过反射获取值

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.14
	var b int64 = 100
	reflectValue(a) // type is float32, value is 3.140000
	reflectValue(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
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 通过反射设置值

想要在函数中通过反射修改变量的值,需要注意函数参数传递的是值拷贝,必须传递变量地址才能修改变量值。而反射中使用专有的Elem()方法来获取指针对应的值。

package main

import (
	"fmt"
	"reflect"
)

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 value
	reflectSetValue2(&a)
	fmt.Println(a)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# isNil()和 isValid()

# isNil()

func (v Value) IsNil() bool
1

IsNil()报告 v 持有的值是否为 nil。v 持有的值的分类必须是通道、函数、接口、映射、指针、切片之一;否则 IsNil 函数会导致 panic。

# isValid()

func (v Value) IsValid() bool
1

IsValid()返回 v 是否持有一个值。如果 v 是 Value 零值会返回假,此时 v 除了 IsValid、String、Kind 之外的方法都会导致 panic。

例子:

IsNil()常被用于判断指针是否为空;IsValid()常被用于判定返回值是否有效。

func main() {
	// *int类型空指针
	var a *int
	fmt.Println("var a *int IsNil:", reflect.ValueOf(a).IsNil())
	// nil值
	fmt.Println("nil IsValid:", reflect.ValueOf(nil).IsValid())
	// 实例化一个匿名结构体
	b := struct{}{}
	// 尝试从结构体中查找"abc"字段
	fmt.Println("不存在的结构体成员:", reflect.ValueOf(b).FieldByName("abc").IsValid())
	// 尝试从结构体中查找"abc"方法
	fmt.Println("不存在的结构体方法:", reflect.ValueOf(b).MethodByName("abc").IsValid())
	// map
	c := map[string]int{}
	// 尝试从map中查找一个不存在的键
	fmt.Println("map中不存在的键:", reflect.ValueOf(c).MapIndex(reflect.ValueOf("嘿嘿")).IsValid())
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 结构体反射

# 与结构体相关的方法

任意值通过reflect.TypeOf()获得反射对象信息后,如果它的类型是结构体,可以通过反射值对象(reflect.Type)的NumField()和Field()方法获得结构体成员的详细信息。

reflect.Type中与获取结构体成员相关的的方法如下表所示。

方法 说明
Field(i int) StructField 根据索引,返回索引对应的结构体字段的信息。
NumField() int 返回结构体成员字段数量。
FieldByName(name string) (StructField, bool) 根据给定字符串返回字符串对应的结构体字段的信息。
FieldByIndex(index []int) StructField 多层成员访问时,根据 []int 提供的每个结构体的字段索引,返回字段的信息。
FieldByNameFunc(match func(string) bool) (StructField,bool) 根据传入的匹配函数匹配需要的字段。
NumMethod() int 返回该类型的方法集中方法的数目
Method(int) Method 返回该类型方法集中的第 i 个方法
MethodByName(string)(Method, bool) 根据方法名返回该类型方法集中的方法

# StructField 类型

StructField类型用来描述结构体中的一个字段的信息。

StructField的定义如下:

type StructField struct {
    // Name是字段的名字。PkgPath是非导出字段的包路径,对导出字段该字段为""。
    // 参见http://golang.org/ref/spec#Uniqueness_of_identifiers
    Name    string
    PkgPath string
    Type      Type      // 字段的类型
    Tag       StructTag // 字段的标签
    Offset    uintptr   // 字段在结构体中的字节偏移量
    Index     []int     // 用于Type.FieldByIndex时的索引切片
    Anonymous bool      // 是否匿名字段
}
1
2
3
4
5
6
7
8
9
10
11

# 结构体反射示例

当我们使用反射得到一个结构体数据之后可以通过索引依次获取其字段信息,也可以通过字段名去获取指定的字段信息。

type student struct {
	Name  string `json:"name"`
	Score 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"))
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

接下来编写一个函数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)
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# call 方法

结构体中的方法的排序是按照 ASCII 码来进行排序的。

调用 call 方法首先得获取到结构体得方法,获取结构体得方法通过tValue.Method(Num)

其中:

  • tValue 是一个type.Value类型得变量
  • Method 是调用得方法名
  • Num 是结构体得方法排序后的索引值

例子:

package main

import (
	"fmt"
	"reflect"
)

// Person 定义一个struct
type Person struct {
	Name    string
	Age     int
	Address string
}

// Set 给Person定义Set方法
func (p *Person) Set(name, address string, age int) {
	p.Name = name
	p.Age = age
	p.Address = address
}

// Get 给Person定义Get方法
func (p *Person) Get() {
	fmt.Println(p)
}

// Sum ...
func (p *Person) Sum(a, b int) {
	fmt.Println(a + b)
}

// 定义一个函数来通过放射操作结构体
func reflectTest(r interface{}) {
	// 通过反射获取type.Type
	// tType:=reflect.TypeOf(r)
	// 通过反射获取type.Value
	tValue := reflect.ValueOf(r)
	// fmt.Println(tValue.Elem().Kind())
	// 判断tValue的类型是否是reflect.Struct
	if tValue.Elem().Kind() != reflect.Struct {
		fmt.Println("the type of r must be struct")
		return
	}
	// 获取结构体总共有几个方法
	fNum := tValue.NumMethod()
	fmt.Println(fNum)
	// 调用方法
	tValue.Method(0).Call(nil)
}

func main() {
	// 实例化结构体
	p1 := &Person{
		Name:    "Tom",
		Age:     30,
		Address: "Chongqing",
	}
	reflectTest(p1)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

最后输出的结果为:

&{Tom 30 Chongqing}
1

我们上面定义的方法的顺序是Set()、Get()、Sum()。但是我们通过反射获取第0方法是Get()。就像我们上面说的,获取的方法是通过 ASSII 码排序后的方法。上面三个方法通过 ASSII 码排序后为 Get()、Set()、Sum()。

如果方法是有参数的,传递的参数必须是[]reflect.Value类型。

如下:

	// 定义切片类型的value作为参数
	var param []reflect.Value
	param = append(param, reflect.ValueOf(10))
	param = append(param, reflect.ValueOf(20))
	tValue.Method(2).Call(param)
1
2
3
4
5
上次更新: 2025/07/18, 11:04:43
文件操作
并发

← 文件操作 并发→

最近更新
01
2025年,SRE在企业中可以做哪些事
07-18
02
SRE 如何提升自己在团队中的影响力
07-18
03
使用Go开发MCP服务
07-18
更多文章>
Theme by Vdoing | Copyright © 2019-2025 乔克 | MIT License | 渝ICP备20002153号 |
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式