Go语言学习笔记 - PART10 - 反射

161 阅读1分钟

反射可以在运行时检测变量的类型和值

反射常用方法

  • reflect.TypeOf() 返回被检查对象的类型
  • reflect.ValueOf() 返回被检查对象的值

Kind()函数返回类型

  • loat64 类型的变量 x,如果 v:=reflect.ValueOf(x),那么 v.Kind() 返回 reflect.Float64
  • Kind总是返回底层类型
    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
    	Ptr
    	Slice
    	String
    	Struct
    	UnsafePointer
    )

通过反射,从对象获取接口值

Interface()可以获得接口值

func main() {
	var x float64 = 3.4
	fmt.Println("type:", reflect.TypeOf(x))
	v := reflect.ValueOf(x)
	fmt.Println("value:", v)
	fmt.Println(v.Interface())
	fmt.Printf("value is %5.2e\n", v.Interface())
	y := v.Interface().(float64)
	fmt.Println(y)
}

通过反射修改变量的值

当 v := reflect.ValueOf(x) 函数通过传递一个 x 拷贝创建了 v,那么 v 的改变并不能更改原始的 x

  • 要想 v 的更改能作用到 x,那就必须传递 x 的地址 v = reflect.ValueOf(&x)

入门教程推荐: github.com/Unknwon/the…