golang反射

1、基本介绍

  1. 反射能够在运行时动态获取变量的各类信息,好比变量的类型(type),类别(kind)
  2. 若是是结构体变量,还能够获取到结构体自己的信息(包括结构体的字段、方法)
  3. 经过反射,能够修改变量的值,能够调用关联的方法
  4. 使用反射,须要import("reflect")

2、反射重要的函数和概念

  1. reflect.TypeOf(变量名),获取变量的类型,返回reflect.Type类型
  2. reflect.ValueOf(变量名),获取变量的值,返回reflect.Value类型reflect.Value 是一个结构体类型,经过reflect.Value,能够获取到关于该变量的不少信息。
  3. 变量、interface{}和reflect.Value是能够相互转换的,这在实际开发中,常常用到
var student Student
var number int
//专门作反射
func test(b interface{}) {
    // 1.如何将interface{} 转成reflect.Value
    rval = reflect.ValueOf(b)
    // 2.如何将reflect.ValueOf转为interface{}
    iVal := rVal.Interface{}
    // 3.如何将interface{}转成原来的变量类型,使用类型断言便可
    v := iVal.(Student)
}

3、常量

  • 常量使用const修饰
  • 常量在定义的时候,必须初始化
  • 常量不能修改
  • 常量只能修饰bool、数值类型(int、float系列)、string类型
  • 语法:const identifier [type] = value

4、反射注意事项和细节说明

  1. reflect.Value.Kind,获取变量的类别,返回的是一个常量
  2. Type是类型,Kind是类别,Type和Kind可能相同也可能不一样好比:var number int 的Type和Kind都是int,好比:var stu Student stu的Type是包名.Student,Kind是struct
  3. 经过反射可让变量在interface{}和Reflect.Value之间相互转换,变量<---->interface{}<---->reflect.Value
  4. 使用反射的方式获取变量的值(并返回相应的类型),要求数据类型匹配,好比x是int,那么就应该使用reflect.Value(x).Int(),而不能使用其余
  5. 经过反射来修改变量,注意当使用Setxxx方法来设置须要经过对应的指针类型来完成,同事须要使用到reflect.Value.Elem()方法
相关文章
相关标签/搜索