Movatterモバイル変換


[0]ホーム

URL:


reflect

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:14Imported by:795,504

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

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

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

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

Index

Examples

Constants

Ptr is the old name for thePointer kind.

Variables

This section is empty.

Functions

funcCopy

func Copy(dst, srcValue)int

Copy copies the contents of src into dst until eitherdst has been filled or src has been exhausted.It returns the number of elements copied.Dst and src each must have kindSlice orArray, anddst and src must have the same element type.It dst is anArray, it panics ifValue.CanSet returns false.

As a special case, src can have kindString if the element type of dst is kindUint8.

funcDeepEqual

func DeepEqual(x, yany)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.

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.

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

Map 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 are the same map object or their corresponding keys(matched using Go equality) map to deeply equal values.

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

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.

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

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 containingsuch 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 thatis a sufficient condition to be deeply equal, regardless of content.DeepEqual has been defined so that the same short-cut appliesto slices and maps: if x and y are the same slice or the same map,they are deeply equal regardless of content.

As DeepEqual traverses the data values it may find a cycle. Thesecond and subsequent times that DeepEqual compares two pointervalues that have been compared before, it treats the values asequal rather than examining the values to which they point.This ensures that DeepEqual terminates.

funcSwapperadded ingo1.8

func Swapper(sliceany) func(i, jint)

Swapper returns a function that swaps the elements in the providedslice.

Swapper panics if the provided interface is not a slice.

funcTypeAssertadded ingo1.25.0

func TypeAssert[Tany](vValue) (T,bool)

TypeAssert is semantically equivalent to:

v2, ok := v.Interface().(T)

Types

typeChanDir

type ChanDirint

ChanDir represents a channel type's direction.

const (RecvDirChanDir             = 1 <<iota// <-chanSendDir// chan<-BothDir =RecvDir |SendDir// chan)

func (ChanDir)String

func (dChanDir) String()string

typeKind

type Kinduint

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

Example
package mainimport ("fmt""reflect")func main() {for _, v := range []any{"hi", 42, func() {}} {switch v := reflect.ValueOf(v); v.Kind() {case reflect.String:fmt.Println(v.String())case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:fmt.Println(v.Int())default:fmt.Printf("unhandled kind %s", v.Kind())}}}
Output:hi42unhandled kind func

const (InvalidKind =iotaBoolIntInt8Int16Int32Int64UintUint8Uint16Uint32Uint64UintptrFloat32Float64Complex64Complex128ArrayChanFuncInterfaceMapPointerSliceStringStructUnsafePointer)

func (Kind)String

func (kKind) String()string

String returns the name of k.

typeMapIteradded ingo1.12

type MapIter struct {// contains filtered or unexported fields}

A MapIter is an iterator for ranging over a map.SeeValue.MapRange.

func (*MapIter)Keyadded ingo1.12

func (iter *MapIter) Key()Value

Key returns the key of iter's current map entry.

func (*MapIter)Nextadded ingo1.12

func (iter *MapIter) Next()bool

Next advances the map iterator and reports whether there is anotherentry. It returns false when iter is exhausted; subsequentcalls toMapIter.Key,MapIter.Value, orMapIter.Next will panic.

func (*MapIter)Resetadded ingo1.18

func (iter *MapIter) Reset(vValue)

Reset modifies iter to iterate over v.It panics if v's Kind is notMap and v is not the zero Value.Reset(Value{}) causes iter to not to refer to any map,which may allow the previously iterated-over map to be garbage collected.

func (*MapIter)Valueadded ingo1.12

func (iter *MapIter) Value()Value

Value returns the value of iter's current map entry.

typeMethod

type Method struct {// Name is the method name.Namestring// PkgPath is the package path that qualifies a lower case (unexported)// method name. It is empty for upper case (exported) method names.// The combination of PkgPath and Name uniquely identifies a method// in a method set.// Seehttps://golang.org/ref/spec#Uniqueness_of_identifiersPkgPathstringTypeType// method typeFuncValue// func with receiver as first argumentIndexint// index for Type.Method}

Method represents a single method.

func (Method)IsExportedadded ingo1.17

func (mMethod) IsExported()bool

IsExported reports whether the method is exported.

typeSelectCaseadded ingo1.1

type SelectCase struct {DirSelectDir// direction of caseChanValue// channel to use (for send or receive)SendValue// value to send (for send)}

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

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

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 beassignable 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 zeroor non-zero.

If Dir isSelectRecv, 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.

typeSelectDiradded ingo1.1

type SelectDirint

A SelectDir describes the communication direction of a select case.

const (SelectSend    SelectDir// case Chan <- SendSelectRecv// case <-Chan:SelectDefault// default)

typeSliceHeaderdeprecated

type SliceHeader struct {DatauintptrLenintCapint}

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

Deprecated: Use unsafe.Slice or unsafe.SliceData instead.

typeStringHeaderdeprecated

type StringHeader struct {DatauintptrLenint}

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

Deprecated: Use unsafe.String or unsafe.StringData instead.

typeStructField

type StructField struct {// Name is the field name.Namestring// PkgPath is the package path that qualifies a lower case (unexported)// field name. It is empty for upper case (exported) field names.// Seehttps://golang.org/ref/spec#Uniqueness_of_identifiersPkgPathstringTypeType// field typeTagStructTag// field tag stringOffsetuintptr// offset within struct, in bytesIndex     []int// index sequence for Type.FieldByIndexAnonymousbool// is an embedded field}

A StructField describes a single field in a struct.

funcVisibleFieldsadded ingo1.17

func VisibleFields(tType) []StructField

VisibleFields returns all the visible fields in t, which must be astruct type. A field is defined as visible if it's accessibledirectly with a FieldByName call. The returned fields include fieldsinside anonymous struct members and unexported fields. They followthe same order found in the struct, with anonymous fields followedimmediately by their promoted fields.

For each element e of the returned slice, the corresponding fieldcan be retrieved from a value v of type t by calling v.FieldByIndex(e.Index).

func (StructField)IsExportedadded ingo1.17

func (fStructField) IsExported()bool

IsExported reports whether the field is exported.

typeStructTag

type StructTagstring

A StructTag is the tag string in a struct field.

By convention, tag strings are a concatenation ofoptionally space-separated key:"value" pairs.Each key is a non-empty string consisting of non-controlcharacters 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.

Example
package mainimport ("fmt""reflect")func main() {type S struct {F string `species:"gopher" color:"blue"`}s := S{}st := reflect.TypeOf(s)field := st.Field(0)fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))}
Output:blue gopher

func (StructTag)Get

func (tagStructTag) Get(keystring)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 valuereturned by Get is unspecified. To determine whether a tag isexplicitly set to the empty string, useStructTag.Lookup.

func (StructTag)Lookupadded ingo1.7

func (tagStructTag) Lookup(keystring) (valuestring, okbool)

Lookup returns the value associated with key in the tag string.If the key is present in the tag the value (which may be empty)is returned. Otherwise the returned value will be the empty string.The ok return value reports whether the value was explicitly set inthe tag string. If the tag does not have the conventional format,the value returned by Lookup is unspecified.

Example
package mainimport ("fmt""reflect")func main() {type S struct {F0 string `alias:"field_0"`F1 string `alias:""`F2 string}s := S{}st := reflect.TypeOf(s)for i := 0; i < st.NumField(); i++ {field := st.Field(i)if alias, ok := field.Tag.Lookup("alias"); ok {if alias == "" {fmt.Println("(blank)")} else {fmt.Println(alias)}} else {fmt.Println("(not specified)")}}}
Output:field_0(blank)(not specified)

typeType

type Type interface {// Align returns the alignment in bytes of a value of// this type when allocated in memory.Align()int// FieldAlign returns the alignment in bytes of a value of// this type when used as a field in a struct.FieldAlign()int// Method returns the i'th method in the type's method set.// It panics if i is not in the range [0, NumMethod()).//// For a non-interface type T or *T, the returned Method's Type and Func// fields describe a function whose first argument is the receiver,// and only exported methods are accessible.//// For an interface type, the returned Method's Type field gives the// method signature, without a receiver, and the Func field is nil.//// Methods are sorted in lexicographic order.//// Calling this method will force the linker to retain all exported methods in all packages.// This may make the executable binary larger but will not affect execution time.Method(int)Method// MethodByName returns the method with that name in the type's// method set and a boolean indicating if the method was found.//// For a non-interface type T or *T, the returned Method's Type and Func// fields describe a function whose first argument is the receiver.//// For an interface type, the returned Method's Type field gives the// method signature, without a receiver, and the Func field is nil.//// Calling this method will cause the linker to retain all methods with this name in all packages.// If the linker can't determine the name, it will retain all exported methods.// This may make the executable binary larger but will not affect execution time.MethodByName(string) (Method,bool)// NumMethod returns the number of methods accessible using Method.//// For a non-interface type, it returns the number of exported methods.//// For an interface type, it returns the number of exported and unexported methods.NumMethod()int// Name returns the type's name within its package for a defined type.// For other (non-defined) types it returns the empty string.Name()string// PkgPath returns a defined type's package path, that is, the import path// that uniquely identifies the package, such as "encoding/base64".// If the type was predeclared (string, error) or not defined (*T, struct{},// []int, or A where A is an alias for a non-defined type), the package path// will be the empty string.PkgPath()string// Size returns the number of bytes needed to store// a value of the given type; it is analogous to unsafe.Sizeof.Size()uintptr// String returns a string representation of the type.// The string representation may use shortened package names// (e.g., base64 instead of "encoding/base64") and is not// guaranteed to be unique among types. To test for type identity,// compare the Types directly.String()string// Kind returns the specific kind of this type.Kind()Kind// Implements reports whether the type implements the interface type u.Implements(uType)bool// AssignableTo reports whether a value of the type is assignable to type u.AssignableTo(uType)bool// ConvertibleTo reports whether a value of the type is convertible to type u.// Even if ConvertibleTo returns true, the conversion may still panic.// For example, a slice of type []T is convertible to *[N]T,// but the conversion will panic if its length is less than N.ConvertibleTo(uType)bool// Comparable reports whether values of this type are comparable.// Even if Comparable returns true, the comparison may still panic.// For example, values of interface type are comparable,// but the comparison will panic if their dynamic type is not comparable.Comparable()bool// Bits returns the size of the type in bits.// It panics if the type's Kind is not one of the// sized or unsized Int, Uint, Float, or Complex kinds.Bits()int// ChanDir returns a channel type's direction.// It panics if the type's Kind is not Chan.ChanDir()ChanDir// IsVariadic reports whether a function type's final input parameter// is a "..." parameter. If so, t.In(t.NumIn() - 1) returns the parameter's// implicit actual type []T.//// For concreteness, if t represents func(x int, y ... float64), then////t.NumIn() == 2//t.In(0) is the reflect.Type for "int"//t.In(1) is the reflect.Type for "[]float64"//t.IsVariadic() == true//// IsVariadic panics if the type's Kind is not Func.IsVariadic()bool// Elem returns a type's element type.// It panics if the type's Kind is not Array, Chan, Map, Pointer, or Slice.Elem()Type// Field returns a struct type's i'th field.// It panics if the type's Kind is not Struct.// It panics if i is not in the range [0, NumField()).Field(iint)StructField// FieldByIndex returns the nested field corresponding// to the index sequence. It is equivalent to calling Field// successively for each index i.// It panics if the type's Kind is not Struct.FieldByIndex(index []int)StructField// FieldByName returns the struct field with the given name// and a boolean indicating if the field was found.// If the returned field is promoted from an embedded struct,// then Offset in the returned StructField is the offset in// the embedded struct.FieldByName(namestring) (StructField,bool)// FieldByNameFunc returns the struct field with a name// that satisfies the match function and a boolean indicating if// the field was found.//// FieldByNameFunc considers the fields in the struct itself// and then the fields in any embedded structs, in breadth first order,// stopping at the shallowest nesting depth containing one or more// fields satisfying the match function. If multiple fields at that depth// satisfy the match function, they cancel each other// and FieldByNameFunc returns no match.// This behavior mirrors Go's handling of name lookup in// structs containing embedded fields.//// If the returned field is promoted from an embedded struct,// then Offset in the returned StructField is the offset in// the embedded struct.FieldByNameFunc(match func(string)bool) (StructField,bool)// In returns the type of a function type's i'th input parameter.// It panics if the type's Kind is not Func.// It panics if i is not in the range [0, NumIn()).In(iint)Type// Key returns a map type's key type.// It panics if the type's Kind is not Map.Key()Type// Len returns an array type's length.// It panics if the type's Kind is not Array.Len()int// NumField returns a struct type's field count.// It panics if the type's Kind is not Struct.NumField()int// NumIn returns a function type's input parameter count.// It panics if the type's Kind is not Func.NumIn()int// NumOut returns a function type's output parameter count.// It panics if the type's Kind is not Func.NumOut()int// Out returns the type of a function type's i'th output parameter.// It panics if the type's Kind is not Func.// It panics if i is not in the range [0, NumOut()).Out(iint)Type// OverflowComplex reports whether the complex128 x cannot be represented by type t.// It panics if t's Kind is not Complex64 or Complex128.OverflowComplex(xcomplex128)bool// OverflowFloat reports whether the float64 x cannot be represented by type t.// It panics if t's Kind is not Float32 or Float64.OverflowFloat(xfloat64)bool// OverflowInt reports whether the int64 x cannot be represented by type t.// It panics if t's Kind is not Int, Int8, Int16, Int32, or Int64.OverflowInt(xint64)bool// OverflowUint reports whether the uint64 x cannot be represented by type t.// It panics if t's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.OverflowUint(xuint64)bool// CanSeq reports whether a [Value] with this type can be iterated over using [Value.Seq].CanSeq()bool// CanSeq2 reports whether a [Value] with this type can be iterated over using [Value.Seq2].CanSeq2()bool// contains filtered or unexported methods}

Type is the representation of a Go type.

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 beforecalling kind-specific methods. Calling a methodinappropriate to the kind of type causes a run-time panic.

Type values are comparable, such as with the == operator,so they can be used as map keys.Two Type values are equal if they represent identical types.

funcArrayOfadded ingo1.5

func ArrayOf(lengthint, elemType)Type

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

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

funcChanOfadded ingo1.1

func ChanOf(dirChanDir, tType)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.

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.

funcFuncOfadded ingo1.5

func FuncOf(in, out []Type, variadicbool)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.

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

funcMapOfadded ingo1.1

func MapOf(key, elemType)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.

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

funcPointerToadded ingo1.18

func PointerTo(tType)Type

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

funcPtrTodeprecated

func PtrTo(tType)Type

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

PtrTo is the old spelling ofPointerTo.The two functions behave identically.

Deprecated: Superseded byPointerTo.

funcSliceOfadded ingo1.1

func SliceOf(tType)Type

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

funcStructOfadded ingo1.7

func StructOf(fields []StructField)Type

StructOf returns the struct type containing fields.The Offset and Index fields are ignored and computed as they would beby the compiler.

StructOf currently does not support promoted methods of embedded fieldsand panics if passed unexported StructFields.

Example
package mainimport ("bytes""encoding/json""fmt""reflect")func main() {typ := reflect.StructOf([]reflect.StructField{{Name: "Height",Type: reflect.TypeOf(float64(0)),Tag:  `json:"height"`,},{Name: "Age",Type: reflect.TypeOf(int(0)),Tag:  `json:"age"`,},})v := reflect.New(typ).Elem()v.Field(0).SetFloat(0.4)v.Field(1).SetInt(2)s := v.Addr().Interface()w := new(bytes.Buffer)if err := json.NewEncoder(w).Encode(s); err != nil {panic(err)}fmt.Printf("value: %+v\n", s)fmt.Printf("json:  %s", w.Bytes())r := bytes.NewReader([]byte(`{"height":1.5,"age":10}`))if err := json.NewDecoder(r).Decode(s); err != nil {panic(err)}fmt.Printf("value: %+v\n", s)}
Output:value: &{Height:0.4 Age:2}json:  {"height":0.4,"age":2}value: &{Height:1.5 Age:10}

funcTypeForadded ingo1.22.0

func TypeFor[Tany]()Type

TypeFor returns theType that represents the type argument T.

funcTypeOf

func TypeOf(iany)Type

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

Example
package mainimport ("fmt""io""os""reflect")func main() {// As interface types are only used for static typing, a// common idiom to find the reflection Type for an interface// type Foo is to use a *Foo value.writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()fileType := reflect.TypeOf((*os.File)(nil))fmt.Println(fileType.Implements(writerType))}
Output:true

typeValue

type Value struct {// contains filtered or unexported fields}

Value is the reflection interface to a Go value.

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 beforecalling kind-specific methods. Calling a methodinappropriate to the kind of type causes a run time panic.

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

A Value can be used concurrently by multiple goroutines provided thatthe underlying Go value can be used concurrently for the equivalentdirect operations.

To compare two Values, compare the results of the Interface method.Using == on two Values does not compare the underlying valuesthey represent.

funcAppend

func Append(sValue, 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.

funcAppendSlice

func AppendSlice(s, tValue)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.

funcIndirect

func Indirect(vValue)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.

funcMakeChan

func MakeChan(typType, bufferint)Value

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

funcMakeFuncadded ingo1.1

func MakeFunc(typType, fn func(args []Value) (results []Value))Value

MakeFunc returns a new function of the givenTypethat wraps the function fn. When called, that new functiondoes the following:

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

The implementation fn can assume that the argumentValue slicehas the number and type of arguments given by typ.If typ describes a variadic function, the final Value is itselfa slice representing the variadic arguments, as in thebody of a variadic function. The result Value slice returned by fnmust have the number and type of results given by typ.

TheValue.Call method allows the caller to invoke a typed functionin terms of Values; in contrast, MakeFunc allows the caller to implementa typed function in terms of Values.

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

Example
package mainimport ("fmt""reflect")func main() {// swap is the implementation passed to MakeFunc.// It must work in terms of reflect.Values so that it is possible// to write code without knowing beforehand what the types// will be.swap := func(in []reflect.Value) []reflect.Value {return []reflect.Value{in[1], in[0]}}// makeSwap expects fptr to be a pointer to a nil function.// It sets that pointer to a new function created with MakeFunc.// When the function is invoked, reflect turns the arguments// into Values, calls swap, and then turns swap's result slice// into the values returned by the new function.makeSwap := func(fptr any) {// fptr is a pointer to a function.// Obtain the function value itself (likely nil) as a reflect.Value// so that we can query its type and then set the value.fn := reflect.ValueOf(fptr).Elem()// Make a function of the right type.v := reflect.MakeFunc(fn.Type(), swap)// Assign it to the value fn represents.fn.Set(v)}// Make and call a swap function for ints.var intSwap func(int, int) (int, int)makeSwap(&intSwap)fmt.Println(intSwap(0, 1))// Make and call a swap function for float64s.var floatSwap func(float64, float64) (float64, float64)makeSwap(&floatSwap)fmt.Println(floatSwap(2.72, 3.14))}
Output:1 03.14 2.72

funcMakeMap

func MakeMap(typType)Value

MakeMap creates a new map with the specified type.

funcMakeMapWithSizeadded ingo1.9

func MakeMapWithSize(typType, nint)Value

MakeMapWithSize creates a new map with the specified typeand initial space for approximately n elements.

funcMakeSlice

func MakeSlice(typType, len, capint)Value

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

funcNew

func New(typType)Value

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

funcNewAt

func NewAt(typType, punsafe.Pointer)Value

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

funcSelectadded ingo1.1

func Select(cases []SelectCase) (chosenint, recvValue, recvOKbool)

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

funcSliceAtadded ingo1.23.0

func SliceAt(typType, punsafe.Pointer, nint)Value

SliceAt returns aValue representing a slice whose underlyingdata starts at p, with length and capacity equal to n.

This is likeunsafe.Slice.

funcValueOf

func ValueOf(iany)Value

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

funcZero

func Zero(typType)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 KindInt and value 0.The returned value is neither addressable nor settable.

func (Value)Addr

func (vValue) Addr()Value

Addr returns a pointer value representing the address of v.It panics ifValue.CanAddr returns false.Addr is typically used to obtain a pointer to a struct fieldor slice element in order to call a method that requires apointer receiver.

func (Value)Bool

func (vValue) Bool()bool

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

func (Value)Bytes

func (vValue) Bytes() []byte

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

func (Value)Call

func (vValue) 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 notFunc.It returns the output results as Values.As in Go, each input argument must be assignable to thetype of the function's corresponding input parameter.If v is a variadic function, Call creates the variadic slice parameteritself, copying in the corresponding values.

func (Value)CallSlice

func (vValue) 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 notFunc or if v is not variadic.It returns the output results as Values.As in Go, each input argument must be assignable to thetype of the function's corresponding input parameter.

func (Value)CanAddr

func (vValue) CanAddr()bool

CanAddr reports whether the value's address can be obtained withValue.Addr.Such values are called addressable. A value is addressable if it isan 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, callingValue.Addr will panic.

func (Value)CanComplexadded ingo1.18

func (vValue) CanComplex()bool

CanComplex reports whetherValue.Complex can be used without panicking.

func (Value)CanConvertadded ingo1.17

func (vValue) CanConvert(tType)bool

CanConvert reports whether the value v can be converted to type t.If v.CanConvert(t) returns true then v.Convert(t) will not panic.

func (Value)CanFloatadded ingo1.18

func (vValue) CanFloat()bool

CanFloat reports whetherValue.Float can be used without panicking.

func (Value)CanIntadded ingo1.18

func (vValue) CanInt()bool

CanInt reports whether Int can be used without panicking.

func (Value)CanInterface

func (vValue) CanInterface()bool

CanInterface reports whetherValue.Interface can be used without panicking.

func (Value)CanSet

func (vValue) CanSet()bool

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

func (Value)CanUintadded ingo1.18

func (vValue) CanUint()bool

CanUint reports whetherValue.Uint can be used without panicking.

func (Value)Cap

func (vValue) Cap()int

Cap returns v's capacity.It panics if v's Kind is notArray,Chan,Slice or pointer toArray.

func (Value)Clearadded ingo1.21.0

func (vValue) Clear()

Clear clears the contents of a map or zeros the contents of a slice.

It panics if v's Kind is notMap orSlice.

func (Value)Close

func (vValue) Close()

Close closes the channel v.It panics if v's Kind is notChan orv is a receive-only channel.

func (Value)Comparableadded ingo1.20

func (vValue) Comparable()bool

Comparable reports whether the value v is comparable.If the type of v is an interface, this checks the dynamic type.If this reports true then v.Interface() == x will not panic for any x,nor will v.Equal(u) for any Value u.

func (Value)Complex

func (vValue) Complex()complex128

Complex returns v's underlying value, as a complex128.It panics if v's Kind is notComplex64 orComplex128

func (Value)Convertadded ingo1.1

func (vValue) Convert(tType)Value

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

func (Value)Elem

func (vValue) Elem()Value

Elem returns the value that the interface v containsor that the pointer v points to.It panics if v's Kind is notInterface orPointer.It returns the zero Value if v is nil.

func (Value)Equaladded ingo1.20

func (vValue) Equal(uValue)bool

Equal reports true if v is equal to u.For two invalid values, Equal will report true.For an interface value, Equal will compare the value within the interface.Otherwise, If the values have different types, Equal will report false.Otherwise, for arrays and structs Equal will compare each element in order,and report false if it finds non-equal elements.During all comparisons, if values of the same type are compared,and the type is not comparable, Equal will panic.

func (Value)Field

func (vValue) Field(iint)Value

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

func (Value)FieldByIndex

func (vValue) FieldByIndex(index []int)Value

FieldByIndex returns the nested field corresponding to index.It panics if evaluation requires stepping through a nilpointer or a field that is not a struct.

Example
package mainimport ("fmt""reflect")func main() {// This example shows a case in which the name of a promoted field// is hidden by another field: FieldByName will not work, so// FieldByIndex must be used instead.type user struct {firstName stringlastName  string}type data struct {userfirstName stringlastName  string}u := data{user:      user{"Embedded John", "Embedded Doe"},firstName: "John",lastName:  "Doe",}s := reflect.ValueOf(u).FieldByIndex([]int{0, 1})fmt.Println("embedded last name:", s)}
Output:embedded last name: Embedded Doe

func (Value)FieldByIndexErradded ingo1.18

func (vValue) FieldByIndexErr(index []int) (Value,error)

FieldByIndexErr returns the nested field corresponding to index.It returns an error if evaluation requires stepping through a nilpointer, but panics if it must step through a field thatis not a struct.

func (Value)FieldByName

func (vValue) FieldByName(namestring)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 notStruct.

Example
package mainimport ("fmt""reflect")func main() {type user struct {firstName stringlastName  string}u := user{firstName: "John", lastName: "Doe"}s := reflect.ValueOf(u)fmt.Println("Name:", s.FieldByName("firstName"))}
Output:Name: John

func (Value)FieldByNameFunc

func (vValue) FieldByNameFunc(match func(string)bool)Value

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

func (Value)Float

func (vValue) Float()float64

Float returns v's underlying value, as a float64.It panics if v's Kind is notFloat32 orFloat64

func (Value)Growadded ingo1.20

func (vValue) Grow(nint)

Grow increases the slice's capacity, if necessary, to guarantee space foranother n elements. After Grow(n), at least n elements can be appendedto the slice without another allocation.

It panics if v's Kind is not aSlice, or if n is negative or too large toallocate the memory, or ifValue.CanSet returns false.

func (Value)Index

func (vValue) Index(iint)Value

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

func (Value)Int

func (vValue) Int()int64

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

func (Value)Interface

func (vValue) Interface() (iany)

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

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

It panics if the Value was obtained by accessingunexported struct fields.

func (Value)InterfaceDatadeprecated

func (vValue) InterfaceData() [2]uintptr

InterfaceData returns a pair of unspecified uintptr values.It panics if v's Kind is not Interface.

In earlier versions of Go, this function returned the interface'svalue as a uintptr pair. As of Go 1.4, the implementation ofinterface values precludes any defined use of InterfaceData.

Deprecated: The memory representation of interface values is notcompatible with InterfaceData.

func (Value)IsNil

func (vValue) IsNil()bool

IsNil reports whether its argument v is nil. The argument must bea chan, func, interface, map, pointer, or slice value; if it isnot, IsNil panics. Note that IsNil is not always equivalent to aregular comparison with nil in Go. For example, if v was createdby callingValueOf with an uninitialized interface variable i,i==nil will be true but v.IsNil will panic as v will be the zeroValue.

func (Value)IsValid

func (vValue) IsValid()bool

IsValid reports whether v represents a value.It returns false if v is the zero Value.IfValue.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)IsZeroadded ingo1.13

func (vValue) IsZero()bool

IsZero reports whether v is the zero value for its type.It panics if the argument is invalid.

func (Value)Kind

func (vValue) Kind()Kind

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

func (Value)Len

func (vValue) Len()int

Len returns v's length.It panics if v's Kind is notArray,Chan,Map,Slice,String, or pointer toArray.

func (Value)MapIndex

func (vValue) MapIndex(keyValue)Value

MapIndex returns the value associated with key in the map v.It panics if v's Kind is notMap.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

func (vValue) MapKeys() []Value

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

func (Value)MapRangeadded ingo1.12

func (vValue) MapRange() *MapIter

MapRange returns a range iterator for a map.It panics if v's Kind is notMap.

CallMapIter.Next to advance the iterator, andMapIter.Key/MapIter.Value to access each entry.MapIter.Next returns false when the iterator is exhausted.MapRange follows the same iteration semantics as a range statement.

Example:

iter := reflect.ValueOf(m).MapRange()for iter.Next() {k := iter.Key()v := iter.Value()...}

func (Value)Method

func (vValue) Method(iint)Value

Method returns a function value corresponding to v's i'th method.The arguments to a Call on the returned function should not includea 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.

Calling this method will force the linker to retain all exported methods in all packages.This may make the executable binary larger but will not affect execution time.

func (Value)MethodByName

func (vValue) MethodByName(namestring)Value

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

Calling this method will cause the linker to retain all methods with this name in all packages.If the linker can't determine the name, it will retain all exported methods.This may make the executable binary larger but will not affect execution time.

func (Value)NumField

func (vValue) NumField()int

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

func (Value)NumMethod

func (vValue) NumMethod()int

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

For a non-interface type, it returns the number of exported methods.

For an interface type, it returns the number of exported and unexported methods.

func (Value)OverflowComplex

func (vValue) OverflowComplex(xcomplex128)bool

OverflowComplex reports whether the complex128 x cannot be represented by v's type.It panics if v's Kind is notComplex64 orComplex128.

func (Value)OverflowFloat

func (vValue) OverflowFloat(xfloat64)bool

OverflowFloat reports whether the float64 x cannot be represented by v's type.It panics if v's Kind is notFloat32 orFloat64.

func (Value)OverflowInt

func (vValue) OverflowInt(xint64)bool

OverflowInt reports whether the int64 x cannot be represented by v's type.It panics if v's Kind is notInt,Int8,Int16,Int32, orInt64.

func (Value)OverflowUint

func (vValue) OverflowUint(xuint64)bool

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

func (Value)Pointer

func (vValue) Pointer()uintptr

Pointer returns v's value as a uintptr.It panics if v's Kind is notChan,Func,Map,Pointer,Slice,String, orUnsafePointer.

If v's Kind isFunc, the returned pointer is an underlyingcode pointer, but not necessarily enough to identify asingle function uniquely. The only guarantee is that theresult is zero if and only if v is a nil func Value.

If v's Kind isSlice, the returned pointer is to the firstelement of the slice. If the slice is nil the returned valueis 0. If the slice is empty but non-nil the return value is non-zero.

If v's Kind isString, the returned pointer is to the firstelement of the underlying bytes of string.

It's preferred to use uintptr(Value.UnsafePointer()) to get the equivalent result.

func (Value)Recv

func (vValue) Recv() (xValue, okbool)

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

func (Value)Send

func (vValue) Send(xValue)

Send sends x on the channel v.It panics if v's kind is notChan 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)Seqadded ingo1.23.0

func (vValue) Seq()iter.Seq[Value]

Seq returns an iter.Seq[Value] that loops over the elements of v.If v's kind is Func, it must be a function that has no results andthat takes a single argument of type func(T) bool for some type T.If v's kind is Pointer, the pointer element type must have kind Array.Otherwise v's kind must be Int, Int8, Int16, Int32, Int64,Uint, Uint8, Uint16, Uint32, Uint64, Uintptr,Array, Chan, Map, Slice, or String.

func (Value)Seq2added ingo1.23.0

func (vValue) Seq2()iter.Seq2[Value,Value]

Seq2 returns an iter.Seq2[Value, Value] that loops over the elements of v.If v's kind is Func, it must be a function that has no results andthat takes a single argument of type func(K, V) bool for some type K, V.If v's kind is Pointer, the pointer element type must have kind Array.Otherwise v's kind must be Array, Map, Slice, or String.

func (Value)Set

func (vValue) Set(xValue)

Set assigns x to the value v.It panics ifValue.CanSet returns false.As in Go, x's value must be assignable to v's type andmust not be derived from an unexported field.

func (Value)SetBool

func (vValue) SetBool(xbool)

SetBool sets v's underlying value.It panics if v's Kind is notBool or ifValue.CanSet returns false.

func (Value)SetBytes

func (vValue) SetBytes(x []byte)

SetBytes sets v's underlying value.It panics if v's underlying value is not a slice of bytesor ifValue.CanSet returns false.

func (Value)SetCapadded ingo1.2

func (vValue) SetCap(nint)

SetCap sets v's capacity to n.It panics if v's Kind is notSlice, or if n is smaller than the length orgreater than the capacity of the slice,or ifValue.CanSet returns false.

func (Value)SetComplex

func (vValue) SetComplex(xcomplex128)

SetComplex sets v's underlying value to x.It panics if v's Kind is notComplex64 orComplex128,or ifValue.CanSet returns false.

func (Value)SetFloat

func (vValue) SetFloat(xfloat64)

SetFloat sets v's underlying value to x.It panics if v's Kind is notFloat32 orFloat64,or ifValue.CanSet returns false.

func (Value)SetInt

func (vValue) SetInt(xint64)

SetInt sets v's underlying value to x.It panics if v's Kind is notInt,Int8,Int16,Int32, orInt64,or ifValue.CanSet returns false.

func (Value)SetIterKeyadded ingo1.18

func (vValue) SetIterKey(iter *MapIter)

SetIterKey assigns to v the key of iter's current map entry.It is equivalent to v.Set(iter.Key()), but it avoids allocating a new Value.As in Go, the key must be assignable to v's type andmust not be derived from an unexported field.It panics ifValue.CanSet returns false.

func (Value)SetIterValueadded ingo1.18

func (vValue) SetIterValue(iter *MapIter)

SetIterValue assigns to v the value of iter's current map entry.It is equivalent to v.Set(iter.Value()), but it avoids allocating a new Value.As in Go, the value must be assignable to v's type andmust not be derived from an unexported field.It panics ifValue.CanSet returns false.

func (Value)SetLen

func (vValue) SetLen(nint)

SetLen sets v's length to n.It panics if v's Kind is notSlice, or if n is negative orgreater than the capacity of the slice,or ifValue.CanSet returns false.

func (Value)SetMapIndex

func (vValue) SetMapIndex(key, elemValue)

SetMapIndex sets the element associated with key in the map v to elem.It panics if v's Kind is notMap.If elem 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 elem must be assignable to the map's key type,and elem's value must be assignable to the map's elem type.

func (Value)SetPointer

func (vValue) SetPointer(xunsafe.Pointer)

SetPointer sets theunsafe.Pointer value v to x.It panics if v's Kind is notUnsafePointeror ifValue.CanSet returns false.

func (Value)SetString

func (vValue) SetString(xstring)

SetString sets v's underlying value to x.It panics if v's Kind is notString or ifValue.CanSet returns false.

func (Value)SetUint

func (vValue) SetUint(xuint64)

SetUint sets v's underlying value to x.It panics if v's Kind is notUint,Uintptr,Uint8,Uint16,Uint32, orUint64,or ifValue.CanSet returns false.

func (Value)SetZeroadded ingo1.20

func (vValue) SetZero()

SetZero sets v to be the zero value of v's type.It panics ifValue.CanSet returns false.

func (Value)Slice

func (vValue) Slice(i, jint)Value

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

func (Value)Slice3added ingo1.2

func (vValue) Slice3(i, j, kint)Value

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

func (Value)String

func (vValue) 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 notString.Instead, it returns a string of the form "<T value>" where T is v's type.The fmt package treats Values specially. It does not call their Stringmethod implicitly but instead prints the concrete values they hold.

func (Value)TryRecv

func (vValue) TryRecv() (xValue, okbool)

TryRecv attempts to receive a value from the channel v but will not block.It panics if v's Kind is notChan.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

func (vValue) TrySend(xValue)bool

TrySend attempts to send x on the channel v but will not block.It panics if v's Kind is notChan.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

func (vValue) Type()Type

Type returns v's type.

func (Value)Uint

func (vValue) Uint()uint64

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

func (Value)UnsafeAddr

func (vValue) UnsafeAddr()uintptr

UnsafeAddr returns a pointer to v's data, as a uintptr.It panics if v is not addressable.

It's preferred to use uintptr(Value.Addr().UnsafePointer()) to get the equivalent result.

func (Value)UnsafePointeradded ingo1.18

func (vValue) UnsafePointer()unsafe.Pointer

UnsafePointer returns v's value as aunsafe.Pointer.It panics if v's Kind is notChan,Func,Map,Pointer,Slice,String orUnsafePointer.

If v's Kind isFunc, the returned pointer is an underlyingcode pointer, but not necessarily enough to identify asingle function uniquely. The only guarantee is that theresult is zero if and only if v is a nil func Value.

If v's Kind isSlice, the returned pointer is to the firstelement of the slice. If the slice is nil the returned valueis nil. If the slice is empty but non-nil the return value is non-nil.

If v's Kind isString, the returned pointer is to the firstelement of the underlying bytes of string.

typeValueError

type ValueError struct {MethodstringKindKind}

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

func (*ValueError)Error

func (e *ValueError) Error()string

Notes

Bugs

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

Source Files

View all Source files

Directories

PathSynopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp