反射 Reflect

反射 Reflect #

reflect.ValueOf 函数直接返回的 reflect.Value 值都是不可修改的(reflect.Elem 可以)。

有两种方法获取一个代表着一个指针所引用着的值的 reflect.Value 值:

  1. 通过调用代表着此指针值的 reflect.Value 值的Elem方法。
  2. 将代表着此指针值的 reflect.Value 值的传递给一个 reflect.Indirect 函数调用。 (如果传递给一个 reflect.Indirect 函数调用的实参不代表着一个指针值,则此调用返回此实参的一个复制。)

Reflect package #

func ValueOf(i interface{}) Value

返回一个新的 reflect.Value 对象,内容为 i 中的确定值。ValueOf(nil) 返回 reflect.Value 的零值

func (v Value) Addr() Value

Addr returns a pointer value representing the address of v. It panics if CanAddr() returns false. Addr is typically used to obtain a pointer to a struct field or slice element in order to call a method that requires a pointer receiver.

可以理解成 &p 操作。

func (v Value) Interface() (i interface{})

Interface returns v’s current value as an interface{}.

使用空接口类型来返回 v 当前的值。

func (v Value) Elem() Value

Elem returns the value that the interface v contains or that the pointer v points to. It panics if v’s Kind is not Interface or Ptr. It returns the zero Value if v is nil.

v 是值,则返回值。若 v 是指向值的指针,则返回指针指向的值(就如同 *p)。

func (v Value) Kind() Kind

返回 v 中值的类型。

Kind 表示的是一些特定的 Type(可以认为是 Type 的一个子集)。

func (v Value) Pointer() uintptr

v 的值以 uintptr 类型返回。如果 v 的类型(Kind)不为 Chan, Func, Map, Ptr, Slice, or UnsafePointer,则会抛出 panic。

func (v Value) Set(x Value)

x 赋给 v 的值。若 CanSetfalse ,则抛出 panic。

func (v Value) Type() Type

返回 v 中的 type 结构数据。

References #