1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 const bigEndian
= false // can be smarter if we find a big-endian machine
15 const ptrSize
= unsafe
.Sizeof((*byte)(nil))
16 const cannotSet
= "cannot set value obtained from unexported struct field"
18 // TODO: This will have to go away when
19 // the new gc goes in.
20 func memmove(adst
, asrc unsafe
.Pointer
, n
uintptr) {
24 case src
< dst
&& src
+n
> dst
:
26 // careful: i is unsigned
29 *(*byte)(unsafe
.Pointer(dst
+ i
)) = *(*byte)(unsafe
.Pointer(src
+ i
))
31 case (n|src|dst
)&(ptrSize
-1) != 0:
33 for i
:= uintptr(0); i
< n
; i
++ {
34 *(*byte)(unsafe
.Pointer(dst
+ i
)) = *(*byte)(unsafe
.Pointer(src
+ i
))
38 for i
:= uintptr(0); i
< n
; i
+= ptrSize
{
39 *(*uintptr)(unsafe
.Pointer(dst
+ i
)) = *(*uintptr)(unsafe
.Pointer(src
+ i
))
44 // Value is the reflection interface to a Go value.
46 // Not all methods apply to all kinds of values. Restrictions,
47 // if any, are noted in the documentation for each method.
48 // Use the Kind method to find out the kind of value before
49 // calling kind-specific methods. Calling a method
50 // inappropriate to the kind of type causes a run time panic.
52 // The zero Value represents no value.
53 // Its IsValid method returns false, its Kind method returns Invalid,
54 // its String method returns "<invalid Value>", and all other methods panic.
55 // Most functions and methods never return an invalid value.
56 // If one does, its documentation states the conditions explicitly.
58 // A Value can be used concurrently by multiple goroutines provided that
59 // the underlying Go value can be used concurrently for the equivalent
62 // typ holds the type of the value represented by a Value.
65 // Pointer-valued data or, if flagIndir is set, pointer to data.
66 // Valid when either flagIndir is set or typ.pointers() is true.
67 // Gccgo always uses this field.
70 // Non-pointer-valued data. When the data is smaller
71 // than a word, it begins at the first byte (in the memory
72 // address sense) of this field.
73 // Valid when flagIndir is not set and typ.pointers() is false.
74 // Gccgo never uses this field.
77 // flag holds metadata about the value.
78 // The lowest bits are flag bits:
79 // - flagRO: obtained via unexported field, so read-only
80 // - flagIndir: val holds a pointer to the data
81 // - flagAddr: v.CanAddr is true (implies flagIndir)
82 // - flagMethod: v is a method value.
83 // The next five bits give the Kind of the value.
84 // This repeats typ.Kind() except for method values.
85 // The remaining 23+ bits give a method number for method values.
86 // If flag.kind() != Func, code can assume that flagMethod is unset.
87 // If typ.size > ptrSize, code can assume that flagIndir is set.
90 // A method value represents a curried method invocation
91 // like r.Read for some receiver r. The typ+val+flag bits describe
92 // the receiver r, but the flag's Kind bits say Func (methods are
93 // functions), and the top bits of the flag give the method number
94 // in r's type's method table.
100 flagRO flag
= 1 << iota
104 flagMethodFn
// gccgo: first fn parameter is always pointer
106 flagKindWidth
= 5 // there are 27 kinds
107 flagKindMask flag
= 1<<flagKindWidth
- 1
108 flagMethodShift
= flagKindShift
+ flagKindWidth
111 func (f flag
) kind() Kind
{
112 return Kind((f
>> flagKindShift
) & flagKindMask
)
115 // pointer returns the underlying pointer represented by v.
116 // v.Kind() must be Ptr, Map, Chan, Func, or UnsafePointer
117 func (v Value
) pointer() unsafe
.Pointer
{
118 if v
.typ
.size
!= ptrSize ||
!v
.typ
.pointers() {
119 panic("can't call pointer on a non-pointer Value")
121 if v
.flag
&flagIndir
!= 0 {
122 return *(*unsafe
.Pointer
)(v
.ptr
)
127 // packEface converts v to the empty interface.
128 func packEface(v Value
) interface{} {
131 e
:= (*emptyInterface
)(unsafe
.Pointer(&i
))
132 // First, fill in the data portion of the interface.
134 case v
.Kind() != Ptr
&& v
.Kind() != UnsafePointer
:
135 // Value is indirect, and so is the interface we're making.
136 if v
.flag
&flagIndir
== 0 {
137 panic("reflect: missing flagIndir")
140 if v
.flag
&flagAddr
!= 0 {
141 // TODO: pass safe boolean from valueInterface so
142 // we don't need to copy if safe==true?
144 memmove(c
, ptr
, t
.size
)
148 case v
.flag
&flagIndir
!= 0:
149 // Value is indirect, but interface is direct. We need
150 // to load the data at v.ptr into the interface data word.
152 e
.word
= iword(*(*unsafe
.Pointer
)(v
.ptr
))
154 e
.word
= iword(loadScalar(v
.ptr
, t
.size
))
157 // Value is direct, and so is the interface.
159 e
.word
= iword(v
.ptr
)
161 // e.word = iword(v.scalar)
162 panic("reflect: missing flagIndir")
165 // Now, fill in the type portion. We're very careful here not
166 // to have any operation between the e.word and e.typ assignments
167 // that would let the garbage collector observe the partially-built
173 // unpackEface converts the empty interface i to a Value.
174 func unpackEface(i
interface{}) Value
{
175 e
:= (*emptyInterface
)(unsafe
.Pointer(&i
))
176 // NOTE: don't read e.word until we know whether it is really a pointer or not.
181 f
:= flag(t
.Kind()) << flagKindShift
182 if t
.Kind() != Ptr
&& t
.Kind() != UnsafePointer
{
185 return Value
{t
, unsafe
.Pointer(e
.word
), f
}
188 // A ValueError occurs when a Value method is invoked on
189 // a Value that does not support it. Such cases are documented
190 // in the description of each method.
191 type ValueError
struct {
196 func (e
*ValueError
) Error() string {
198 return "reflect: call of " + e
.Method
+ " on zero Value"
200 return "reflect: call of " + e
.Method
+ " on " + e
.Kind
.String() + " Value"
203 // methodName returns the name of the calling method,
204 // assumed to be two stack frames above.
205 func methodName() string {
206 pc
, _
, _
, _
:= runtime
.Caller(2)
207 f
:= runtime
.FuncForPC(pc
)
209 return "unknown method"
214 // An iword is the word that would be stored in an
215 // interface to represent a given value v. Specifically, if v is
216 // bigger than a pointer, its word is a pointer to v's data.
217 // Otherwise, its word holds the data stored
218 // in its leading bytes (so is not a pointer).
219 // Because the value sometimes holds a pointer, we use
220 // unsafe.Pointer to represent it, so that if iword appears
221 // in a struct, the garbage collector knows that might be
223 // TODO: get rid of all occurrences of iword (except in the interface decls below?)
224 // We want to get rid of the "feature" that an unsafe.Pointer is sometimes a pointer
225 // and sometimes a uintptr.
226 type iword unsafe
.Pointer
228 // Get an iword that represents this value.
229 // TODO: this function goes away at some point
230 func (v Value
) iword() iword
{
235 if v
.flag
&flagIndir
!= 0 {
236 if v
.kind() != Ptr
&& v
.kind() != UnsafePointer
{
239 // Have indirect but want direct word.
241 return iword(*(*unsafe
.Pointer
)(v
.ptr
))
243 return iword(loadScalar(v
.ptr
, v
.typ
.size
))
248 // return iword(v.scalar)
249 panic("reflect: missing flagIndir")
252 // Build a Value from a type/iword pair, plus any extra flags.
253 // TODO: this function goes away at some point
254 func fromIword(t
*rtype
, w iword
, fl flag
) Value
{
255 fl |
= flag(t
.Kind()) << flagKindShift
256 if t
.Kind() != Ptr
&& t
.Kind() != UnsafePointer
{
257 return Value
{t
, unsafe
.Pointer(w
) /* 0, */, fl | flagIndir
}
258 } else if t
.pointers() {
259 return Value
{t
, unsafe
.Pointer(w
) /* 0, */, fl
}
261 panic("reflect: can't reach")
265 // loadScalar loads n bytes at p from memory into a uintptr
266 // that forms the second word of an interface. The data
267 // must be non-pointer in nature.
268 func loadScalar(p unsafe
.Pointer
, n
uintptr) uintptr {
269 // Run the copy ourselves instead of calling memmove
270 // to avoid moving w to the heap.
274 panic("reflect: internal error: loadScalar of " + strconv
.Itoa(int(n
)) + "-byte value")
277 *(*uint8)(unsafe
.Pointer(&w
)) = *(*uint8)(p
)
279 *(*uint16)(unsafe
.Pointer(&w
)) = *(*uint16)(p
)
281 *(*[3]byte)(unsafe
.Pointer(&w
)) = *(*[3]byte)(p
)
283 *(*uint32)(unsafe
.Pointer(&w
)) = *(*uint32)(p
)
285 *(*[5]byte)(unsafe
.Pointer(&w
)) = *(*[5]byte)(p
)
287 *(*[6]byte)(unsafe
.Pointer(&w
)) = *(*[6]byte)(p
)
289 *(*[7]byte)(unsafe
.Pointer(&w
)) = *(*[7]byte)(p
)
291 *(*uint64)(unsafe
.Pointer(&w
)) = *(*uint64)(p
)
296 // storeScalar stores n bytes from w into p.
297 func storeScalar(p unsafe
.Pointer
, w
uintptr, n
uintptr) {
298 // Run the copy ourselves instead of calling memmove
299 // to avoid moving w to the heap.
302 panic("reflect: internal error: storeScalar of " + strconv
.Itoa(int(n
)) + "-byte value")
305 *(*uint8)(p
) = *(*uint8)(unsafe
.Pointer(&w
))
307 *(*uint16)(p
) = *(*uint16)(unsafe
.Pointer(&w
))
309 *(*[3]byte)(p
) = *(*[3]byte)(unsafe
.Pointer(&w
))
311 *(*uint32)(p
) = *(*uint32)(unsafe
.Pointer(&w
))
313 *(*[5]byte)(p
) = *(*[5]byte)(unsafe
.Pointer(&w
))
315 *(*[6]byte)(p
) = *(*[6]byte)(unsafe
.Pointer(&w
))
317 *(*[7]byte)(p
) = *(*[7]byte)(unsafe
.Pointer(&w
))
319 *(*uint64)(p
) = *(*uint64)(unsafe
.Pointer(&w
))
323 // emptyInterface is the header for an interface{} value.
324 type emptyInterface
struct {
329 // nonEmptyInterface is the header for a interface value with methods.
330 type nonEmptyInterface
struct {
331 // see ../runtime/iface.c:/Itab
333 typ
*rtype
// dynamic concrete type
334 fun
[100000]unsafe
.Pointer
// method table
339 // mustBe panics if f's kind is not expected.
340 // Making this a method on flag instead of on Value
341 // (and embedding flag in Value) means that we can write
342 // the very clear v.mustBe(Bool) and have it compile into
343 // v.flag.mustBe(Bool), which will only bother to copy the
344 // single important word for the receiver.
345 func (f flag
) mustBe(expected Kind
) {
348 panic(&ValueError
{methodName(), k
})
352 // mustBeExported panics if f records that the value was obtained using
353 // an unexported field.
354 func (f flag
) mustBeExported() {
356 panic(&ValueError
{methodName(), 0})
359 panic("reflect: " + methodName() + " using value obtained using unexported field")
363 // mustBeAssignable panics if f records that the value is not assignable,
364 // which is to say that either it was obtained using an unexported field
365 // or it is not addressable.
366 func (f flag
) mustBeAssignable() {
368 panic(&ValueError
{methodName(), Invalid
})
370 // Assignable if addressable and not read-only.
372 panic("reflect: " + methodName() + " using value obtained using unexported field")
375 panic("reflect: " + methodName() + " using unaddressable value")
379 // Addr returns a pointer value representing the address of v.
380 // It panics if CanAddr() returns false.
381 // Addr is typically used to obtain a pointer to a struct field
382 // or slice element in order to call a method that requires a
384 func (v Value
) Addr() Value
{
385 if v
.flag
&flagAddr
== 0 {
386 panic("reflect.Value.Addr of unaddressable value")
388 return Value
{v
.typ
.ptrTo(), v
.ptr
/* 0, */, (v
.flag
& flagRO
) |
flag(Ptr
)<<flagKindShift
}
391 // Bool returns v's underlying value.
392 // It panics if v's kind is not Bool.
393 func (v Value
) Bool() bool {
395 if v
.flag
&flagIndir
!= 0 {
396 return *(*bool)(v
.ptr
)
398 // return *(*bool)(unsafe.Pointer(&v.scalar))
399 panic("reflect: missing flagIndir")
402 // Bytes returns v's underlying value.
403 // It panics if v's underlying value is not a slice of bytes.
404 func (v Value
) Bytes() []byte {
406 if v
.typ
.Elem().Kind() != Uint8
{
407 panic("reflect.Value.Bytes of non-byte slice")
409 // Slice is always bigger than a word; assume flagIndir.
410 return *(*[]byte)(v
.ptr
)
413 // runes returns v's underlying value.
414 // It panics if v's underlying value is not a slice of runes (int32s).
415 func (v Value
) runes() []rune
{
417 if v
.typ
.Elem().Kind() != Int32
{
418 panic("reflect.Value.Bytes of non-rune slice")
420 // Slice is always bigger than a word; assume flagIndir.
421 return *(*[]rune
)(v
.ptr
)
424 // CanAddr returns true if the value's address can be obtained with Addr.
425 // Such values are called addressable. A value is addressable if it is
426 // an element of a slice, an element of an addressable array,
427 // a field of an addressable struct, or the result of dereferencing a pointer.
428 // If CanAddr returns false, calling Addr will panic.
429 func (v Value
) CanAddr() bool {
430 return v
.flag
&flagAddr
!= 0
433 // CanSet returns true if the value of v can be changed.
434 // A Value can be changed only if it is addressable and was not
435 // obtained by the use of unexported struct fields.
436 // If CanSet returns false, calling Set or any type-specific
437 // setter (e.g., SetBool, SetInt64) will panic.
438 func (v Value
) CanSet() bool {
439 return v
.flag
&(flagAddr|flagRO
) == flagAddr
442 // Call calls the function v with the input arguments in.
443 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]).
444 // Call panics if v's Kind is not Func.
445 // It returns the output results as Values.
446 // As in Go, each input argument must be assignable to the
447 // type of the function's corresponding input parameter.
448 // If v is a variadic function, Call creates the variadic slice parameter
449 // itself, copying in the corresponding values.
450 func (v Value
) Call(in
[]Value
) []Value
{
453 return v
.call("Call", in
)
456 // CallSlice calls the variadic function v with the input arguments in,
457 // assigning the slice in[len(in)-1] to v's final variadic argument.
458 // For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]...).
459 // Call panics if v's Kind is not Func or if v is not variadic.
460 // It returns the output results as Values.
461 // As in Go, each input argument must be assignable to the
462 // type of the function's corresponding input parameter.
463 func (v Value
) CallSlice(in
[]Value
) []Value
{
466 return v
.call("CallSlice", in
)
469 var makeFuncStubFn
= makeFuncStub
470 var makeFuncStubCode
= **(**uintptr)(unsafe
.Pointer(&makeFuncStubFn
))
472 func (v Value
) call(op
string, in
[]Value
) []Value
{
473 // Get function pointer, type.
479 if v
.flag
&flagMethod
!= 0 {
480 t
, fn
, rcvr
= methodReceiver(op
, v
, int(v
.flag
)>>flagMethodShift
)
481 } else if v
.flag
&flagIndir
!= 0 {
482 fn
= *(*unsafe
.Pointer
)(v
.ptr
)
488 panic("reflect.Value.Call: call of nil function")
491 // If target is makeFuncStub, short circuit the unpack onto stack /
492 // pack back into []Value for the args and return values. Just do the
494 // We need to do this here because otherwise we have a situation where
495 // reflect.callXX calls makeFuncStub, neither of which knows the
496 // layout of the args. That's bad for precise gc & stack copying.
497 x
:= (*makeFuncImpl
)(fn
)
498 if x
.code
== makeFuncStubCode
{
502 isSlice
:= op
== "CallSlice"
506 panic("reflect: CallSlice of non-variadic function")
509 panic("reflect: CallSlice with too few input arguments")
512 panic("reflect: CallSlice with too many input arguments")
519 panic("reflect: Call with too few input arguments")
521 if !t
.IsVariadic() && len(in
) > n
{
522 panic("reflect: Call with too many input arguments")
525 for _
, x
:= range in
{
526 if x
.Kind() == Invalid
{
527 panic("reflect: " + op
+ " using zero Value argument")
530 for i
:= 0; i
< n
; i
++ {
531 if xt
, targ
:= in
[i
].Type(), t
.In(i
); !xt
.AssignableTo(targ
) {
532 panic("reflect: " + op
+ " using " + xt
.String() + " as type " + targ
.String())
535 if !isSlice
&& t
.IsVariadic() {
536 // prepare slice for remaining values
538 slice
:= MakeSlice(t
.In(n
), m
, m
)
539 elem
:= t
.In(n
).Elem()
540 for i
:= 0; i
< m
; i
++ {
542 if xt
:= x
.Type(); !xt
.AssignableTo(elem
) {
543 panic("reflect: cannot use " + xt
.String() + " as type " + elem
.String() + " in " + op
)
545 slice
.Index(i
).Set(x
)
548 in
= make([]Value
, n
+1)
554 if nin
!= t
.NumIn() {
555 panic("reflect.Value.Call: wrong argument count")
559 if v
.flag
&flagMethod
!= 0 {
562 firstPointer
:= len(in
) > 0 && t
.In(0).Kind() != Ptr
&& v
.flag
&flagMethodFn
!= 0
563 params
:= make([]unsafe
.Pointer
, nin
)
565 if v
.flag
&flagMethod
!= 0 {
566 // Hard-wired first argument.
569 params
[0] = unsafe
.Pointer(p
)
572 for i
, pv
:= range in
{
574 targ
:= t
.In(i
).(*rtype
)
575 pv
= pv
.assignTo("reflect.Value.Call", targ
, nil)
576 if pv
.flag
&flagIndir
== 0 {
577 p
:= new(unsafe
.Pointer
)
579 params
[off
] = unsafe
.Pointer(p
)
583 if i
== 0 && firstPointer
{
584 p
:= new(unsafe
.Pointer
)
586 params
[off
] = unsafe
.Pointer(p
)
591 ret
:= make([]Value
, nout
)
592 results
:= make([]unsafe
.Pointer
, nout
)
593 for i
:= 0; i
< nout
; i
++ {
595 results
[i
] = unsafe
.Pointer(v
.Pointer())
599 var pp
*unsafe
.Pointer
603 var pr
*unsafe
.Pointer
604 if len(results
) > 0 {
608 call(t
, fn
, v
.flag
&flagMethod
!= 0, firstPointer
, pp
, pr
)
613 // methodReceiver returns information about the receiver
614 // described by v. The Value v may or may not have the
615 // flagMethod bit set, so the kind cached in v.flag should
617 func methodReceiver(op
string, v Value
, methodIndex
int) (t
*rtype
, fn unsafe
.Pointer
, rcvr iword
) {
619 if v
.typ
.Kind() == Interface
{
620 tt
:= (*interfaceType
)(unsafe
.Pointer(v
.typ
))
621 if i
< 0 || i
>= len(tt
.methods
) {
622 panic("reflect: internal error: invalid method index")
625 if m
.pkgPath
!= nil {
626 panic("reflect: " + op
+ " of unexported method")
629 iface
:= (*nonEmptyInterface
)(v
.ptr
)
630 if iface
.itab
== nil {
631 panic("reflect: " + op
+ " of method on nil interface value")
633 fn
= unsafe
.Pointer(&iface
.itab
.fun
[i
])
636 ut
:= v
.typ
.uncommon()
637 if ut
== nil || i
< 0 || i
>= len(ut
.methods
) {
638 panic("reflect: internal error: invalid method index")
641 if m
.pkgPath
!= nil {
642 panic("reflect: " + op
+ " of unexported method")
644 fn
= unsafe
.Pointer(&m
.tfn
)
646 // Can't call iword here, because it checks v.kind,
647 // and that is always Func.
648 if v
.flag
&flagIndir
!= 0 && (v
.typ
.Kind() == Ptr || v
.typ
.Kind() == UnsafePointer
) {
649 rcvr
= iword(loadScalar(v
.ptr
, v
.typ
.size
))
657 // align returns the result of rounding x up to a multiple of n.
658 // n must be a power of two.
659 func align(x
, n
uintptr) uintptr {
660 return (x
+ n
- 1) &^ (n
- 1)
663 // funcName returns the name of f, for use in error messages.
664 func funcName(f
func([]Value
) []Value
) string {
665 pc
:= *(*uintptr)(unsafe
.Pointer(&f
))
666 rf
:= runtime
.FuncForPC(pc
)
673 // Cap returns v's capacity.
674 // It panics if v's Kind is not Array, Chan, or Slice.
675 func (v Value
) Cap() int {
681 return int(chancap(v
.pointer()))
683 // Slice is always bigger than a word; assume flagIndir.
684 return (*sliceHeader
)(v
.ptr
).Cap
686 panic(&ValueError
{"reflect.Value.Cap", k
})
689 // Close closes the channel v.
690 // It panics if v's Kind is not Chan.
691 func (v Value
) Close() {
694 chanclose(v
.pointer())
697 // Complex returns v's underlying value, as a complex128.
698 // It panics if v's Kind is not Complex64 or Complex128
699 func (v Value
) Complex() complex128
{
703 if v
.flag
&flagIndir
!= 0 {
704 return complex128(*(*complex64
)(v
.ptr
))
706 // return complex128(*(*complex64)(unsafe.Pointer(&v.scalar)))
707 panic("reflect: missing flagIndir")
709 // complex128 is always bigger than a word; assume flagIndir.
710 return *(*complex128
)(v
.ptr
)
712 panic(&ValueError
{"reflect.Value.Complex", k
})
715 // Elem returns the value that the interface v contains
716 // or that the pointer v points to.
717 // It panics if v's Kind is not Interface or Ptr.
718 // It returns the zero Value if v is nil.
719 func (v Value
) Elem() Value
{
723 var eface
interface{}
724 if v
.typ
.NumMethod() == 0 {
725 eface
= *(*interface{})(v
.ptr
)
727 eface
= (interface{})(*(*interface {
731 x
:= unpackEface(eface
)
732 x
.flag |
= v
.flag
& flagRO
736 if v
.flag
&flagIndir
!= 0 {
737 ptr
= *(*unsafe
.Pointer
)(ptr
)
739 // The returned value's address is v's value.
743 tt
:= (*ptrType
)(unsafe
.Pointer(v
.typ
))
745 fl
:= v
.flag
&flagRO | flagIndir | flagAddr
746 fl |
= flag(typ
.Kind() << flagKindShift
)
747 return Value
{typ
, ptr
/* 0, */, fl
}
749 panic(&ValueError
{"reflect.Value.Elem", k
})
752 // Field returns the i'th field of the struct v.
753 // It panics if v's Kind is not Struct or i is out of range.
754 func (v Value
) Field(i
int) Value
{
756 tt
:= (*structType
)(unsafe
.Pointer(v
.typ
))
757 if i
< 0 || i
>= len(tt
.fields
) {
758 panic("reflect: Field index out of range")
760 field
:= &tt
.fields
[i
]
763 // Inherit permission bits from v.
764 fl
:= v
.flag
& (flagRO | flagIndir | flagAddr
)
765 // Using an unexported field forces flagRO.
766 if field
.pkgPath
!= nil {
769 fl |
= flag(typ
.Kind()) << flagKindShift
771 var ptr unsafe
.Pointer
772 // var scalar uintptr
774 case fl
&flagIndir
!= 0:
775 // Indirect. Just bump pointer.
776 ptr
= unsafe
.Pointer(uintptr(v
.ptr
) + field
.offset
)
778 if field
.offset
!= 0 {
779 panic("field access of ptr value isn't at offset 0")
783 // Must be scalar. Discard leading bytes.
784 // scalar = v.scalar << (field.offset * 8)
785 panic("reflect: missing flagIndir")
787 // Must be scalar. Discard leading bytes.
788 // scalar = v.scalar >> (field.offset * 8)
789 panic("reflect: missing flagIndir")
792 return Value
{typ
, ptr
/* scalar, */, fl
}
795 // FieldByIndex returns the nested field corresponding to index.
796 // It panics if v's Kind is not struct.
797 func (v Value
) FieldByIndex(index
[]int) Value
{
799 for i
, x
:= range index
{
801 if v
.Kind() == Ptr
&& v
.Elem().Kind() == Struct
{
810 // FieldByName returns the struct field with the given name.
811 // It returns the zero Value if no field was found.
812 // It panics if v's Kind is not struct.
813 func (v Value
) FieldByName(name
string) Value
{
815 if f
, ok
:= v
.typ
.FieldByName(name
); ok
{
816 return v
.FieldByIndex(f
.Index
)
821 // FieldByNameFunc returns the struct field with a name
822 // that satisfies the match function.
823 // It panics if v's Kind is not struct.
824 // It returns the zero Value if no field was found.
825 func (v Value
) FieldByNameFunc(match
func(string) bool) Value
{
827 if f
, ok
:= v
.typ
.FieldByNameFunc(match
); ok
{
828 return v
.FieldByIndex(f
.Index
)
833 // Float returns v's underlying value, as a float64.
834 // It panics if v's Kind is not Float32 or Float64
835 func (v Value
) Float() float64 {
839 if v
.flag
&flagIndir
!= 0 {
840 return float64(*(*float32)(v
.ptr
))
842 // return float64(*(*float32)(unsafe.Pointer(&v.scalar)))
843 panic("reflect: missing flagIndir")
845 if v
.flag
&flagIndir
!= 0 {
846 return *(*float64)(v
.ptr
)
848 // return *(*float64)(unsafe.Pointer(&v.scalar))
849 panic("reflect: missing flagIndir")
851 panic(&ValueError
{"reflect.Value.Float", k
})
854 var uint8Type
= TypeOf(uint8(0)).(*rtype
)
856 // Index returns v's i'th element.
857 // It panics if v's Kind is not Array, Slice, or String or i is out of range.
858 func (v Value
) Index(i
int) Value
{
862 tt
:= (*arrayType
)(unsafe
.Pointer(v
.typ
))
863 if i
< 0 || i
> int(tt
.len) {
864 panic("reflect: array index out of range")
867 fl
:= v
.flag
& (flagRO | flagIndir | flagAddr
) // bits same as overall array
868 fl |
= flag(typ
.Kind()) << flagKindShift
869 offset
:= uintptr(i
) * typ
.size
871 var val unsafe
.Pointer
873 case fl
&flagIndir
!= 0:
874 // Indirect. Just bump pointer.
875 val
= unsafe
.Pointer(uintptr(v
.ptr
) + offset
)
878 panic("can't Index(i) with i!=0 on ptrLike value")
882 // Direct. Discard leading bytes.
883 // scalar = v.scalar << (offset * 8)
884 panic("reflect: missing flagIndir")
886 // Direct. Discard leading bytes.
887 // scalar = v.scalar >> (offset * 8)
888 panic("reflect: missing flagIndir")
890 return Value
{typ
, val
/* scalar, */, fl
}
893 // Element flag same as Elem of Ptr.
894 // Addressable, indirect, possibly read-only.
895 fl
:= flagAddr | flagIndir | v
.flag
&flagRO
896 s
:= (*sliceHeader
)(v
.ptr
)
897 if i
< 0 || i
>= s
.Len
{
898 panic("reflect: slice index out of range")
900 tt
:= (*sliceType
)(unsafe
.Pointer(v
.typ
))
902 fl |
= flag(typ
.Kind()) << flagKindShift
903 val
:= unsafe
.Pointer(uintptr(s
.Data
) + uintptr(i
)*typ
.size
)
904 return Value
{typ
, val
/* 0, */, fl
}
907 fl
:= v
.flag
&flagRO |
flag(Uint8
<<flagKindShift
) | flagIndir
908 s
:= (*StringHeader
)(v
.ptr
)
909 if i
< 0 || i
>= s
.Len
{
910 panic("reflect: string index out of range")
913 *(*byte)(unsafe
.Pointer(&b
)) = *(*byte)(unsafe
.Pointer(uintptr(s
.Data
) + uintptr(i
)))
914 return Value
{uint8Type
, unsafe
.Pointer(&b
) /* 0, */, fl | flagIndir
}
916 panic(&ValueError
{"reflect.Value.Index", k
})
919 // Int returns v's underlying value, as an int64.
920 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64.
921 func (v Value
) Int() int64 {
924 if v
.flag
&flagIndir
!= 0 {
927 // The escape analysis is good enough that &v.scalar
928 // does not trigger a heap allocation.
929 // p = unsafe.Pointer(&v.scalar)
931 case Int
, Int8
, Int16
, Int32
, Int64
:
932 panic("reflect: missing flagIndir")
937 return int64(*(*int)(p
))
939 return int64(*(*int8)(p
))
941 return int64(*(*int16)(p
))
943 return int64(*(*int32)(p
))
945 return int64(*(*int64)(p
))
947 panic(&ValueError
{"reflect.Value.Int", k
})
950 // CanInterface returns true if Interface can be used without panicking.
951 func (v Value
) CanInterface() bool {
953 panic(&ValueError
{"reflect.Value.CanInterface", Invalid
})
955 return v
.flag
&flagRO
== 0
958 // Interface returns v's current value as an interface{}.
959 // It is equivalent to:
960 // var i interface{} = (v's underlying value)
961 // It panics if the Value was obtained by accessing
962 // unexported struct fields.
963 func (v Value
) Interface() (i
interface{}) {
964 return valueInterface(v
, true)
967 func valueInterface(v Value
, safe
bool) interface{} {
969 panic(&ValueError
{"reflect.Value.Interface", 0})
971 if safe
&& v
.flag
&flagRO
!= 0 {
972 // Do not allow access to unexported values via Interface,
973 // because they might be pointers that should not be
974 // writable or methods or function that should not be callable.
975 panic("reflect.Value.Interface: cannot return value obtained from unexported field or method")
977 if v
.flag
&flagMethod
!= 0 {
978 v
= makeMethodValue("Interface", v
)
981 if v
.flag
&flagMethodFn
!= 0 {
982 if v
.typ
.Kind() != Func
{
983 panic("reflect: MethodFn of non-Func")
985 ft
:= (*funcType
)(unsafe
.Pointer(v
.typ
))
986 if ft
.in
[0].Kind() != Ptr
{
987 v
= makeValueMethod(v
)
991 if v
.kind() == Interface
{
992 // Special case: return the element inside the interface.
993 // Empty interface has one layout, all interfaces with
994 // methods have a second layout.
995 if v
.NumMethod() == 0 {
996 return *(*interface{})(v
.ptr
)
998 return *(*interface {
1003 // Non-interface value.
1004 var eface emptyInterface
1005 eface
.typ
= toType(v
.typ
).common()
1006 eface
.word
= v
.iword()
1008 // Don't need to allocate if v is not addressable or fits in one word.
1009 if v
.flag
&flagAddr
!= 0 && v
.kind() != Ptr
&& v
.kind() != UnsafePointer
{
1010 // eface.word is a pointer to the actual data,
1011 // which might be changed. We need to return
1012 // a pointer to unchanging data, so make a copy.
1013 ptr
:= unsafe_New(v
.typ
)
1014 memmove(ptr
, unsafe
.Pointer(eface
.word
), v
.typ
.size
)
1015 eface
.word
= iword(ptr
)
1018 if v
.flag
&flagIndir
== 0 && v
.kind() != Ptr
&& v
.kind() != UnsafePointer
{
1019 panic("missing flagIndir")
1021 // TODO: pass safe to packEface so we don't need to copy if safe==true?
1025 // InterfaceData returns the interface v's value as a uintptr pair.
1026 // It panics if v's Kind is not Interface.
1027 func (v Value
) InterfaceData() [2]uintptr {
1028 // TODO: deprecate this
1030 // We treat this as a read operation, so we allow
1031 // it even for unexported data, because the caller
1032 // has to import "unsafe" to turn it into something
1033 // that can be abused.
1034 // Interface value is always bigger than a word; assume flagIndir.
1035 return *(*[2]uintptr)(v
.ptr
)
1038 // IsNil returns true if v is a nil value.
1039 // It panics if v's Kind is not Chan, Func, Interface, Map, Ptr, or Slice.
1040 func (v Value
) IsNil() bool {
1043 case Chan
, Func
, Map
, Ptr
:
1044 if v
.flag
&flagMethod
!= 0 {
1048 if v
.flag
&flagIndir
!= 0 {
1049 ptr
= *(*unsafe
.Pointer
)(ptr
)
1052 case Interface
, Slice
:
1053 // Both interface and slice are nil if first word is 0.
1054 // Both are always bigger than a word; assume flagIndir.
1055 return *(*unsafe
.Pointer
)(v
.ptr
) == nil
1057 panic(&ValueError
{"reflect.Value.IsNil", k
})
1060 // IsValid returns true if v represents a value.
1061 // It returns false if v is the zero Value.
1062 // If IsValid returns false, all other methods except String panic.
1063 // Most functions and methods never return an invalid value.
1064 // If one does, its documentation states the conditions explicitly.
1065 func (v Value
) IsValid() bool {
1069 // Kind returns v's Kind.
1070 // If v is the zero Value (IsValid returns false), Kind returns Invalid.
1071 func (v Value
) Kind() Kind
{
1075 // Len returns v's length.
1076 // It panics if v's Kind is not Array, Chan, Map, Slice, or String.
1077 func (v Value
) Len() int {
1081 tt
:= (*arrayType
)(unsafe
.Pointer(v
.typ
))
1084 return chanlen(v
.pointer())
1086 return maplen(v
.pointer())
1088 // Slice is bigger than a word; assume flagIndir.
1089 return (*sliceHeader
)(v
.ptr
).Len
1091 // String is bigger than a word; assume flagIndir.
1092 return (*stringHeader
)(v
.ptr
).Len
1094 panic(&ValueError
{"reflect.Value.Len", k
})
1097 // MapIndex returns the value associated with key in the map v.
1098 // It panics if v's Kind is not Map.
1099 // It returns the zero Value if key is not found in the map or if v represents a nil map.
1100 // As in Go, the key's value must be assignable to the map's key type.
1101 func (v Value
) MapIndex(key Value
) Value
{
1103 tt
:= (*mapType
)(unsafe
.Pointer(v
.typ
))
1105 // Do not require key to be exported, so that DeepEqual
1106 // and other programs can use all the keys returned by
1107 // MapKeys as arguments to MapIndex. If either the map
1108 // or the key is unexported, though, the result will be
1109 // considered unexported. This is consistent with the
1110 // behavior for structs, which allow read but not write
1111 // of unexported fields.
1112 key
= key
.assignTo("reflect.Value.MapIndex", tt
.key
, nil)
1114 var k unsafe
.Pointer
1115 if key
.flag
&flagIndir
!= 0 {
1117 } else if key
.typ
.pointers() {
1118 k
= unsafe
.Pointer(&key
.ptr
)
1120 // k = unsafe.Pointer(&key.scalar)
1121 panic("reflect: missing flagIndir")
1123 e
:= mapaccess(v
.typ
, v
.pointer(), k
)
1128 fl
:= (v
.flag | key
.flag
) & flagRO
1129 fl |
= flag(typ
.Kind()) << flagKindShift
1130 if typ
.Kind() != Ptr
&& typ
.Kind() != UnsafePointer
{
1131 // Copy result so future changes to the map
1132 // won't change the underlying value.
1133 c
:= unsafe_New(typ
)
1134 memmove(c
, e
, typ
.size
)
1135 return Value
{typ
, c
/* 0, */, fl | flagIndir
}
1136 } else if typ
.pointers() {
1137 return Value
{typ
, *(*unsafe
.Pointer
)(e
) /* 0, */, fl
}
1139 panic("reflect: can't happen")
1143 // MapKeys returns a slice containing all the keys present in the map,
1144 // in unspecified order.
1145 // It panics if v's Kind is not Map.
1146 // It returns an empty slice if v represents a nil map.
1147 func (v Value
) MapKeys() []Value
{
1149 tt
:= (*mapType
)(unsafe
.Pointer(v
.typ
))
1152 fl
:= v
.flag
&flagRO |
flag(keyType
.Kind())<<flagKindShift
1153 if keyType
.Kind() != Ptr
&& keyType
.Kind() != UnsafePointer
{
1162 it
:= mapiterinit(v
.typ
, m
)
1163 a
:= make([]Value
, mlen
)
1165 for i
= 0; i
< len(a
); i
++ {
1166 key
:= mapiterkey(it
)
1168 // Someone deleted an entry from the map since we
1169 // called maplen above. It's a data race, but nothing
1170 // we can do about it.
1173 if keyType
.Kind() != Ptr
&& keyType
.Kind() != UnsafePointer
{
1174 // Copy result so future changes to the map
1175 // won't change the underlying value.
1176 c
:= unsafe_New(keyType
)
1177 memmove(c
, key
, keyType
.size
)
1178 a
[i
] = Value
{keyType
, c
/* 0, */, fl | flagIndir
}
1179 } else if keyType
.pointers() {
1180 a
[i
] = Value
{keyType
, *(*unsafe
.Pointer
)(key
) /* 0, */, fl
}
1182 panic("reflect: can't happen")
1189 // Method returns a function value corresponding to v's i'th method.
1190 // The arguments to a Call on the returned function should not include
1191 // a receiver; the returned function will always use v as the receiver.
1192 // Method panics if i is out of range or if v is a nil interface value.
1193 func (v Value
) Method(i
int) Value
{
1195 panic(&ValueError
{"reflect.Value.Method", Invalid
})
1197 if v
.flag
&flagMethod
!= 0 || i
< 0 || i
>= v
.typ
.NumMethod() {
1198 panic("reflect: Method index out of range")
1200 if v
.typ
.Kind() == Interface
&& v
.IsNil() {
1201 panic("reflect: Method on nil interface value")
1203 fl
:= v
.flag
& (flagRO | flagIndir
)
1204 fl |
= flag(Func
) << flagKindShift
1205 fl |
= flag(i
)<<flagMethodShift | flagMethod
1206 return Value
{v
.typ
, v
.ptr
/* v.scalar, */, fl
}
1209 // NumMethod returns the number of methods in the value's method set.
1210 func (v Value
) NumMethod() int {
1212 panic(&ValueError
{"reflect.Value.NumMethod", Invalid
})
1214 if v
.flag
&flagMethod
!= 0 {
1217 return v
.typ
.NumMethod()
1220 // MethodByName returns a function value corresponding to the method
1221 // of v with the given name.
1222 // The arguments to a Call on the returned function should not include
1223 // a receiver; the returned function will always use v as the receiver.
1224 // It returns the zero Value if no method was found.
1225 func (v Value
) MethodByName(name
string) Value
{
1227 panic(&ValueError
{"reflect.Value.MethodByName", Invalid
})
1229 if v
.flag
&flagMethod
!= 0 {
1232 m
, ok
:= v
.typ
.MethodByName(name
)
1236 return v
.Method(m
.Index
)
1239 // NumField returns the number of fields in the struct v.
1240 // It panics if v's Kind is not Struct.
1241 func (v Value
) NumField() int {
1243 tt
:= (*structType
)(unsafe
.Pointer(v
.typ
))
1244 return len(tt
.fields
)
1247 // OverflowComplex returns true if the complex128 x cannot be represented by v's type.
1248 // It panics if v's Kind is not Complex64 or Complex128.
1249 func (v Value
) OverflowComplex(x complex128
) bool {
1253 return overflowFloat32(real(x
)) ||
overflowFloat32(imag(x
))
1257 panic(&ValueError
{"reflect.Value.OverflowComplex", k
})
1260 // OverflowFloat returns true if the float64 x cannot be represented by v's type.
1261 // It panics if v's Kind is not Float32 or Float64.
1262 func (v Value
) OverflowFloat(x
float64) bool {
1266 return overflowFloat32(x
)
1270 panic(&ValueError
{"reflect.Value.OverflowFloat", k
})
1273 func overflowFloat32(x
float64) bool {
1277 return math
.MaxFloat32
< x
&& x
<= math
.MaxFloat64
1280 // OverflowInt returns true if the int64 x cannot be represented by v's type.
1281 // It panics if v's Kind is not Int, Int8, int16, Int32, or Int64.
1282 func (v Value
) OverflowInt(x
int64) bool {
1285 case Int
, Int8
, Int16
, Int32
, Int64
:
1286 bitSize
:= v
.typ
.size
* 8
1287 trunc
:= (x
<< (64 - bitSize
)) >> (64 - bitSize
)
1290 panic(&ValueError
{"reflect.Value.OverflowInt", k
})
1293 // OverflowUint returns true if the uint64 x cannot be represented by v's type.
1294 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1295 func (v Value
) OverflowUint(x
uint64) bool {
1298 case Uint
, Uintptr
, Uint8
, Uint16
, Uint32
, Uint64
:
1299 bitSize
:= v
.typ
.size
* 8
1300 trunc
:= (x
<< (64 - bitSize
)) >> (64 - bitSize
)
1303 panic(&ValueError
{"reflect.Value.OverflowUint", k
})
1306 // Pointer returns v's value as a uintptr.
1307 // It returns uintptr instead of unsafe.Pointer so that
1308 // code using reflect cannot obtain unsafe.Pointers
1309 // without importing the unsafe package explicitly.
1310 // It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer.
1312 // If v's Kind is Func, the returned pointer is an underlying
1313 // code pointer, but not necessarily enough to identify a
1314 // single function uniquely. The only guarantee is that the
1315 // result is zero if and only if v is a nil func Value.
1317 // If v's Kind is Slice, the returned pointer is to the first
1318 // element of the slice. If the slice is nil the returned value
1319 // is 0. If the slice is empty but non-nil the return value is non-zero.
1320 func (v Value
) Pointer() uintptr {
1324 case Chan
, Map
, Ptr
, UnsafePointer
:
1325 return uintptr(v
.pointer())
1327 if v
.flag
&flagMethod
!= 0 {
1328 // As the doc comment says, the returned pointer is an
1329 // underlying code pointer but not necessarily enough to
1330 // identify a single function uniquely. All method expressions
1331 // created via reflect have the same underlying code pointer,
1332 // so their Pointers are equal. The function used here must
1333 // match the one used in makeMethodValue.
1335 return **(**uintptr)(unsafe
.Pointer(&f
))
1338 // Non-nil func value points at data block.
1339 // First word of data block is actual code.
1341 p
= *(*unsafe
.Pointer
)(p
)
1346 return (*SliceHeader
)(v
.ptr
).Data
1348 panic(&ValueError
{"reflect.Value.Pointer", k
})
1351 // Recv receives and returns a value from the channel v.
1352 // It panics if v's Kind is not Chan.
1353 // The receive blocks until a value is ready.
1354 // The boolean value ok is true if the value x corresponds to a send
1355 // on the channel, false if it is a zero value received because the channel is closed.
1356 func (v Value
) Recv() (x Value
, ok
bool) {
1359 return v
.recv(false)
1362 // internal recv, possibly non-blocking (nb).
1363 // v is known to be a channel.
1364 func (v Value
) recv(nb
bool) (val Value
, ok
bool) {
1365 tt
:= (*chanType
)(unsafe
.Pointer(v
.typ
))
1366 if ChanDir(tt
.dir
)&RecvDir
== 0 {
1367 panic("reflect: recv on send-only channel")
1369 word
, selected
, ok
:= chanrecv(v
.typ
, v
.pointer(), nb
)
1371 val
= fromIword(tt
.elem
, word
, 0)
1376 // Send sends x on the channel v.
1377 // It panics if v's kind is not Chan or if x's type is not the same type as v's element type.
1378 // As in Go, x's value must be assignable to the channel's element type.
1379 func (v Value
) Send(x Value
) {
1385 // internal send, possibly non-blocking.
1386 // v is known to be a channel.
1387 func (v Value
) send(x Value
, nb
bool) (selected
bool) {
1388 tt
:= (*chanType
)(unsafe
.Pointer(v
.typ
))
1389 if ChanDir(tt
.dir
)&SendDir
== 0 {
1390 panic("reflect: send on recv-only channel")
1393 x
= x
.assignTo("reflect.Value.Send", tt
.elem
, nil)
1394 return chansend(v
.typ
, v
.pointer(), x
.iword(), nb
)
1397 // Set assigns x to the value v.
1398 // It panics if CanSet returns false.
1399 // As in Go, x's value must be assignable to v's type.
1400 func (v Value
) Set(x Value
) {
1401 v
.mustBeAssignable()
1402 x
.mustBeExported() // do not let unexported x leak
1403 var target
*interface{}
1404 if v
.kind() == Interface
{
1405 target
= (*interface{})(v
.ptr
)
1407 x
= x
.assignTo("reflect.Set", v
.typ
, target
)
1408 if x
.flag
&flagIndir
!= 0 {
1409 memmove(v
.ptr
, x
.ptr
, v
.typ
.size
)
1410 } else if x
.typ
.pointers() {
1411 *(*unsafe
.Pointer
)(v
.ptr
) = x
.ptr
1413 // memmove(v.ptr, unsafe.Pointer(&x.scalar), v.typ.size)
1414 panic("reflect: missing flagIndir")
1418 // SetBool sets v's underlying value.
1419 // It panics if v's Kind is not Bool or if CanSet() is false.
1420 func (v Value
) SetBool(x
bool) {
1421 v
.mustBeAssignable()
1426 // SetBytes sets v's underlying value.
1427 // It panics if v's underlying value is not a slice of bytes.
1428 func (v Value
) SetBytes(x
[]byte) {
1429 v
.mustBeAssignable()
1431 if v
.typ
.Elem().Kind() != Uint8
{
1432 panic("reflect.Value.SetBytes of non-byte slice")
1434 *(*[]byte)(v
.ptr
) = x
1437 // setRunes sets v's underlying value.
1438 // It panics if v's underlying value is not a slice of runes (int32s).
1439 func (v Value
) setRunes(x
[]rune
) {
1440 v
.mustBeAssignable()
1442 if v
.typ
.Elem().Kind() != Int32
{
1443 panic("reflect.Value.setRunes of non-rune slice")
1445 *(*[]rune
)(v
.ptr
) = x
1448 // SetComplex sets v's underlying value to x.
1449 // It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false.
1450 func (v Value
) SetComplex(x complex128
) {
1451 v
.mustBeAssignable()
1452 switch k
:= v
.kind(); k
{
1454 panic(&ValueError
{"reflect.Value.SetComplex", k
})
1456 *(*complex64
)(v
.ptr
) = complex64(x
)
1458 *(*complex128
)(v
.ptr
) = x
1462 // SetFloat sets v's underlying value to x.
1463 // It panics if v's Kind is not Float32 or Float64, or if CanSet() is false.
1464 func (v Value
) SetFloat(x
float64) {
1465 v
.mustBeAssignable()
1466 switch k
:= v
.kind(); k
{
1468 panic(&ValueError
{"reflect.Value.SetFloat", k
})
1470 *(*float32)(v
.ptr
) = float32(x
)
1472 *(*float64)(v
.ptr
) = x
1476 // SetInt sets v's underlying value to x.
1477 // It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false.
1478 func (v Value
) SetInt(x
int64) {
1479 v
.mustBeAssignable()
1480 switch k
:= v
.kind(); k
{
1482 panic(&ValueError
{"reflect.Value.SetInt", k
})
1484 *(*int)(v
.ptr
) = int(x
)
1486 *(*int8)(v
.ptr
) = int8(x
)
1488 *(*int16)(v
.ptr
) = int16(x
)
1490 *(*int32)(v
.ptr
) = int32(x
)
1492 *(*int64)(v
.ptr
) = x
1496 // SetLen sets v's length to n.
1497 // It panics if v's Kind is not Slice or if n is negative or
1498 // greater than the capacity of the slice.
1499 func (v Value
) SetLen(n
int) {
1500 v
.mustBeAssignable()
1502 s
:= (*sliceHeader
)(v
.ptr
)
1503 if n
< 0 || n
> int(s
.Cap
) {
1504 panic("reflect: slice length out of range in SetLen")
1509 // SetCap sets v's capacity to n.
1510 // It panics if v's Kind is not Slice or if n is smaller than the length or
1511 // greater than the capacity of the slice.
1512 func (v Value
) SetCap(n
int) {
1513 v
.mustBeAssignable()
1515 s
:= (*sliceHeader
)(v
.ptr
)
1516 if n
< int(s
.Len
) || n
> int(s
.Cap
) {
1517 panic("reflect: slice capacity out of range in SetCap")
1522 // SetMapIndex sets the value associated with key in the map v to val.
1523 // It panics if v's Kind is not Map.
1524 // If val is the zero Value, SetMapIndex deletes the key from the map.
1525 // As in Go, key's value must be assignable to the map's key type,
1526 // and val's value must be assignable to the map's value type.
1527 func (v Value
) SetMapIndex(key
, val Value
) {
1530 key
.mustBeExported()
1531 tt
:= (*mapType
)(unsafe
.Pointer(v
.typ
))
1532 key
= key
.assignTo("reflect.Value.SetMapIndex", tt
.key
, nil)
1533 var k unsafe
.Pointer
1534 if key
.flag
&flagIndir
!= 0 {
1536 } else if key
.typ
.pointers() {
1537 k
= unsafe
.Pointer(&key
.ptr
)
1539 // k = unsafe.Pointer(&key.scalar)
1540 panic("reflect: missing flagIndir")
1543 mapdelete(v
.typ
, v
.pointer(), k
)
1546 val
.mustBeExported()
1547 val
= val
.assignTo("reflect.Value.SetMapIndex", tt
.elem
, nil)
1548 var e unsafe
.Pointer
1549 if val
.flag
&flagIndir
!= 0 {
1551 } else if val
.typ
.pointers() {
1552 e
= unsafe
.Pointer(&val
.ptr
)
1554 // e = unsafe.Pointer(&val.scalar)
1555 panic("reflect: missing flagIndir")
1557 mapassign(v
.typ
, v
.pointer(), k
, e
)
1560 // SetUint sets v's underlying value to x.
1561 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false.
1562 func (v Value
) SetUint(x
uint64) {
1563 v
.mustBeAssignable()
1564 switch k
:= v
.kind(); k
{
1566 panic(&ValueError
{"reflect.Value.SetUint", k
})
1568 *(*uint)(v
.ptr
) = uint(x
)
1570 *(*uint8)(v
.ptr
) = uint8(x
)
1572 *(*uint16)(v
.ptr
) = uint16(x
)
1574 *(*uint32)(v
.ptr
) = uint32(x
)
1576 *(*uint64)(v
.ptr
) = x
1578 *(*uintptr)(v
.ptr
) = uintptr(x
)
1582 // SetPointer sets the unsafe.Pointer value v to x.
1583 // It panics if v's Kind is not UnsafePointer.
1584 func (v Value
) SetPointer(x unsafe
.Pointer
) {
1585 v
.mustBeAssignable()
1586 v
.mustBe(UnsafePointer
)
1587 *(*unsafe
.Pointer
)(v
.ptr
) = x
1590 // SetString sets v's underlying value to x.
1591 // It panics if v's Kind is not String or if CanSet() is false.
1592 func (v Value
) SetString(x
string) {
1593 v
.mustBeAssignable()
1595 *(*string)(v
.ptr
) = x
1598 // Slice returns v[i:j].
1599 // It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array,
1600 // or if the indexes are out of bounds.
1601 func (v Value
) Slice(i
, j
int) Value
{
1607 switch kind
:= v
.kind(); kind
{
1609 panic(&ValueError
{"reflect.Value.Slice", kind
})
1612 if v
.flag
&flagAddr
== 0 {
1613 panic("reflect.Value.Slice: slice of unaddressable array")
1615 tt
:= (*arrayType
)(unsafe
.Pointer(v
.typ
))
1617 typ
= (*sliceType
)(unsafe
.Pointer(tt
.slice
))
1621 typ
= (*sliceType
)(unsafe
.Pointer(v
.typ
))
1622 s
:= (*sliceHeader
)(v
.ptr
)
1623 base
= unsafe
.Pointer(s
.Data
)
1627 s
:= (*stringHeader
)(v
.ptr
)
1628 if i
< 0 || j
< i || j
> s
.Len
{
1629 panic("reflect.Value.Slice: string slice index out of bounds")
1631 t
:= stringHeader
{unsafe
.Pointer(uintptr(s
.Data
) + uintptr(i
)), j
- i
}
1632 return Value
{v
.typ
, unsafe
.Pointer(&t
) /* 0, */, v
.flag
}
1635 if i
< 0 || j
< i || j
> cap {
1636 panic("reflect.Value.Slice: slice index out of bounds")
1639 // Declare slice so that gc can see the base pointer in it.
1640 var x
[]unsafe
.Pointer
1642 // Reinterpret as *sliceHeader to edit.
1643 s
:= (*sliceHeader
)(unsafe
.Pointer(&x
))
1644 s
.Data
= unsafe
.Pointer(uintptr(base
) + uintptr(i
)*typ
.elem
.Size())
1648 fl
:= v
.flag
&flagRO | flagIndir |
flag(Slice
)<<flagKindShift
1649 return Value
{typ
.common(), unsafe
.Pointer(&x
) /* 0, */, fl
}
1652 // Slice3 is the 3-index form of the slice operation: it returns v[i:j:k].
1653 // It panics if v's Kind is not Array or Slice, or if v is an unaddressable array,
1654 // or if the indexes are out of bounds.
1655 func (v Value
) Slice3(i
, j
, k
int) Value
{
1661 switch kind
:= v
.kind(); kind
{
1663 panic(&ValueError
{"reflect.Value.Slice3", kind
})
1666 if v
.flag
&flagAddr
== 0 {
1667 panic("reflect.Value.Slice3: slice of unaddressable array")
1669 tt
:= (*arrayType
)(unsafe
.Pointer(v
.typ
))
1671 typ
= (*sliceType
)(unsafe
.Pointer(tt
.slice
))
1675 typ
= (*sliceType
)(unsafe
.Pointer(v
.typ
))
1676 s
:= (*sliceHeader
)(v
.ptr
)
1681 if i
< 0 || j
< i || k
< j || k
> cap {
1682 panic("reflect.Value.Slice3: slice index out of bounds")
1685 // Declare slice so that the garbage collector
1686 // can see the base pointer in it.
1687 var x
[]unsafe
.Pointer
1689 // Reinterpret as *sliceHeader to edit.
1690 s
:= (*sliceHeader
)(unsafe
.Pointer(&x
))
1691 s
.Data
= unsafe
.Pointer(uintptr(base
) + uintptr(i
)*typ
.elem
.Size())
1695 fl
:= v
.flag
&flagRO | flagIndir |
flag(Slice
)<<flagKindShift
1696 return Value
{typ
.common(), unsafe
.Pointer(&x
) /* 0, */, fl
}
1699 // String returns the string v's underlying value, as a string.
1700 // String is a special case because of Go's String method convention.
1701 // Unlike the other getters, it does not panic if v's Kind is not String.
1702 // Instead, it returns a string of the form "<T value>" where T is v's type.
1703 func (v Value
) String() string {
1704 switch k
:= v
.kind(); k
{
1706 return "<invalid Value>"
1708 return *(*string)(v
.ptr
)
1710 // If you call String on a reflect.Value of other type, it's better to
1711 // print something than to panic. Useful in debugging.
1712 return "<" + v
.typ
.String() + " Value>"
1715 // TryRecv attempts to receive a value from the channel v but will not block.
1716 // It panics if v's Kind is not Chan.
1717 // If the receive cannot finish without blocking, x is the zero Value.
1718 // The boolean ok is true if the value x corresponds to a send
1719 // on the channel, false if it is a zero value received because the channel is closed.
1720 func (v Value
) TryRecv() (x Value
, ok
bool) {
1726 // TrySend attempts to send x on the channel v but will not block.
1727 // It panics if v's Kind is not Chan.
1728 // It returns true if the value was sent, false otherwise.
1729 // As in Go, x's value must be assignable to the channel's element type.
1730 func (v Value
) TrySend(x Value
) bool {
1733 return v
.send(x
, true)
1736 // Type returns v's type.
1737 func (v Value
) Type() Type
{
1740 panic(&ValueError
{"reflect.Value.Type", Invalid
})
1742 if f
&flagMethod
== 0 {
1744 return toType(v
.typ
)
1748 // v.typ describes the receiver, not the method type.
1749 i
:= int(v
.flag
) >> flagMethodShift
1750 if v
.typ
.Kind() == Interface
{
1751 // Method on interface.
1752 tt
:= (*interfaceType
)(unsafe
.Pointer(v
.typ
))
1753 if i
< 0 || i
>= len(tt
.methods
) {
1754 panic("reflect: internal error: invalid method index")
1757 return toType(m
.typ
)
1759 // Method on concrete type.
1760 ut
:= v
.typ
.uncommon()
1761 if ut
== nil || i
< 0 || i
>= len(ut
.methods
) {
1762 panic("reflect: internal error: invalid method index")
1765 return toType(m
.mtyp
)
1768 // Uint returns v's underlying value, as a uint64.
1769 // It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64.
1770 func (v Value
) Uint() uint64 {
1772 var p unsafe
.Pointer
1773 if v
.flag
&flagIndir
!= 0 {
1776 // The escape analysis is good enough that &v.scalar
1777 // does not trigger a heap allocation.
1778 // p = unsafe.Pointer(&v.scalar)
1780 case Uint
, Uint8
, Uint16
, Uint32
, Uint64
, Uintptr
:
1781 panic("reflect: missing flagIndir")
1786 return uint64(*(*uint)(p
))
1788 return uint64(*(*uint8)(p
))
1790 return uint64(*(*uint16)(p
))
1792 return uint64(*(*uint32)(p
))
1794 return uint64(*(*uint64)(p
))
1796 return uint64(*(*uintptr)(p
))
1798 panic(&ValueError
{"reflect.Value.Uint", k
})
1801 // UnsafeAddr returns a pointer to v's data.
1802 // It is for advanced clients that also import the "unsafe" package.
1803 // It panics if v is not addressable.
1804 func (v Value
) UnsafeAddr() uintptr {
1807 panic(&ValueError
{"reflect.Value.UnsafeAddr", Invalid
})
1809 if v
.flag
&flagAddr
== 0 {
1810 panic("reflect.Value.UnsafeAddr of unaddressable value")
1812 return uintptr(v
.ptr
)
1815 // StringHeader is the runtime representation of a string.
1816 // It cannot be used safely or portably and its representation may
1817 // change in a later release.
1818 // Moreover, the Data field is not sufficient to guarantee the data
1819 // it references will not be garbage collected, so programs must keep
1820 // a separate, correctly typed pointer to the underlying data.
1821 type StringHeader
struct {
1826 // stringHeader is a safe version of StringHeader used within this package.
1827 type stringHeader
struct {
1832 // SliceHeader is the runtime representation of a slice.
1833 // It cannot be used safely or portably and its representation may
1834 // change in a later release.
1835 // Moreover, the Data field is not sufficient to guarantee the data
1836 // it references will not be garbage collected, so programs must keep
1837 // a separate, correctly typed pointer to the underlying data.
1838 type SliceHeader
struct {
1844 // sliceHeader is a safe version of SliceHeader used within this package.
1845 type sliceHeader
struct {
1851 func typesMustMatch(what
string, t1
, t2 Type
) {
1853 panic(what
+ ": " + t1
.String() + " != " + t2
.String())
1857 // grow grows the slice s so that it can hold extra more values, allocating
1858 // more capacity if needed. It also returns the old and new slice lengths.
1859 func grow(s Value
, extra
int) (Value
, int, int) {
1863 panic("reflect.Append: slice overflow")
1867 return s
.Slice(0, i1
), i0
, i1
1880 t
:= MakeSlice(s
.Type(), i1
, m
)
1885 // Append appends the values x to a slice s and returns the resulting slice.
1886 // As in Go, each x's value must be assignable to the slice's element type.
1887 func Append(s Value
, x
...Value
) Value
{
1889 s
, i0
, i1
:= grow(s
, len(x
))
1890 for i
, j
:= i0
, 0; i
< i1
; i
, j
= i
+1, j
+1 {
1891 s
.Index(i
).Set(x
[j
])
1896 // AppendSlice appends a slice t to a slice s and returns the resulting slice.
1897 // The slices s and t must have the same element type.
1898 func AppendSlice(s
, t Value
) Value
{
1901 typesMustMatch("reflect.AppendSlice", s
.Type().Elem(), t
.Type().Elem())
1902 s
, i0
, i1
:= grow(s
, t
.Len())
1903 Copy(s
.Slice(i0
, i1
), t
)
1907 // Copy copies the contents of src into dst until either
1908 // dst has been filled or src has been exhausted.
1909 // It returns the number of elements copied.
1910 // Dst and src each must have kind Slice or Array, and
1911 // dst and src must have the same element type.
1912 func Copy(dst
, src Value
) int {
1914 if dk
!= Array
&& dk
!= Slice
{
1915 panic(&ValueError
{"reflect.Copy", dk
})
1918 dst
.mustBeAssignable()
1920 dst
.mustBeExported()
1923 if sk
!= Array
&& sk
!= Slice
{
1924 panic(&ValueError
{"reflect.Copy", sk
})
1926 src
.mustBeExported()
1928 de
:= dst
.typ
.Elem()
1929 se
:= src
.typ
.Elem()
1930 typesMustMatch("reflect.Copy", de
, se
)
1933 if sn
:= src
.Len(); n
> sn
{
1937 // If sk is an in-line array, cannot take its address.
1938 // Instead, copy element by element.
1939 // TODO: memmove would be ok for this (sa = unsafe.Pointer(&v.scalar))
1940 // if we teach the compiler that ptrs don't escape from memmove.
1941 if src
.flag
&flagIndir
== 0 {
1942 for i
:= 0; i
< n
; i
++ {
1943 dst
.Index(i
).Set(src
.Index(i
))
1948 // Copy via memmove.
1949 var da
, sa unsafe
.Pointer
1953 da
= (*sliceHeader
)(dst
.ptr
).Data
1958 sa
= (*sliceHeader
)(src
.ptr
).Data
1960 memmove(da
, sa
, uintptr(n
)*de
.Size())
1964 // A runtimeSelect is a single case passed to rselect.
1965 // This must match ../runtime/chan.c:/runtimeSelect
1966 type runtimeSelect
struct {
1967 dir
uintptr // 0, SendDir, or RecvDir
1968 typ
*rtype
// channel type
1969 ch iword
// interface word for channel
1970 val iword
// interface word for value (for SendDir)
1973 // rselect runs a select. It returns the index of the chosen case,
1974 // and if the case was a receive, the interface word of the received
1975 // value and the conventional OK bool to indicate whether the receive
1976 // corresponds to a sent value.
1977 func rselect([]runtimeSelect
) (chosen
int, recv iword
, recvOK
bool)
1979 // A SelectDir describes the communication direction of a select case.
1982 // NOTE: These values must match ../runtime/chan.c:/SelectDir.
1986 SelectSend
// case Chan <- Send
1987 SelectRecv
// case <-Chan:
1988 SelectDefault
// default
1991 // A SelectCase describes a single case in a select operation.
1992 // The kind of case depends on Dir, the communication direction.
1994 // If Dir is SelectDefault, the case represents a default case.
1995 // Chan and Send must be zero Values.
1997 // If Dir is SelectSend, the case represents a send operation.
1998 // Normally Chan's underlying value must be a channel, and Send's underlying value must be
1999 // assignable to the channel's element type. As a special case, if Chan is a zero Value,
2000 // then the case is ignored, and the field Send will also be ignored and may be either zero
2003 // If Dir is SelectRecv, the case represents a receive operation.
2004 // Normally Chan's underlying value must be a channel and Send must be a zero Value.
2005 // If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value.
2006 // When a receive operation is selected, the received Value is returned by Select.
2008 type SelectCase
struct {
2009 Dir SelectDir
// direction of case
2010 Chan Value
// channel to use (for send or receive)
2011 Send Value
// value to send (for send)
2014 // Select executes a select operation described by the list of cases.
2015 // Like the Go select statement, it blocks until at least one of the cases
2016 // can proceed, makes a uniform pseudo-random choice,
2017 // and then executes that case. It returns the index of the chosen case
2018 // and, if that case was a receive operation, the value received and a
2019 // boolean indicating whether the value corresponds to a send on the channel
2020 // (as opposed to a zero value received because the channel is closed).
2021 func Select(cases
[]SelectCase
) (chosen
int, recv Value
, recvOK
bool) {
2022 // NOTE: Do not trust that caller is not modifying cases data underfoot.
2023 // The range is safe because the caller cannot modify our copy of the len
2024 // and each iteration makes its own copy of the value c.
2025 runcases
:= make([]runtimeSelect
, len(cases
))
2026 haveDefault
:= false
2027 for i
, c
:= range cases
{
2029 rc
.dir
= uintptr(c
.Dir
)
2032 panic("reflect.Select: invalid Dir")
2034 case SelectDefault
: // default
2036 panic("reflect.Select: multiple default cases")
2039 if c
.Chan
.IsValid() {
2040 panic("reflect.Select: default case has Chan value")
2042 if c
.Send
.IsValid() {
2043 panic("reflect.Select: default case has Send value")
2053 tt
:= (*chanType
)(unsafe
.Pointer(ch
.typ
))
2054 if ChanDir(tt
.dir
)&SendDir
== 0 {
2055 panic("reflect.Select: SendDir case using recv-only channel")
2057 rc
.ch
= *(*iword
)(ch
.iword())
2061 panic("reflect.Select: SendDir case missing Send value")
2064 v
= v
.assignTo("reflect.Select", tt
.elem
, nil)
2068 if c
.Send
.IsValid() {
2069 panic("reflect.Select: RecvDir case has Send value")
2077 tt
:= (*chanType
)(unsafe
.Pointer(ch
.typ
))
2079 if ChanDir(tt
.dir
)&RecvDir
== 0 {
2080 panic("reflect.Select: RecvDir case using send-only channel")
2082 rc
.ch
= *(*iword
)(ch
.iword())
2086 chosen
, word
, recvOK
:= rselect(runcases
)
2087 if runcases
[chosen
].dir
== uintptr(SelectRecv
) {
2088 tt
:= (*chanType
)(unsafe
.Pointer(runcases
[chosen
].typ
))
2089 recv
= fromIword(tt
.elem
, word
, 0)
2091 return chosen
, recv
, recvOK
2098 // implemented in package runtime
2099 func unsafe_New(*rtype
) unsafe
.Pointer
2100 func unsafe_NewArray(*rtype
, int) unsafe
.Pointer
2102 // MakeSlice creates a new zero-initialized slice value
2103 // for the specified slice type, length, and capacity.
2104 func MakeSlice(typ Type
, len, cap int) Value
{
2105 if typ
.Kind() != Slice
{
2106 panic("reflect.MakeSlice of non-slice type")
2109 panic("reflect.MakeSlice: negative len")
2112 panic("reflect.MakeSlice: negative cap")
2115 panic("reflect.MakeSlice: len > cap")
2118 s
:= sliceHeader
{unsafe_NewArray(typ
.Elem().(*rtype
), cap), len, cap}
2119 return Value
{typ
.common(), unsafe
.Pointer(&s
) /* 0, */, flagIndir |
flag(Slice
)<<flagKindShift
}
2122 // MakeChan creates a new channel with the specified type and buffer size.
2123 func MakeChan(typ Type
, buffer
int) Value
{
2124 if typ
.Kind() != Chan
{
2125 panic("reflect.MakeChan of non-chan type")
2128 panic("reflect.MakeChan: negative buffer size")
2130 if typ
.ChanDir() != BothDir
{
2131 panic("reflect.MakeChan: unidirectional channel type")
2133 ch
:= makechan(typ
.(*rtype
), uint64(buffer
))
2134 return Value
{typ
.common(), unsafe
.Pointer(&ch
) /* 0, */, flagIndir |
(flag(Chan
) << flagKindShift
)}
2137 // MakeMap creates a new map of the specified type.
2138 func MakeMap(typ Type
) Value
{
2139 if typ
.Kind() != Map
{
2140 panic("reflect.MakeMap of non-map type")
2142 m
:= makemap(typ
.(*rtype
))
2143 return Value
{typ
.common(), unsafe
.Pointer(&m
) /* 0, */, flagIndir |
(flag(Map
) << flagKindShift
)}
2146 // Indirect returns the value that v points to.
2147 // If v is a nil pointer, Indirect returns a zero Value.
2148 // If v is not a pointer, Indirect returns v.
2149 func Indirect(v Value
) Value
{
2150 if v
.Kind() != Ptr
{
2156 // ValueOf returns a new Value initialized to the concrete value
2157 // stored in the interface i. ValueOf(nil) returns the zero Value.
2158 func ValueOf(i
interface{}) Value
{
2163 // TODO(rsc): Eliminate this terrible hack.
2164 // In the call to unpackEface, i.typ doesn't escape,
2165 // and i.word is an integer. So it looks like
2166 // i doesn't escape. But really it does,
2167 // because i.word is actually a pointer.
2170 return unpackEface(i
)
2173 // Zero returns a Value representing the zero value for the specified type.
2174 // The result is different from the zero value of the Value struct,
2175 // which represents no value at all.
2176 // For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0.
2177 // The returned value is neither addressable nor settable.
2178 func Zero(typ Type
) Value
{
2180 panic("reflect: Zero(nil)")
2183 fl
:= flag(t
.Kind()) << flagKindShift
2184 if t
.Kind() == Ptr || t
.Kind() == UnsafePointer
{
2185 return Value
{t
, nil /* 0, */, fl
}
2187 return Value
{t
, unsafe_New(typ
.(*rtype
)) /* 0, */, fl | flagIndir
}
2190 // New returns a Value representing a pointer to a new zero value
2191 // for the specified type. That is, the returned Value's Type is PtrTo(t).
2192 func New(typ Type
) Value
{
2194 panic("reflect: New(nil)")
2196 ptr
:= unsafe_New(typ
.(*rtype
))
2197 fl
:= flag(Ptr
) << flagKindShift
2198 return Value
{typ
.common().ptrTo(), ptr
/* 0, */, fl
}
2201 // NewAt returns a Value representing a pointer to a value of the
2202 // specified type, using p as that pointer.
2203 func NewAt(typ Type
, p unsafe
.Pointer
) Value
{
2204 fl
:= flag(Ptr
) << flagKindShift
2205 return Value
{typ
.common().ptrTo(), p
/* 0, */, fl
}
2208 // assignTo returns a value v that can be assigned directly to typ.
2209 // It panics if v is not assignable to typ.
2210 // For a conversion to an interface type, target is a suggested scratch space to use.
2211 func (v Value
) assignTo(context
string, dst
*rtype
, target
*interface{}) Value
{
2212 if v
.flag
&flagMethod
!= 0 {
2213 v
= makeMethodValue(context
, v
)
2217 case directlyAssignable(dst
, v
.typ
):
2218 // Overwrite type so that they match.
2219 // Same memory layout, so no harm done.
2221 fl
:= v
.flag
& (flagRO | flagAddr | flagIndir
)
2222 fl |
= flag(dst
.Kind()) << flagKindShift
2223 return Value
{dst
, v
.ptr
/* v.scalar, */, fl
}
2225 case implements(dst
, v
.typ
):
2227 target
= new(interface{})
2229 x
:= valueInterface(v
, false)
2230 if dst
.NumMethod() == 0 {
2233 ifaceE2I(dst
, x
, unsafe
.Pointer(target
))
2235 return Value
{dst
, unsafe
.Pointer(target
) /* 0, */, flagIndir |
flag(Interface
)<<flagKindShift
}
2239 panic(context
+ ": value of type " + v
.typ
.String() + " is not assignable to type " + dst
.String())
2242 // Convert returns the value v converted to type t.
2243 // If the usual Go conversion rules do not allow conversion
2244 // of the value v to type t, Convert panics.
2245 func (v Value
) Convert(t Type
) Value
{
2246 if v
.flag
&flagMethod
!= 0 {
2247 v
= makeMethodValue("Convert", v
)
2249 op
:= convertOp(t
.common(), v
.typ
)
2251 panic("reflect.Value.Convert: value of type " + v
.typ
.String() + " cannot be converted to type " + t
.String())
2256 // convertOp returns the function to convert a value of type src
2257 // to a value of type dst. If the conversion is illegal, convertOp returns nil.
2258 func convertOp(dst
, src
*rtype
) func(Value
, Type
) Value
{
2260 case Int
, Int8
, Int16
, Int32
, Int64
:
2262 case Int
, Int8
, Int16
, Int32
, Int64
, Uint
, Uint8
, Uint16
, Uint32
, Uint64
, Uintptr
:
2264 case Float32
, Float64
:
2270 case Uint
, Uint8
, Uint16
, Uint32
, Uint64
, Uintptr
:
2272 case Int
, Int8
, Int16
, Int32
, Int64
, Uint
, Uint8
, Uint16
, Uint32
, Uint64
, Uintptr
:
2274 case Float32
, Float64
:
2277 return cvtUintString
2280 case Float32
, Float64
:
2282 case Int
, Int8
, Int16
, Int32
, Int64
:
2284 case Uint
, Uint8
, Uint16
, Uint32
, Uint64
, Uintptr
:
2286 case Float32
, Float64
:
2290 case Complex64
, Complex128
:
2292 case Complex64
, Complex128
:
2297 if dst
.Kind() == Slice
&& dst
.Elem().PkgPath() == "" {
2298 switch dst
.Elem().Kind() {
2300 return cvtStringBytes
2302 return cvtStringRunes
2307 if dst
.Kind() == String
&& src
.Elem().PkgPath() == "" {
2308 switch src
.Elem().Kind() {
2310 return cvtBytesString
2312 return cvtRunesString
2317 // dst and src have same underlying type.
2318 if haveIdenticalUnderlyingType(dst
, src
) {
2322 // dst and src are unnamed pointer types with same underlying base type.
2323 if dst
.Kind() == Ptr
&& dst
.Name() == "" &&
2324 src
.Kind() == Ptr
&& src
.Name() == "" &&
2325 haveIdenticalUnderlyingType(dst
.Elem().common(), src
.Elem().common()) {
2329 if implements(dst
, src
) {
2330 if src
.Kind() == Interface
{
2339 // makeInt returns a Value of type t equal to bits (possibly truncated),
2340 // where t is a signed or unsigned int type.
2341 func makeInt(f flag
, bits
uint64, t Type
) Value
{
2343 if typ
.size
> ptrSize
{
2344 // Assume ptrSize >= 4, so this must be uint64.
2345 ptr
:= unsafe_New(typ
)
2346 *(*uint64)(unsafe
.Pointer(ptr
)) = bits
2347 return Value
{typ
, ptr
/* 0, */, f | flagIndir |
flag(typ
.Kind())<<flagKindShift
}
2352 *(*uint8)(unsafe
.Pointer(&s
)) = uint8(bits
)
2354 *(*uint16)(unsafe
.Pointer(&s
)) = uint16(bits
)
2356 *(*uint32)(unsafe
.Pointer(&s
)) = uint32(bits
)
2358 *(*uint64)(unsafe
.Pointer(&s
)) = uint64(bits
)
2360 return Value
{typ
, unsafe
.Pointer(&s
) /* 0, */, f | flagIndir |
flag(typ
.Kind())<<flagKindShift
}
2363 // makeFloat returns a Value of type t equal to v (possibly truncated to float32),
2364 // where t is a float32 or float64 type.
2365 func makeFloat(f flag
, v
float64, t Type
) Value
{
2367 if typ
.size
> ptrSize
{
2368 // Assume ptrSize >= 4, so this must be float64.
2369 ptr
:= unsafe_New(typ
)
2370 *(*float64)(unsafe
.Pointer(ptr
)) = v
2371 return Value
{typ
, ptr
/* 0, */, f | flagIndir |
flag(typ
.Kind())<<flagKindShift
}
2377 *(*float32)(unsafe
.Pointer(&s
)) = float32(v
)
2379 *(*float64)(unsafe
.Pointer(&s
)) = v
2381 return Value
{typ
, unsafe
.Pointer(&s
) /* 0, */, f | flagIndir |
flag(typ
.Kind())<<flagKindShift
}
2384 // makeComplex returns a Value of type t equal to v (possibly truncated to complex64),
2385 // where t is a complex64 or complex128 type.
2386 func makeComplex(f flag
, v complex128
, t Type
) Value
{
2388 if typ
.size
> ptrSize
{
2389 ptr
:= unsafe_New(typ
)
2392 *(*complex64
)(unsafe
.Pointer(ptr
)) = complex64(v
)
2394 *(*complex128
)(unsafe
.Pointer(ptr
)) = v
2396 return Value
{typ
, ptr
/* 0, */, f | flagIndir |
flag(typ
.Kind())<<flagKindShift
}
2399 // Assume ptrSize <= 8 so this must be complex64.
2401 *(*complex64
)(unsafe
.Pointer(&s
)) = complex64(v
)
2402 return Value
{typ
, unsafe
.Pointer(&s
) /* 0, */, f | flagIndir |
flag(typ
.Kind())<<flagKindShift
}
2405 func makeString(f flag
, v
string, t Type
) Value
{
2406 ret
:= New(t
).Elem()
2408 ret
.flag
= ret
.flag
&^flagAddr | f | flagIndir
2412 func makeBytes(f flag
, v
[]byte, t Type
) Value
{
2413 ret
:= New(t
).Elem()
2415 ret
.flag
= ret
.flag
&^flagAddr | f | flagIndir
2419 func makeRunes(f flag
, v
[]rune
, t Type
) Value
{
2420 ret
:= New(t
).Elem()
2422 ret
.flag
= ret
.flag
&^flagAddr | f | flagIndir
2426 // These conversion functions are returned by convertOp
2427 // for classes of conversions. For example, the first function, cvtInt,
2428 // takes any value v of signed int type and returns the value converted
2429 // to type t, where t is any signed or unsigned int type.
2431 // convertOp: intXX -> [u]intXX
2432 func cvtInt(v Value
, t Type
) Value
{
2433 return makeInt(v
.flag
&flagRO
, uint64(v
.Int()), t
)
2436 // convertOp: uintXX -> [u]intXX
2437 func cvtUint(v Value
, t Type
) Value
{
2438 return makeInt(v
.flag
&flagRO
, v
.Uint(), t
)
2441 // convertOp: floatXX -> intXX
2442 func cvtFloatInt(v Value
, t Type
) Value
{
2443 return makeInt(v
.flag
&flagRO
, uint64(int64(v
.Float())), t
)
2446 // convertOp: floatXX -> uintXX
2447 func cvtFloatUint(v Value
, t Type
) Value
{
2448 return makeInt(v
.flag
&flagRO
, uint64(v
.Float()), t
)
2451 // convertOp: intXX -> floatXX
2452 func cvtIntFloat(v Value
, t Type
) Value
{
2453 return makeFloat(v
.flag
&flagRO
, float64(v
.Int()), t
)
2456 // convertOp: uintXX -> floatXX
2457 func cvtUintFloat(v Value
, t Type
) Value
{
2458 return makeFloat(v
.flag
&flagRO
, float64(v
.Uint()), t
)
2461 // convertOp: floatXX -> floatXX
2462 func cvtFloat(v Value
, t Type
) Value
{
2463 return makeFloat(v
.flag
&flagRO
, v
.Float(), t
)
2466 // convertOp: complexXX -> complexXX
2467 func cvtComplex(v Value
, t Type
) Value
{
2468 return makeComplex(v
.flag
&flagRO
, v
.Complex(), t
)
2471 // convertOp: intXX -> string
2472 func cvtIntString(v Value
, t Type
) Value
{
2473 return makeString(v
.flag
&flagRO
, string(v
.Int()), t
)
2476 // convertOp: uintXX -> string
2477 func cvtUintString(v Value
, t Type
) Value
{
2478 return makeString(v
.flag
&flagRO
, string(v
.Uint()), t
)
2481 // convertOp: []byte -> string
2482 func cvtBytesString(v Value
, t Type
) Value
{
2483 return makeString(v
.flag
&flagRO
, string(v
.Bytes()), t
)
2486 // convertOp: string -> []byte
2487 func cvtStringBytes(v Value
, t Type
) Value
{
2488 return makeBytes(v
.flag
&flagRO
, []byte(v
.String()), t
)
2491 // convertOp: []rune -> string
2492 func cvtRunesString(v Value
, t Type
) Value
{
2493 return makeString(v
.flag
&flagRO
, string(v
.runes()), t
)
2496 // convertOp: string -> []rune
2497 func cvtStringRunes(v Value
, t Type
) Value
{
2498 return makeRunes(v
.flag
&flagRO
, []rune(v
.String()), t
)
2501 // convertOp: direct copy
2502 func cvtDirect(v Value
, typ Type
) Value
{
2506 if f
&flagAddr
!= 0 {
2507 // indirect, mutable word - make a copy
2509 memmove(c
, ptr
, t
.size
)
2513 return Value
{t
, ptr
/* v.scalar, */, v
.flag
&flagRO | f
} // v.flag&flagRO|f == f?
2516 // convertOp: concrete -> interface
2517 func cvtT2I(v Value
, typ Type
) Value
{
2518 target
:= new(interface{})
2519 x
:= valueInterface(v
, false)
2520 if typ
.NumMethod() == 0 {
2523 ifaceE2I(typ
.(*rtype
), x
, unsafe
.Pointer(target
))
2525 return Value
{typ
.common(), unsafe
.Pointer(target
) /* 0, */, v
.flag
&flagRO | flagIndir |
flag(Interface
)<<flagKindShift
}
2528 // convertOp: interface -> interface
2529 func cvtI2I(v Value
, typ Type
) Value
{
2532 ret
.flag |
= v
.flag
& flagRO
2535 return cvtT2I(v
.Elem(), typ
)
2538 // implemented in ../pkg/runtime
2539 func chancap(ch unsafe
.Pointer
) int
2540 func chanclose(ch unsafe
.Pointer
)
2541 func chanlen(ch unsafe
.Pointer
) int
2542 func chanrecv(t
*rtype
, ch unsafe
.Pointer
, nb
bool) (val iword
, selected
, received
bool)
2543 func chansend(t
*rtype
, ch unsafe
.Pointer
, val iword
, nb
bool) bool
2545 func makechan(typ
*rtype
, size
uint64) (ch unsafe
.Pointer
)
2546 func makemap(t
*rtype
) (m unsafe
.Pointer
)
2547 func mapaccess(t
*rtype
, m unsafe
.Pointer
, key unsafe
.Pointer
) (val unsafe
.Pointer
)
2548 func mapassign(t
*rtype
, m unsafe
.Pointer
, key
, val unsafe
.Pointer
)
2549 func mapdelete(t
*rtype
, m unsafe
.Pointer
, key unsafe
.Pointer
)
2550 func mapiterinit(t
*rtype
, m unsafe
.Pointer
) unsafe
.Pointer
2551 func mapiterkey(it unsafe
.Pointer
) (key unsafe
.Pointer
)
2552 func mapiternext(it unsafe
.Pointer
)
2553 func maplen(m unsafe
.Pointer
) int
2555 func call(typ
*rtype
, fnaddr unsafe
.Pointer
, isInterface
bool, isMethod
bool, params
*unsafe
.Pointer
, results
*unsafe
.Pointer
)
2556 func ifaceE2I(t
*rtype
, src
interface{}, dst unsafe
.Pointer
)
2558 // Dummy annotation marking that the value x escapes,
2559 // for use in cases where the reflect code is so clever that
2560 // the compiler cannot follow.
2561 func escapes(x
interface{}) {