本文整理汇总了Golang中reflect.Copy函数的典型用法代码示例。如果您正苦于以下问题:Golang Copy函数的具体用法?Golang Copy怎么用?Golang Copy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Copy函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
src := reflect.ValueOf([]int{1, 2, 3})
/* make sure the dest space is larger than src */
dest := reflect.ValueOf([]int{10, 20, 30})
cnt := reflect.Copy(dest, src)
data := dest.Interface().([]int)
data[0] = 100
fmt.Println(cnt)
fmt.Println(src)
fmt.Println(dest)
elmt := map[string]int{"age": 10}
data2 := make([]map[string]int, 1)
data2[0] = elmt
src2 := reflect.ValueOf(data2)
dest2 := reflect.ValueOf(make([]map[string]int, 1))
cnt2 := reflect.Copy(dest2, src2)
data2[0]["age"] = 100 /* they share the same map */
fmt.Println(cnt2)
fmt.Println(src2)
fmt.Println(dest2)
}
示例2: Remove
// Remove removes the first occurence of the given val. It returns true
// if an element was removed, false otherwise. Note that the first argument
// must a pointer to a slice, while the second one must be a valid element
// of the slice. Otherwise, this function will panic.
func Remove(slicePtr interface{}, val interface{}) bool {
s := reflect.ValueOf(slicePtr)
if s.Kind() != reflect.Ptr || s.Type().Elem().Kind() != reflect.Slice {
panic(fmt.Errorf("first argument to Remove must be pointer to slice, not %T", slicePtr))
}
if s.IsNil() {
return false
}
itr := s.Elem()
v := reflect.ValueOf(val)
if itr.Type().Elem() != v.Type() {
panic(fmt.Errorf("second argument to Remove must be %s, not %s", itr.Type().Elem(), v.Type()))
}
vi := v.Interface()
for ii := 0; ii < itr.Len(); ii++ {
if reflect.DeepEqual(itr.Index(ii).Interface(), vi) {
newSlice := reflect.MakeSlice(itr.Type(), itr.Len()-1, itr.Len()-1)
reflect.Copy(newSlice, itr.Slice(0, ii))
reflect.Copy(newSlice.Slice(ii, newSlice.Len()), itr.Slice(ii+1, itr.Len()))
s.Elem().Set(newSlice)
return true
}
}
return false
}
示例3: overwrite
func (s RSlice) overwrite(offset int, source *reflect.Value) {
if offset == 0 {
reflect.Copy(*s.Value, *source)
} else {
reflect.Copy(s.Slice(offset, s.Len()), *source)
}
}
示例4: mapArray
func (this *SpecificDatumReader) mapArray(field Schema, reflectField reflect.Value, dec Decoder) (reflect.Value, error) {
if arrayLength, err := dec.ReadArrayStart(); err != nil {
return reflect.ValueOf(arrayLength), err
} else {
array := reflect.MakeSlice(reflectField.Type(), 0, 0)
for {
arrayPart := reflect.MakeSlice(reflectField.Type(), int(arrayLength), int(arrayLength))
var i int64 = 0
for ; i < arrayLength; i++ {
val, err := this.readValue(field.(*ArraySchema).Items, arrayPart.Index(int(i)), dec)
if err != nil {
return reflect.ValueOf(arrayLength), err
}
if val.Kind() == reflect.Ptr {
arrayPart.Index(int(i)).Set(val.Elem())
} else {
arrayPart.Index(int(i)).Set(val)
}
}
//concatenate arrays
concatArray := reflect.MakeSlice(reflectField.Type(), array.Len()+int(arrayLength), array.Cap()+int(arrayLength))
reflect.Copy(concatArray, array)
reflect.Copy(concatArray, arrayPart)
array = concatArray
arrayLength, err = dec.ArrayNext()
if err != nil {
return reflect.ValueOf(arrayLength), err
} else if arrayLength == 0 {
break
}
}
return array, nil
}
}
示例5: NextN
//return the next n permuations, if n>p.Left(),return all the left permuations
//if all permutaions generated or n is illegal(n<=0),return a empty slice
func (p *Permutator) NextN(n int) interface{} {
<-p.idle
//if n<=0 or we generate all pemutations,just return a empty slice
if n <= 0 || p.left() == 0 {
p.idle <- true
return reflect.MakeSlice(reflect.SliceOf(p.value.Type()), 0, 0).Interface()
}
var i, j int
cap := p.left()
if cap > n {
cap = n
}
result := reflect.MakeSlice(reflect.SliceOf(p.value.Type()), cap, cap)
if p.length == 1 {
p.index++
l := reflect.MakeSlice(p.value.Type(), p.length, p.length)
reflect.Copy(l, p.value)
p.idle <- true
result.Index(0).Set(l)
return result.Interface()
}
if p.index == 1 {
p.index++
l := reflect.MakeSlice(p.value.Type(), p.length, p.length)
reflect.Copy(l, p.value)
result.Index(0).Set(l)
}
for k := 1; k < cap; k++ {
for i = p.length - 2; i >= 0; i-- {
if p.less(p.value.Index(i).Interface(), p.value.Index(i+1).Interface()) {
break
}
}
for j = p.length - 1; j >= 0; j-- {
if p.less(p.value.Index(i).Interface(), p.value.Index(j).Interface()) {
break
}
}
//swap
temp := reflect.ValueOf(p.value.Index(i).Interface())
p.value.Index(i).Set(p.value.Index(j))
p.value.Index(j).Set(temp)
//reverse
reverse(p.value, i+1, p.length-1)
//increase the counter
p.index++
l := reflect.MakeSlice(p.value.Type(), p.length, p.length)
reflect.Copy(l, p.value)
result.Index(k).Set(l)
}
p.idle <- true
return result.Interface()
}
示例6: TestRaceReflectCopyWW
func TestRaceReflectCopyWW(t *testing.T) {
ch := make(chan bool, 1)
a := make([]byte, 2)
v := reflect.ValueOf(a)
go func() {
reflect.Copy(v, v)
ch <- true
}()
reflect.Copy(v, v)
<-ch
}
示例7: parseNextItem
func (fs *FlagSet) parseNextItem(args []string) ([]string, error) {
if strings.HasPrefix(args[0], "--") {
return fs.parseLongFlag(args)
} else if strings.HasPrefix(args[0], "-") {
return fs.parseShortFlagCluster(args)
}
if fs.Verbs != nil {
verb, ok := fs.Verbs[args[0]]
if !ok {
return args, fmt.Errorf("Unknown verb: %s", args[0])
}
err := verb.Parse(args[1:])
if err != nil {
return args, err
}
return []string{}, nil
}
if fs.remainderFlag != nil {
remainder := reflect.MakeSlice(fs.remainderFlag.value.Type(), len(args), len(args))
reflect.Copy(remainder, reflect.ValueOf(args))
fs.remainderFlag.value.Set(remainder)
return []string{}, nil
}
return args, fmt.Errorf("Invalid trailing arguments: %v", args)
}
示例8: Reallocate
/*
Create a new memory container and copy contents across to it.
Returns nil when reallocation fails.
*/
func Reallocate(container interface{}, length, capacity int) (r interface{}) {
switch c := container.(type) {
case Resizeable:
c.Reallocate(length, capacity)
r = c
default:
if c := reflect.ValueOf(container); c.Kind() == reflect.Slice {
if length > capacity {
length = capacity
}
if c.Cap() != capacity {
n := reflect.MakeSlice(c.Type(), length, capacity)
reflect.Copy(n, c)
c = n
}
if c.Len() != length {
c = makeAddressable(c)
c.SetLen(length)
}
r = c.Interface()
}
}
return
}
示例9: encodeFixedArray
// encodeFixedArray writes the XDR encoded representation of each element
// in the passed array represented by the reflection value to the encapsulated
// writer and returns the number of bytes written. The ignoreOpaque flag
// controls whether or not uint8 (byte) elements should be encoded individually
// or as a fixed sequence of opaque data.
//
// A MarshalError is returned if any issues are encountered while encoding
// the array elements.
//
// Reference:
// RFC Section 4.12 - Fixed-Length Array
// Individually XDR encoded array elements
func (enc *Encoder) encodeFixedArray(v reflect.Value, ignoreOpaque bool) (int, error) {
// Treat [#]byte (byte is alias for uint8) as opaque data unless ignored.
if !ignoreOpaque && v.Type().Elem().Kind() == reflect.Uint8 {
// Create a slice of the underlying array for better efficiency
// when possible. Can't create a slice of an unaddressable
// value.
if v.CanAddr() {
return enc.EncodeFixedOpaque(v.Slice(0, v.Len()).Bytes())
}
// When the underlying array isn't addressable fall back to
// copying the array into a new slice. This is rather ugly, but
// the inability to create a constant slice from an
// unaddressable array is a limitation of Go.
slice := make([]byte, v.Len(), v.Len())
reflect.Copy(reflect.ValueOf(slice), v)
return enc.EncodeFixedOpaque(slice)
}
// Encode each array element.
var n int
for i := 0; i < v.Len(); i++ {
n2, err := enc.encode(v.Index(i))
n += n2
if err != nil {
return n, err
}
}
return n, nil
}
示例10: TestSort
func TestSort(t *testing.T) {
tests := []interface{}{
[]int{3, 4, 6, 7, 2},
[]uint{3, 4, 6, 7, 2},
[]float64{3, 4, 6, 7, 2},
[]string{"f", "d", "a", "c"},
[]int{1},
[]int{},
}
for _, v := range tests {
vv := reflect.ValueOf(v)
cpy := reflect.MakeSlice(vv.Type(), vv.Len(), vv.Len())
reflect.Copy(cpy, vv)
switch x := v.(type) {
case []int:
sort.Ints(x)
case []uint:
sort.Sort(uintslice(x))
case []float64:
sort.Float64s(x)
case []string:
sort.Strings(x)
}
reflectSortCompare(t, v, cpy)
}
}
示例11: decodeSlice
func decodeSlice(d *decodeState, kind int, value reflect.Value) {
if kind != kindArray {
d.saveErrorAndSkip(kind, value.Type())
return
}
v := value.(*reflect.SliceValue)
t := v.Type().(*reflect.SliceType)
offset := d.beginDoc()
i := 0
for {
kind, _ := d.scanKindName()
if kind == 0 {
break
}
if i >= v.Cap() {
newcap := v.Cap() + v.Cap()/2
if newcap < 4 {
newcap = 4
}
newv := reflect.MakeSlice(t, v.Len(), newcap)
reflect.Copy(newv, v)
v.Set(newv)
}
if i >= v.Len() {
v.SetLen(i + 1)
}
d.decodeValue(kind, v.Elem(i))
i += 1
}
d.endDoc(offset)
}
示例12: decodeSliceElems
func decodeSliceElems(s *Stream, val reflect.Value, elemdec decoder) error {
i := 0
for ; ; i++ {
// grow slice if necessary
if i >= val.Cap() {
newcap := val.Cap() + val.Cap()/2
if newcap < 4 {
newcap = 4
}
newv := reflect.MakeSlice(val.Type(), val.Len(), newcap)
reflect.Copy(newv, val)
val.Set(newv)
}
if i >= val.Len() {
val.SetLen(i + 1)
}
// decode into element
if err := elemdec(s, val.Index(i)); err == EOL {
break
} else if err != nil {
return addErrorContext(err, fmt.Sprint("[", i, "]"))
}
}
if i < val.Len() {
val.SetLen(i)
}
return nil
}
示例13: encodeByteArray
func encodeByteArray(b []byte, v reflect.Value) []byte {
n := v.Len()
if n < (0xec - 0xe0) {
b = append(b, byte(0xe0+n))
} else {
b = encodeK4(b, 0xec, uint64(n))
}
// Fast path for when the array is addressable (which it almost
// always will be).
if v.CanAddr() {
return append(b, v.Slice(0, n).Bytes()...)
}
i := len(b)
j := i + n
if j > cap(b) {
t := make([]byte, i, j)
copy(t, b)
b = t
}
reflect.Copy(reflect.ValueOf(b[i:j]), v)
return b[:j]
}
示例14: setCustomType
func setCustomType(base structPointer, f field, value interface{}) {
if value == nil {
return
}
v := reflect.ValueOf(value).Elem()
t := reflect.TypeOf(value).Elem()
kind := t.Kind()
switch kind {
case reflect.Slice:
slice := reflect.MakeSlice(t, v.Len(), v.Cap())
reflect.Copy(slice, v)
oldHeader := structPointer_GetSliceHeader(base, f)
oldHeader.Data = slice.Pointer()
oldHeader.Len = v.Len()
oldHeader.Cap = v.Cap()
default:
l := 1
size := reflect.TypeOf(value).Elem().Size()
if kind == reflect.Array {
l = reflect.TypeOf(value).Elem().Len()
size = reflect.TypeOf(value).Size()
}
total := int(size) * l
structPointer_Copy(toStructPointer(reflect.ValueOf(value)), structPointer_Add(base, f), total)
}
}
示例15: unmarshalArray
func (p *Decoder) unmarshalArray(pval *plistValue, val reflect.Value) {
subvalues := pval.value.([]*plistValue)
var n int
if val.Kind() == reflect.Slice {
// Slice of element values.
// Grow slice.
cnt := len(subvalues) + val.Len()
if cnt >= val.Cap() {
ncap := 2 * cnt
if ncap < 4 {
ncap = 4
}
new := reflect.MakeSlice(val.Type(), val.Len(), ncap)
reflect.Copy(new, val)
val.Set(new)
}
n = val.Len()
val.SetLen(cnt)
} else if val.Kind() == reflect.Array {
if len(subvalues) > val.Cap() {
panic(fmt.Errorf("plist: attempted to unmarshal %d values into an array of size %d", len(subvalues), val.Cap()))
}
} else {
panic(&incompatibleDecodeTypeError{val.Type(), pval.kind})
}
// Recur to read element into slice.
for _, sval := range subvalues {
p.unmarshal(sval, val.Index(n))
n++
}
return
}