[关闭]
@fzbing 2016-08-24T09:18:12.000000Z 字数 35784 阅读 1245

Package reflect

golang


go1.6.3

概览

Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.

反射包实现了运行时反射,允许程序操作任意类型的对象。典型的用法是用静态类型为interface{}的变量保存一个值,并用TypeOf解析它的动态类型信息,该函数返回一个类型为Type的值。

A call to ValueOf returns a Value representing the run-time data. Zero takes a Type and returns a Value representing a zero value for that type.

调用ValueOf函数返回一个类型为Value的值,它代表了一个运行时的数据。Zero函数接受一个类型为Type的值,并返回一个类型为Value的值,它代表了该类型的零值。

See "The Laws of Reflection" for an introduction to reflection in Go: https://golang.org/doc/articles/laws_of_reflection.html

"The Laws of Reflection" 提供了一个关于Go中反射机制的介绍:
https://golang.org/doc/articles/laws_of_reflection.html

索引

func Copy

  1. func Copy(dst, src Value) int

Copy copies the contents of src into dst until either dst has been filled or src has been exhausted. It returns the number of elements copied. Dst and src each must have kind Slice or Array, and dst and src must have the same element type.

Copy 复制src 的内容到dst,直到dst 被填满或者src 已经没有值可复制。它返回复制的元素的数量。dst 和src 的Kind必须是Slice 或者Array,并且dst 和 src 必须有相同的元素类型。

func DeepEqual

  1. func DeepEqual(x, y interface{}) bool

DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.

DeepEqual 报告x和y是否是“深相等的”。两个相同类型的值是深相等的,如果符合下面的一条规则。不同类型的值一定不深相等。

Array values are deeply equal when their corresponding elements are deeply equal.

数组类型的值是深相等的,当他们的元素相应的深相等。

Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.

结构体类型的值是深相等的,当他们相应的字段,包括暴露的和非暴露的,是深相等的。

Func values are deeply equal if both are nil; otherwise they are not deeply equal.

函数类型的值是深相等的,当它们都是nil,否则它们是不深相等的。

Interface values are deeply equal if they hold deeply equal concrete values.

接口类型的值是深相等的,当它们持有深相等的具体的值。

Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.

映射类型的值是深相等的,当它们相同的映射对象或者它们有相同的长度并且它们相应的键(用Go的相等是匹配的)映射为深相等的值。

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.

指针类型的值是深相等的,当它们是相等的,用Go的 == 操作符比较 或者 它们指向深相等的值。

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.

切片类型的值是深相等的,当所有下面都为true时:它们都是nil 或者 非nil但是它们有相同的长度并且或者它们指向相同的相同的底层数组的初始实体(也就是,&x[0] == &y[0]),或者它们相应的元素(知道切片的长度)是深相等的。注意,一个非nil的空切片和一个nil切片(举例,[]byte{} 和 []byte(nil))是不深相等的。

Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.

别的类型的值 - 数值类型,布尔类型,字符串类型和管道类型 - 是深相等的,当它们是相等的,用Go的 == 操作符判断。

In general DeepEqual is a recursive relaxation of Go's == operator. However, this idea is impossible to implement without some inconsistency. Specifically, it is possible for a value to be unequal to itself, either because it is of func type (uncomparable in general) or because it is a floating-point NaN value (not equal to itself in floating-point comparison), or because it is an array, struct, or interface containing such a value. On the other hand, pointer values are always equal to themselves, even if they point at or contain such problematic values, because they compare equal using Go's == operator, and that is a sufficient condition to be deeply equal, regardless of content. DeepEqual has been defined so that the same short-cut applies to slices and maps: if x and y are the same slice or the same map, they are deeply equal regardless of content.

在一般情况下,DeepEqual 是递归的用Go的相等运算符 == 。然而,在存在不一致性的前提下,这个想法是不可能实现的。

func Select

  1. func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)

Select executes a select operation described by the list of cases. Like the Go select statement, it blocks until at least one of the cases can proceed, makes a uniform pseudo-random choice, and then executes that case. It returns the index of the chosen case and, if that case was a receive operation, the value received and a boolean indicating whether the value corresponds to a send on the channel (as opposed to a zero value received because the channel is closed).

Select 执行一个选择操作,描述的被一个case的列表。像Go的select语句一样,它会阻塞直到至少一条case可以被处理,做了一个统一的伪随机选择,然后执行这个case。它返回被选择的case的索引,如果该case是一个接收操作,接收到的值和一个布尔值表明是否该值是相应的发送管道的值(相反的是接受到一个零值,因为该通道被关闭)。

type ChanDir

  1. type ChanDir int

ChanDir represents a channel type's direction.

ChanDir 代表一个管道类型的方向。

  1. const (
  2. RecvDir ChanDir = 1 << iota // <-chan
  3. SendDir // chan<-
  4. BothDir = RecvDir | SendDir // chan
  5. )

func (ChanDir) String

  1. func (d ChanDir) String() string

type Kind

  1. type Kind uint

A Kind represents the specific kind of type that a Type represents. The zero Kind is not a valid kind.

一个Kind类型的值代表Type类型值的具体的类型。零值表示一个无效的Kind。【Kind类型的零值是不合法的】

  1. const (
  2. Invalid Kind = iota
  3. Bool
  4. Int
  5. Int8
  6. Int16
  7. Int32
  8. Int64
  9. Uint
  10. Uint8
  11. Uint16
  12. Uint32
  13. Uint64
  14. Uintptr
  15. Float32
  16. Float64
  17. Complex64
  18. Complex128
  19. Array
  20. Chan
  21. Func
  22. Interface
  23. Map
  24. Ptr
  25. Slice
  26. String
  27. Struct
  28. UnsafePointer
  29. )

func (Kind) String

  1. func (k Kind) String() string

type Method

  1. type Method struct {
  2. // Name is the method name.
  3. // PkgPath is the package path that qualifies a lower case (unexported)
  4. // method name. It is empty for upper case (exported) method names.
  5. // The combination of PkgPath and Name uniquely identifies a method
  6. // in a method set.
  7. // See https://golang.org/ref/spec#Uniqueness_of_identifiers
  8. Name string
  9. PkgPath string
  10. Type Type // method type
  11. Func Value // func with receiver as first argument
  12. Index int // index for Type.Method
  13. }

Method represents a single method.

Method代表一个方法。

type SelectCase

  1. type SelectCase struct {
  2. Dir SelectDir // direction of case
  3. Chan Value // channel to use (for send or receive)
  4. Send Value // value to send (for send)
  5. }

A SelectCase describes a single case in a select operation. The kind of case depends on Dir, the communication direction.

一个SelectCase类型的值描述了一个case,select操作中的。case的种类依赖于Dir,通讯的方向。

If Dir is SelectDefault, the case represents a default case. Chan and Send must be zero Values.

如果Dir是SelectDefault,该case代表默认case。Chan和Send必须是一个零值。

If Dir is SelectSend, the case represents a send operation. Normally Chan's underlying value must be a channel, and Send's underlying value must be assignable to the channel's element type. As a special case, if Chan is a zero Value, then the case is ignored, and the field Send will also be ignored and may be either zero or non-zero.

如果Dir是SelectSend,该case代表一个发送操作。正常的,Chan的底层值必须是一个管道,并且Send的底层值必须是可以赋值给管道的元素类型的值。作为一个特例,如果Chan是一个零值,那么该case被忽略,并且Send字段也会被忽略,无论是不是零值。

If Dir is SelectRecv, the case represents a receive operation. Normally Chan's underlying value must be a channel and Send must be a zero Value. If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value. When a receive operation is selected, the received Value is returned by Select.

如果Dir是SelectRecv,该case代表一个接收操作。正常的,Chan的底层值必须是一个管道,并且Send必须是一个零值。如果Chan是一个零值,那么该case会被忽略,但是Send必须仍是一个零值。当一个接收操作被选择的时候,接收的值Select被返回。

type SelectDir

  1. type SelectDir int

A SelectDir describes the communication direction of a select case.

一个SelectDir描述了select case的通讯方向。

  1. const (
  2. SelectSend SelectDir // case Chan <- Send
  3. SelectRecv // case <-Chan:
  4. SelectDefault // default
  5. )

type SliceHeader

  1. type SliceHeader struct {
  2. Data uintptr
  3. Len int
  4. Cap int
  5. }

SliceHeader is the runtime representation of a slice. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

SliceHeader是一个运行时切片的表示。它不能保证安全性和可移植性,它的表示也许会在下一个版本发生变化。此外,Data字段不能充分保证引用的数据不会被当成垃圾收集,因此程序必须维护一个独立的、指向底层数据的类型正确的指针。

type StringHeader

  1. type StringHeader struct {
  2. Data uintptr
  3. Len int
  4. }

StringHeader is the runtime representation of a string. It cannot be used safely or portably and its representation may change in a later release. Moreover, the Data field is not sufficient to guarantee the data it references will not be garbage collected, so programs must keep a separate, correctly typed pointer to the underlying data.

StringHeader 是一个运行时字符串的表示。它不能保证安全性和可移植性,它的表示也许会在下一个版本发生变化。此外,Data字段不能充分保证引用的数据不会被当成垃圾收集,因此程序必须维护一个独立的、指向底层数据的类型正确的指针。

type StructField

  1. type StructField struct {
  2. // Name is the field name.
  3. Name string
  4. // PkgPath is the package path that qualifies a lower case (unexported)
  5. // field name. It is empty for upper case (exported) field names.
  6. // See https://golang.org/ref/spec#Uniqueness_of_identifiers
  7. PkgPath string
  8. Type Type // field type
  9. Tag StructTag // field tag string
  10. Offset uintptr // offset within struct, in bytes
  11. Index []int // index sequence for Type.FieldByIndex
  12. Anonymous bool // is an embedded field
  13. }

A StructField describes a single field in a struct.

一个StructField描述了一个结构体字段。

type StructTag

  1. type StructTag string

A StructTag is the tag string in a struct field.

一个StructTag类型的值是一个结构体字段里的tag字符串。

By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs. Each key is a non-empty string consisting of non-control characters other than space (U+0020 ' '), quote (U+0022 '"'), and colon (U+003A ':'). Each value is quoted using U+0022 '"' characters and Go string literal syntax.

通过转换,tag字符串是一个可选的以空格分隔的key:"value"对的并列。每一个key是一个非空字符串由非控制字符,同时也不能是space (U+0020 ' ') quote (U+0022 '"') colon (U+003A ':')。每一个值是一个用U+0022 '"'字符引起的Go字符串字面量。

Example

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. type S struct {
  8. F string `species:"gopher" color:"blue"`
  9. }
  10. s := S{}
  11. st := reflect.TypeOf(s)
  12. field := st.Field(0)
  13. fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
  14. }

func (StructTag) Get

  1. func (tag StructTag) Get(key string) string

Get returns the value associated with key in the tag string. If there is no such key in the tag, Get returns the empty string. If the tag does not have the conventional format, the value returned by Get is unspecified.

Get 返回tag字符串中key对应的值。如果没有tag中没有该key,Get返回空字符串。如果tag不符合标准格式,Get的返回值是不确定的。

type Type

  1. type Type interface {
  2. // Align returns the alignment in bytes of a value of
  3. // this type when allocated in memory.
  4. Align() int
  5. // FieldAlign returns the alignment in bytes of a value of
  6. // this type when used as a field in a struct.
  7. FieldAlign() int
  8. // Method returns the i'th method in the type's method set.
  9. // It panics if i is not in the range [0, NumMethod()).
  10. //
  11. // For a non-interface type T or *T, the returned Method's Type and Func
  12. // fields describe a function whose first argument is the receiver.
  13. //
  14. // For an interface type, the returned Method's Type field gives the
  15. // method signature, without a receiver, and the Func field is nil.
  16. Method(int) Method
  17. // MethodByName returns the method with that name in the type's
  18. // method set and a boolean indicating if the method was found.
  19. //
  20. // For a non-interface type T or *T, the returned Method's Type and Func
  21. // fields describe a function whose first argument is the receiver.
  22. //
  23. // For an interface type, the returned Method's Type field gives the
  24. // method signature, without a receiver, and the Func field is nil.
  25. MethodByName(string) (Method, bool)
  26. // NumMethod returns the number of methods in the type's method set.
  27. NumMethod() int
  28. // Name returns the type's name within its package.
  29. // It returns an empty string for unnamed types.
  30. Name() string
  31. // PkgPath returns a named type's package path, that is, the import path
  32. // that uniquely identifies the package, such as "encoding/base64".
  33. // If the type was predeclared (string, error) or unnamed (*T, struct{}, []int),
  34. // the package path will be the empty string.
  35. PkgPath() string
  36. // Size returns the number of bytes needed to store
  37. // a value of the given type; it is analogous to unsafe.Sizeof.
  38. Size() uintptr
  39. // String returns a string representation of the type.
  40. // The string representation may use shortened package names
  41. // (e.g., base64 instead of "encoding/base64") and is not
  42. // guaranteed to be unique among types. To test for equality,
  43. // compare the Types directly.
  44. String() string
  45. // Kind returns the specific kind of this type.
  46. Kind() Kind
  47. // Implements reports whether the type implements the interface type u.
  48. Implements(u Type) bool
  49. // AssignableTo reports whether a value of the type is assignable to type u.
  50. AssignableTo(u Type) bool
  51. // ConvertibleTo reports whether a value of the type is convertible to type u.
  52. ConvertibleTo(u Type) bool
  53. // Comparable reports whether values of this type are comparable.
  54. Comparable() bool
  55. // Bits returns the size of the type in bits.
  56. // It panics if the type's Kind is not one of the
  57. // sized or unsized Int, Uint, Float, or Complex kinds.
  58. Bits() int
  59. // ChanDir returns a channel type's direction.
  60. // It panics if the type's Kind is not Chan.
  61. ChanDir() ChanDir
  62. // IsVariadic reports whether a function type's final input parameter
  63. // is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's
  64. // implicit actual type []T.
  65. //
  66. // For concreteness, if t represents func(x int, y ... float64), then
  67. //
  68. // t.NumIn() == 2
  69. // t.In(0) is the reflect.Type for "int"
  70. // t.In(1) is the reflect.Type for "[]float64"
  71. // t.IsVariadic() == true
  72. //
  73. // IsVariadic panics if the type's Kind is not Func.
  74. IsVariadic() bool
  75. // Elem returns a type's element type.
  76. // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
  77. Elem() Type
  78. // Field returns a struct type's i'th field.
  79. // It panics if the type's Kind is not Struct.
  80. // It panics if i is not in the range [0, NumField()).
  81. Field(i int) StructField
  82. // FieldByIndex returns the nested field corresponding
  83. // to the index sequence. It is equivalent to calling Field
  84. // successively for each index i.
  85. // It panics if the type's Kind is not Struct.
  86. FieldByIndex(index []int) StructField
  87. // FieldByName returns the struct field with the given name
  88. // and a boolean indicating if the field was found.
  89. FieldByName(name string) (StructField, bool)
  90. // FieldByNameFunc returns the first struct field with a name
  91. // that satisfies the match function and a boolean indicating if
  92. // the field was found.
  93. FieldByNameFunc(match func(string) bool) (StructField, bool)
  94. // In returns the type of a function type's i'th input parameter.
  95. // It panics if the type's Kind is not Func.
  96. // It panics if i is not in the range [0, NumIn()).
  97. In(i int) Type
  98. // Key returns a map type's key type.
  99. // It panics if the type's Kind is not Map.
  100. Key() Type
  101. // Len returns an array type's length.
  102. // It panics if the type's Kind is not Array.
  103. Len() int
  104. // NumField returns a struct type's field count.
  105. // It panics if the type's Kind is not Struct.
  106. NumField() int
  107. // NumIn returns a function type's input parameter count.
  108. // It panics if the type's Kind is not Func.
  109. NumIn() int
  110. // NumOut returns a function type's output parameter count.
  111. // It panics if the type's Kind is not Func.
  112. NumOut() int
  113. // Out returns the type of a function type's i'th output parameter.
  114. // It panics if the type's Kind is not Func.
  115. // It panics if i is not in the range [0, NumOut()).
  116. Out(i int) Type
  117. // contains filtered or unexported methods
  118. }

Type is the representation of a Go type.

Type 代表Go的一个类型。

Not all methods apply to all kinds of types. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of type before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run-time panic.

不是所有的方法都能应用与所有类型。限制,如果有的话,被注释在每个方法的文档。用Kind方法查看Type类型的种类,在调用相应种类的方法时。调用一个与type的种类不合适的方法,会导致一个运行时panic。

func ArrayOf

  1. func ArrayOf(count int, elem Type) Type

ArrayOf returns the array type with the given count and element type. For example, if t represents int, ArrayOf(5, t) represents [5]int.

ArrayOf 返回给定个数和元素类型的数组类型。例如,如果t表示int,ArrayOf(5, t) 表示 [5]int

If the resulting type would be larger than the available address space, ArrayOf panics.

如果结果类型大于可获得的地址空间,ArrayOf会panic。

func ChanOf

  1. func ChanOf(dir ChanDir, t Type) Type

ChanOf returns the channel type with the given direction and element type. For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int.

ChanOf 返回给定方向和元素类型的管道类型。例如,如果t表示int,ChanOf(RecvDir, t) 表示 <-chan int

The gc runtime imposes a limit of 64 kB on channel element types. If t's size is equal to or exceeds this limit, ChanOf panics. '

运行时GC强制将通道的元素类型的大小限定为64kb。如果t的尺寸大于或等于该限制,本函数将会panic。

func FuncOf

  1. func FuncOf(in, out []Type, variadic bool) Type

FuncOf returns the function type with the given argument and result types. For example if k represents int and e represents string, FuncOf([]Type{k}, []Type{e}, false) represents func(int) string.

FuncOf 返回给定参数和返回值类型的函数类型。例如,如果k表示int,e 表示string,FuncOf([]Type{k}, []Type{e}, false)表示func(int) string

The variadic argument controls whether the function is variadic. FuncOf panics if the in[len(in)-1] does not represent a slice and variadic is true.

可变参数 控制着函数是一个可变参数函数。如果 in[len(in)-1] 不是一个切片类型并且variadic为true,那么FuncOf将会panic。

func MapOf

  1. func MapOf(key, elem Type) Type

MapOf returns the map type with the given key and element types. For example, if k represents int and e represents string, MapOf(k, e) represents map[int]string.

MapOf 返回一个映射类型,给定了键和元素的类型。例如,如果k表示int,e表示string,MapOf(k, e) 表示 map[int]string

If the key type is not a valid map key type (that is, if it does not implement Go's == operator), MapOf panics. '

如果key的类型不是一个有效的映射的键类型(也就是,如果它没有实现Go的 == 操作符),MapOf会panic。

func PtrTo

  1. func PtrTo(t Type) Type

PtrTo returns the pointer type with element t. For example, if t represents type Foo, PtrTo(t) represents *Foo.

PtrTo 返回一个指针类型,给定了元素类型t。例如,如果t表示一个类型Foo,PtrTo(t) 表示 *Foo

func SliceOf

  1. func SliceOf(t Type) Type

SliceOf returns the slice type with element type t. For example, if t represents int, SliceOf(t) represents []int.

SliceOf 返回一个slice类型,给定了元素类型 t。例如,如果t表示int,SliceOf(t)表示[]int

func TypeOf

  1. func TypeOf(i interface{}) Type

TypeOf returns the reflection Type that represents the dynamic type of i. If i is a nil interface value, TypeOf returns nil.

TypeOf 返回反射的Type,它表示了i的动态的类型。如果i是一个nil interface{} 值,TypeOf 返回nil。【???,Type 的零值是nil】

Example

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "reflect"
  7. )
  8. func main() {
  9. // As interface types are only used for static typing, a
  10. // common idiom to find the reflection Type for an interface
  11. // type Foo is to use a *Foo value.
  12. writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
  13. fileType := reflect.TypeOf((*os.File)(nil))
  14. fmt.Println(fileType.Implements(writerType))
  15. }

type Value

  1. type Value struct {
  2. // contains filtered or unexported fields
  3. }

Value is the reflection interface to a Go value.

Value 是Go的值的反射接口。

Not all methods apply to all kinds of values. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of value before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run time panic.

不是所有的方法都能应用于所有种类的值。限制,如果存在,被注释在每个方法的文档。用Kind方法来查看值得类型,在调用具体的方法之前。调用一个与类型不合适的方法会导致一个运行时panic。

The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "", and all other methods panic. Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.

Value的零值表示没有值。它的IsValid方法返回false,它的Kind方法返回Invalid,它的String方法返回 "<invalid> Value",并且所有其它方法将会panic。大多数函数和方法不会返回一个无效的值。如果返回了无效的值,那么它的文档必须显式的说明具体情况

A Value can be used concurrently by multiple goroutines provided that the underlying Go value can be used concurrently for the equivalent direct operations.

底层的Go值可以被用于并发,那么它的Value也可以用于并发。【for the equivalent direct operations.】

Using == on two Values does not compare the underlying values they represent, but rather the contents of the Value structs. To compare two Values, compare the results of the Interface method.

用 == 在两个value上不能比较它们表示的底层值,而是Value结构体的内容。为了比较两个Value,比较Interface方法返回的结果。【】

func Append

  1. func Append(s Value, x ...Value) Value

Append appends the values x to a slice s and returns the resulting slice. As in Go, each x's value must be assignable to the slice's element type.

Append 追加值x 在切片s后,然后返回结果切片。在Go里,每一个x的值必须能被复制给切片的元素类型。

func AppendSlice

  1. func AppendSlice(s, t Value) Value

AppendSlice appends a slice t to a slice s and returns the resulting slice. The slices s and t must have the same element type.

AppendSlice 追加一个切片t在切片s的后面,并返回结果切片。切片s和t必须有相同的类型。

func Indirect

  1. func Indirect(v Value) Value

Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

Indirect 返回v 指向的值。如果v是一个nil指针,Indirect 返回一个零值。如果v不是一个指针,Indirect返回v。

func MakeChan

  1. func MakeChan(typ Type, buffer int) Value

MakeChan creates a new channel with the specified type and buffer size.

MakeChan 创建一个新的管道,给定了具体类型和缓冲长度。

func MakeFunc

  1. func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value

MakeFunc returns a new function of the given Type that wraps the function fn. When called, that new function does the following:

MakeFunc 返回一个新函数,给定了一个类,包裹函数fn。当被调用的时候,该新函数做下面几件事:

- converts its arguments to a slice of Values.
- runs results := fn(args).
- returns the results as a slice of Values, one per formal result.

- 转换它的参数为一个Value的切片
- 运行 results := fn(args).
- 返回结果,作为一个Value的切片,每一个正式的结果。【】

The implementation fn can assume that the argument Value slice has the number and type of arguments given by typ. If typ describes a variadic function, the final Value is itself a slice representing the variadic arguments, as in the body of a variadic function. The result Value slice returned by fn must have the number and type of results given by typ.

fn的实现能够假定,参数Value切片有数量和类型,和typ给出的参数。【】如果typ描述了一个变长函数,最后一个Value是一个切片,用来代表变长参数,fn返回的结果Value切片必须有数量和类型,given by typ。【】

The Value.Call method allows the caller to invoke a typed function in terms of Values; in contrast, MakeFunc allows the caller to implement a typed function in terms of Values.

Value.Call 方法允许调用者去调用一个给定类型的函数,依据Values;相反地,MakeFunc允许调用者去实现一个给定类型的函数,依据Values。

The Examples section of the documentation includes an illustration of how to use MakeFunc to build a swap function for different types.

下面的例子,阐述了如何用MakeFunc去构建一个swap函数来交换不同类型的值。

Example

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. func main() {
  7. // swap is the implementation passed to MakeFunc.
  8. // It must work in terms of reflect.Values so that it is possible
  9. // to write code without knowing beforehand what the types
  10. // will be.
  11. swap := func(in []reflect.Value) []reflect.Value {
  12. return []reflect.Value{in[1], in[0]}
  13. }
  14. // makeSwap expects fptr to be a pointer to a nil function.
  15. // It sets that pointer to a new function created with MakeFunc.
  16. // When the function is invoked, reflect turns the arguments
  17. // into Values, calls swap, and then turns swap's result slice
  18. // into the values returned by the new function.
  19. makeSwap := func(fptr interface{}) {
  20. // fptr is a pointer to a function.
  21. // Obtain the function value itself (likely nil) as a reflect.Value
  22. // so that we can query its type and then set the value.
  23. fn := reflect.ValueOf(fptr).Elem()
  24. // Make a function of the right type.
  25. v := reflect.MakeFunc(fn.Type(), swap)
  26. // Assign it to the value fn represents.
  27. fn.Set(v)
  28. }
  29. // Make and call a swap function for ints.
  30. var intSwap func(int, int) (int, int)
  31. makeSwap(&intSwap)
  32. fmt.Println(intSwap(0, 1))
  33. // Make and call a swap function for float64s.
  34. var floatSwap func(float64, float64) (float64, float64)
  35. makeSwap(&floatSwap)
  36. fmt.Println(floatSwap(2.72, 3.14))
  37. }

func MakeMap

  1. func MakeMap(typ Type) Value

MakeMap creates a new map of the specified type.

MakeMap 创建一个新的指定类型的映射。

func MakeSlice

  1. func MakeSlice(typ Type, len, cap int) Value

MakeSlice creates a new zero-initialized slice value for the specified slice type, length, and capacity.

MakeSlice 创建一个新的初始化为零值的切片,给定了切片元素的类型,长度,容量。

func New

  1. func New(typ Type) Value

New returns a Value representing a pointer to a new zero value for the specified type. That is, the returned Value's Type is PtrTo(typ).

New 返回一个Value类型的值,表示一个指向给定类型的零值的指针。也就是,返回值的类型是 PtrTo(typ)。

func NewAt

  1. func NewAt(typ Type, p unsafe.Pointer) Value

NewAt returns a Value representing a pointer to a value of the specified type, using p as that pointer.

NewAt 返回一个Value,表示一个指向特定类型的指针,用 p 作为指针值。

func ValueOf

  1. func ValueOf(i interface{}) Value

ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.

ValueOf 返回一个新的Value类型的值,初始化了一个具体的值存储在接口变量 i 中。ValueOf(nil) 返回零值。

func Zero

  1. func Zero(typ Type) Value

Zero returns a Value representing the zero value for the specified type. The result is different from the zero value of the Value struct, which represents no value at all. For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. The returned value is neither addressable nor settable.

Zero 返回一个Value类型的值,表示一个给定类型的零值。这个结果与Value 结构体的零值是不同的,Value的零值表示没有值。例如,Zero(TypeOf(42)) 返回一个零值,Kind 为 Int ,值为0 。返回值是不可寻址的,不可设置的。

func (Value) Addr

  1. 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.

Addr 返回一个指针值,代表了v的地址。它将会panic,如果CanAddr()返回false。Addr是一个典型的用法,去获得一个指向结构体字段或者切片元素的指针值,为了调用一个方法,需要一个指针接受者。

func (Value) Bool

  1. func (v Value) Bool() bool

Bool returns v's underlying value. It panics if v's kind is not Bool.

Bool 返回v的底层值。如果v的Kind不是Bool,它将会panic。

func (Value) Bytes

  1. func (v Value) Bytes() []byte

Bytes returns v's underlying value. It panics if v's underlying value is not a slice of bytes.

Bytes 返回v的底层值。它将会panic,如果v的底层值不是一个byte切片。

func (Value) Call

  1. func (v Value) Call(in []Value) []Value

Call calls the function v with the input arguments in. For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). Call panics if v's Kind is not Func. It returns the output results as Values. As in Go, each input argument must be assignable to the type of the function's corresponding input parameter. If v is a variadic function, Call creates the variadic slice parameter itself, copying in the corresponding values.

Call 调用一个函数v,用输入参数in。例如,如果len(in) == 3,v.Call(in) 代表了Go调用,v(in[0], in[1], in[2])。Call panic,如果v的Kind不是一个Func。它返回输出结果,以Value的形式。在Go中,每一个输入参数必须指定为函数的输入参数一致的类型。如果v是一个可变函数,Call创建可变切片参数,复制相应的值。

func (Value) CallSlice

  1. func (v Value) CallSlice(in []Value) []Value

CallSlice calls the variadic function v with the input arguments in, assigning the slice in[len(in)-1] to v's final variadic argument. For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...). CallSlice panics if v's Kind is not Func or if v is not variadic. It returns the output results as Values. As in Go, each input argument must be assignable to the type of the function's corresponding input parameter.

CallSlice 调用可变参数函数v,指定切片 in[len(in)-1] 为v的最后一个可变参数。例如,如果len(in) == 3v.CallSlice(in) 代表Go调用 v(in[0], in[1], in[2]...)。CallSlice panic,如果v的Kind不是Func或者v不是可变参函数。它返回输出结果为
Values。在Go中,每一个输入参数的类型必须与函数的参数一致。

func (Value) CanAddr

  1. func (v Value) CanAddr() bool

CanAddr reports whether the value's address can be obtained with Addr. Such values are called addressable. A value is addressable if it is an element of a slice, an element of an addressable array, a field of an addressable struct, or the result of dereferencing a pointer. If CanAddr returns false, calling Addr will panic.

CanAddr 说明是否可以通过Addr获得该值的地址。一个值是可以寻址的,如果它是切片或者可寻址数组的一个元素,可寻址结构体的字段,或者指针解引用得到结果。如果CanAddr返回false,调用Addr将会panic。

func (Value) CanInterface

  1. func (v Value) CanInterface() bool

CanInterface reports whether Interface can be used without panicking.

CanInterface 说明 是否 Interface 能被使用,而不是panic。

func (Value) CanSet

  1. func (v Value) CanSet() bool

CanSet reports whether the value of v can be changed. A Value can be changed only if it is addressable and was not obtained by the use of unexported struct fields. If CanSet returns false, calling Set or any type-specific setter (e.g., SetBool, SetInt) will panic.

CanSet 说明v的值是否可以改变。一个Value能被改变,如果它是可寻址的,并且不是不可获得的,通过结构体的非暴露字段。如果CanSet返回false,调用Set或者任何类型制定的setter(例如,SetBool,SetInt)将会panic。

func (Value) Cap

  1. func (v Value) Cap() int

Cap returns v's capacity. It panics if v's Kind is not Array, Chan, or Slice.

Cap 返回v的容量。如果v的Kind不是Array、Chan、Slice,它将会panic。

func (Value) Close

  1. func (v Value) Close()

Close closes the channel v. It panics if v's Kind is not Chan.

Close 关闭管道v。如果v的Kind不是Chan,它将会panic。

func (Value) Complex

  1. func (v Value) Complex() complex128

Complex returns v's underlying value, as a complex128. It panics if v's Kind is not Complex64 or Complex128

Complex 返回v的底层之,作为一个complex128.它将会panic,如果v的Kind不是Complex64或者Complex128。

func (Value) Convert

  1. func (v Value) Convert(t Type) Value

Convert returns the value v converted to type t. If the usual Go conversion rules do not allow conversion of the value v to type t, Convert panics.

Convert 返回v转换为t的值。如果Go的转换规则不允许值v到类型t的转换,Convert panic。

func (Value) Elem

  1. 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.

Elem 返回 接口值v包含或者指针v指向的值。它将会panic,如果v的Kind不是Interface 或者 Ptr。它返回零值,如果v是nil。

func (Value) Field

  1. func (v Value) Field(i int) Value

Field returns the i'th field of the struct v. It panics if v's Kind is not Struct or i is out of range.

Filed 返回结构体v的第i个字段。它将会panic,如果v的Kind不是Struct,或者i超出范围。

func (Value) FieldByIndex

  1. func (v Value) FieldByIndex(index []int) Value

FieldByIndex returns the nested field corresponding to index. It panics if v's Kind is not struct.

FieldByIndex 返回索引相应的嵌套的字段。它将会panic,如果v的Kind不是一个结构体。

func (Value) FieldByName

  1. func (v Value) FieldByName(name string) Value

FieldByName returns the struct field with the given name. It returns the zero Value if no field was found. It panics if v's Kind is not struct.

FieldByName 返回结构体字段,用给定的名字。它返回零值,如果没有字段发现。它将会panic,如果v的Kind不是结构体。

func (Value) FieldByNameFunc

  1. func (v Value) FieldByNameFunc(match func(string) bool) Value

FieldByNameFunc returns the struct field with a name that satisfies the match function. It panics if v's Kind is not struct. It returns the zero Value if no field was found.

FieldByNameFunc 返回结构体字段,用给定的名字,满足匹配的函数。它将会panic,如果v的Kind不是结构体。它返回零值,如果没有字段返回。

func (Value) Float

  1. func (v Value) Float() float64

Float returns v's underlying value, as a float64. It panics if v's Kind is not Float32 or Float64

Float 返回v的底层值,作为一个float64。它将会panic,如果v的Kind不是Float23,或者Float64。

func (Value) Index

  1. func (v Value) Index(i int) Value

Index returns v's i'th element. It panics if v's Kind is not Array, Slice, or String or i is out of range.

Index 返回v的第i个元素。它将会panic,如果v的Kind不是Array、Slice、或者String,或者i超出范围。

func (Value) Int

  1. func (v Value) Int() int64

Int returns v's underlying value, as an int64. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.

Int 返回v的底层值,作为一个int64。它将会panic,如果v的Kind不是Int、Int8、Int16、Int32、或者Int64。

func (Value) Interface

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

Interface returns v's current value as an interface{}. It is equivalent to:

Interface 把v 的当前值作为一个interface{}返回。它等价于:

  1. var i interface{} = (v's underlying value)

It panics if the Value was obtained by accessing unexported struct fields.

如果Value被得到,通过访问结构体的非暴露字段,它将会panic。

func (Value) InterfaceData

  1. func (v Value) InterfaceData() [2]uintptr

InterfaceData returns the interface v's value as a uintptr pair. It panics if v's Kind is not Interface.

InterfaceData 返回接口v的值作为一个 uintptr 对。它将会panic,如果v的Kind不是Interface。

func (Value) IsNil

  1. func (v Value) IsNil() bool

IsNil reports whether its argument v is nil. The argument must be a chan, func, interface, map, pointer, or slice value; if it is not, IsNil panics. Note that IsNil is not always equivalent to a regular comparison with nil in Go. For example, if v was created by calling ValueOf with an uninitialized interface variable i, i==nil will be true but v.IsNil will panic as v will be the zero Value.

IsNil 说明是否它的参数v是nil。它的参数必须是一个chan、func、interface、map、pointer、或者slice值。如果它不是,IsNil将会panic。注意,IsNil不总是等价与一个与Go中nil的比较。例如,如果v被创建,通过调用ValueOf用一个未序列化的接口变量i,i==nil将会是true,但是v.IsNil将会panic,因为v将会是一个零值。

func (Value) IsValid

  1. func (v Value) IsValid() bool

IsValid reports whether v represents a value. It returns false if v is the zero Value. If IsValid returns false, all other methods except String panic. Most functions and methods never return an invalid value. If one does, its documentation states the conditions explicitly.

func (Value) Kind

  1. func (v Value) Kind() Kind

Kind returns v's Kind. If v is the zero Value (IsValid returns false), Kind returns Invalid.

Kind 返回v的Kind。如果v是零值(用IsValid 判断返回 false),Kind返回Invalid。

func (Value) Len

  1. func (v Value) Len() int

Len returns v's length. It panics if v's Kind is not Array, Chan, Map, Slice, or String.

Len 返回v的长度。如果v的Kind不是Array、Chan、Map、Slice或者String,它将会panic。

func (Value) MapIndex

  1. func (v Value) MapIndex(key Value) Value

MapIndex returns the value associated with key in the map v. It panics if v's Kind is not Map. It returns the zero Value if key is not found in the map or if v represents a nil map. As in Go, the key's value must be assignable to the map's key type.

func (Value) MapKeys

  1. func (v Value) MapKeys() []Value

MapKeys returns a slice containing all the keys present in the map, in unspecified order. It panics if v's Kind is not Map. It returns an empty slice if v represents a nil map.

func (Value) Method

  1. func (v Value) Method(i int) Value

Method returns a function value corresponding to v's i'th method. The arguments to a Call on the returned function should not include a receiver; the returned function will always use v as the receiver. Method panics if i is out of range or if v is a nil interface value.

func (Value) MethodByName

  1. func (v Value) MethodByName(name string) Value

MethodByName returns a function value corresponding to the method of v with the given name. The arguments to a Call on the returned function should not include a receiver; the returned function will always use v as the receiver. It returns the zero Value if no method was found.

func (Value) NumField

  1. func (v Value) NumField() int

NumField returns the number of fields in the struct v. It panics if v's Kind is not Struct.

func (Value) NumMethod

  1. func (v Value) NumMethod() int

NumMethod returns the number of methods in the value's method set.

func (Value) OverflowComplex

  1. func (v Value) OverflowComplex(x complex128) bool

OverflowComplex reports whether the complex128 x cannot be represented by v's type. It panics if v's Kind is not Complex64 or Complex128.

func (Value) OverflowFloat

  1. func (v Value) OverflowFloat(x float64) bool

OverflowFloat reports whether the float64 x cannot be represented by v's type. It panics if v's Kind is not Float32 or Float64.

func (Value) OverflowInt

  1. func (v Value) OverflowInt(x int64) bool

OverflowInt reports whether the int64 x cannot be represented by v's type. It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.

func (Value) OverflowUint

  1. func (v Value) OverflowUint(x uint64) bool

OverflowUint reports whether the uint64 x cannot be represented by v's type. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.

func (Value) Pointer

  1. func (v Value) Pointer() uintptr

Pointer returns v's value as a uintptr. It returns uintptr instead of unsafe.Pointer so that code using reflect cannot obtain unsafe.Pointers without importing the unsafe package explicitly. It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.

If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

If v's Kind is Slice, the returned pointer is to the first element of the slice. If the slice is nil the returned value is 0. If the slice is empty but non-nil the return value is non-zero.

func (Value) Recv

  1. func (v Value) Recv() (x Value, ok bool)

Recv receives and returns a value from the channel v. It panics if v's Kind is not Chan. The receive blocks until a value is ready. The boolean value ok is true if the value x corresponds to a send on the channel, false if it is a zero value received because the channel is closed.

func (Value) Send

  1. func (v Value) Send(x Value)

Send sends x on the channel v. It panics if v's kind is not Chan or if x's type is not the same type as v's element type. As in Go, x's value must be assignable to the channel's element type.

func (Value) Set

  1. func (v Value) Set(x Value)

Set assigns x to the value v. It panics if CanSet returns false. As in Go, x's value must be assignable to v's type.

func (Value) SetBool

  1. func (v Value) SetBool(x bool)

SetBool sets v's underlying value. It panics if v's Kind is not Bool or if CanSet() is false.

func (Value) SetBytes

  1. func (v Value) SetBytes(x []byte)

SetBytes sets v's underlying value. It panics if v's underlying value is not a slice of bytes.

func (Value) SetCap

  1. func (v Value) SetCap(n int)

SetCap sets v's capacity to n. It panics if v's Kind is not Slice or if n is smaller than the length or greater than the capacity of the slice.

func (Value) SetComplex

  1. func (v Value) SetComplex(x complex128)

SetComplex sets v's underlying value to x. It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.

func (Value) SetFloat

  1. func (v Value) SetFloat(x float64)

SetFloat sets v's underlying value to x. It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.

func (Value) SetInt

  1. func (v Value) SetInt(x int64)

SetInt sets v's underlying value to x. It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.

func (Value) SetLen

  1. func (v Value) SetLen(n int)

SetLen sets v's length to n. It panics if v's Kind is not Slice or if n is negative or greater than the capacity of the slice.

func (Value) SetMapIndex

  1. func (v Value) SetMapIndex(key, val Value)

SetMapIndex sets the value associated with key in the map v to val. It panics if v's Kind is not Map. If val is the zero Value, SetMapIndex deletes the key from the map. Otherwise if v holds a nil map, SetMapIndex will panic. As in Go, key's value must be assignable to the map's key type, and val's value must be assignable to the map's value type.

func (Value) SetPointer

  1. func (v Value) SetPointer(x unsafe.Pointer)

SetPointer sets the unsafe.Pointer value v to x. It panics if v's Kind is not UnsafePointer.

func (Value) SetString

  1. func (v Value) SetString(x string)

SetString sets v's underlying value to x. It panics if v's Kind is not String or if CanSet() is false.

func (Value) SetUint

  1. func (v Value) SetUint(x uint64)

SetUint sets v's underlying value to x. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.

func (Value) Slice

  1. func (v Value) Slice(i, j int) Value

Slice returns v[i:j]. It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, or if the indexes are out of bounds.

func (Value) Slice3

  1. func (v Value) Slice3(i, j, k int) Value

Slice3 is the 3-index form of the slice operation: it returns v[i:j:k]. It panics if v's Kind is not Array or Slice, or if v is an unaddressable array, or if the indexes are out of bounds.

func (Value) String

  1. func (v Value) String() string

String returns the string v's underlying value, as a string. String is a special case because of Go's String method convention. Unlike the other getters, it does not panic if v's Kind is not String. Instead, it returns a string of the form "" where T is v's type. The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.

func (Value) TryRecv

  1. func (v Value) TryRecv() (x Value, ok bool)

TryRecv attempts to receive a value from the channel v but will not block. It panics if v's Kind is not Chan. If the receive delivers a value, x is the transferred value and ok is true. If the receive cannot finish without blocking, x is the zero Value and ok is false. If the channel is closed, x is the zero value for the channel's element type and ok is false.

func (Value) TrySend

  1. func (v Value) TrySend(x Value) bool

TrySend attempts to send x on the channel v but will not block. It panics if v's Kind is not Chan. It reports whether the value was sent. As in Go, x's value must be assignable to the channel's element type.

func (Value) Type

  1. func (v Value) Type() Type

Type returns v's type.

func (Value) Uint

  1. func (v Value) Uint() uint64

Uint returns v's underlying value, as a uint64. It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.

func (Value) UnsafeAddr

  1. func (v Value) UnsafeAddr() uintptr

UnsafeAddr returns a pointer to v's data. It is for advanced clients that also import the "unsafe" package. It panics if v is not addressable.

type ValueError

  1. type ValueError struct {
  2. Method string
  3. Kind Kind
  4. }

A ValueError occurs when a Value method is invoked on a Value that does not support it. Such cases are documented in the description of each method.

func (*ValueError) Error

  1. func (e *ValueError) Error() string

Bugs


FieldByName and related functions consider struct field names to be equal if the names are equal, even if they are unexported names originating in different packages. The practical effect of this is that the result of t.FieldByName("x") is not well defined if the struct type t contains multiple fields named x (embedded from different packages). FieldByName may return one of the fields named x or may report that there are none. See golang.org/issue/4876 for more details.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注