本文整理汇总了Golang中reflect.AppendSlice函数的典型用法代码示例。如果您正苦于以下问题:Golang AppendSlice函数的具体用法?Golang AppendSlice怎么用?Golang AppendSlice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了AppendSlice函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Append
func (association *Association) Append(values ...interface{}) *Association {
scope := association.Scope
field := scope.IndirectValue().FieldByName(association.Column)
for _, value := range values {
reflectvalue := reflect.ValueOf(value)
if reflectvalue.Kind() == reflect.Ptr {
if reflectvalue.Elem().Kind() == reflect.Struct {
if field.Type().Elem().Kind() == reflect.Ptr {
field.Set(reflect.Append(field, reflectvalue))
} else if field.Type().Elem().Kind() == reflect.Struct {
field.Set(reflect.Append(field, reflectvalue.Elem()))
}
} else if reflectvalue.Elem().Kind() == reflect.Slice {
if field.Type().Elem().Kind() == reflect.Ptr {
field.Set(reflect.AppendSlice(field, reflectvalue))
} else if field.Type().Elem().Kind() == reflect.Struct {
field.Set(reflect.AppendSlice(field, reflectvalue.Elem()))
}
}
} else if reflectvalue.Kind() == reflect.Struct && field.Type().Elem().Kind() == reflect.Struct {
field.Set(reflect.Append(field, reflectvalue))
} else if reflectvalue.Kind() == reflect.Slice && field.Type().Elem() == reflectvalue.Type().Elem() {
field.Set(reflect.AppendSlice(field, reflectvalue))
} else {
association.err(errors.New("invalid association type"))
}
}
scope.callCallbacks(scope.db.parent.callback.updates)
return association.err(scope.db.Error)
}
示例2: Build
func (s *sequenceType) Build(i *Injector) (Binding, error) {
binding, err := Annotate(s.v).Build(i)
if err != nil {
return Binding{}, err
}
if binding.Provides.Kind() != reflect.Slice {
return Binding{}, fmt.Errorf("Sequence() must be bound to a slice not %s", binding.Provides)
}
next, ok := i.bindings[binding.Provides]
return Binding{
Provides: binding.Provides,
Requires: binding.Requires,
Build: func() (interface{}, error) {
out := reflect.MakeSlice(binding.Provides, 0, 0)
if ok {
v, err := next.Build()
if err != nil {
return nil, err
}
out = reflect.AppendSlice(out, reflect.ValueOf(v))
}
v, err := binding.Build()
if err != nil {
return nil, err
}
out = reflect.AppendSlice(out, reflect.ValueOf(v))
return out.Interface(), nil
},
}, nil
}
示例3: DeleteCopy
// DeleteCopy removes the element of the slice at a given index.
// The returned slice references a new array, the original
// array and all referencing slices are un-altered.
//
// The returned slice will be the same type as the given slice, but
// stored in an interface{}.
//
// Uses reflection to perform this action on slices of any type.
// Will panic if:
// - slice argument is not a slice type
// - idx is not in the range 0 .. len(slice)-1
//
// Equivalent to:
// slice = append(append(make([]T,0,len(slice)-1),slice[:idx]...),slice[idx+1]...)
func DeleteCopy(slice interface{}, index int) interface{} {
sliceVal := checkDelete(slice, index)
begin := sliceVal.Slice(0, index)
end := sliceVal.Slice(index+1, sliceVal.Len())
tmp := reflect.MakeSlice(sliceVal.Type(), 0, sliceVal.Len()-1)
return reflect.AppendSlice(reflect.AppendSlice(tmp, begin), end).Interface()
}
示例4: InsertCopy
// InsertCopy adds an element to a slice at a given index. Always allocates
// a new slice, and never modifies the original memory.
//
// The returned slice will be the same type as the given slice, but
// stored in an interface{}.
//
// Uses reflection to perform this action on slices of any type.
// Will panic if:
// - slice argument is not a slice type
// - slice argument's element type doesn't match item's type
// - idx is not in the range 0 .. len(slice)
//
// Equivalent to:
// begin, end := slice[:idx], slice[idx:]
// slice = append(append(append(make([]T,0,len(slice)+1), begin...),item),end...)
func InsertCopy(slice interface{}, index int, item interface{}) interface{} {
sliceVal, itemVal := checkInsert(slice, index, item)
begin := sliceVal.Slice(0, index)
end := sliceVal.Slice(index, sliceVal.Len())
out := reflect.MakeSlice(sliceVal.Type(), 0, sliceVal.Len()+1)
out = reflect.AppendSlice(reflect.Append(reflect.AppendSlice(out, begin), itemVal), end)
return out.Interface()
}
示例5: Fuzz
func (f *protoFuzzer) Fuzz(v reflect.Value) {
if !v.CanSet() {
return
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
f.FuzzInt(v)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
f.FuzzUint(v)
case reflect.String:
str := ""
for i := 0; i < v.Len(); i++ {
str = str + string(' '+rune(f.r.Intn(94)))
}
v.SetString(str)
return
case reflect.Ptr:
if !v.IsNil() {
f.Fuzz(v.Elem())
}
return
case reflect.Slice:
mode := f.r.Intn(3)
switch {
case v.Len() > 0 && mode == 0:
// fuzz entry
f.Fuzz(v.Index(f.r.Intn(v.Len())))
case v.Len() > 0 && mode == 1:
// remove entry
entry := f.r.Intn(v.Len())
pre := v.Slice(0, entry)
post := v.Slice(entry+1, v.Len())
v.Set(reflect.AppendSlice(pre, post))
default:
// add entry
entry := reflect.MakeSlice(v.Type(), 1, 1)
f.Fuzz(entry) // XXX fill all fields
v.Set(reflect.AppendSlice(v, entry))
}
return
case reflect.Struct:
f.Fuzz(v.Field(f.r.Intn(v.NumField())))
return
case reflect.Map:
// TODO fuzz map
default:
panic(fmt.Sprintf("Not fuzzing %v %+v", v.Kind(), v))
}
}
示例6: main
func main() {
var a []int
var value reflect.Value = reflect.ValueOf(&a)
//判断指针是否指向内存地址
if !value.CanSet() {
value = value.Elem() //使指针指向内存地址
}
value = reflect.AppendSlice(value, reflect.ValueOf([]int{1, 2})) //支持切片
value = reflect.AppendSlice(value, reflect.ValueOf([]int{3, 4, 5, 6, 7, 8, 9})) //支持切片
fmt.Println(value.Kind(), value.Slice(0, value.Len()).Interface())
///// >> slice [1 2 3 4 5 6 7 8 9]
}
示例7: Next
func (s *sliceShrink) Next() (interface{}, bool) {
if s.chunkLength == 0 {
return nil, false
}
value := reflect.AppendSlice(reflect.MakeSlice(s.original.Type(), 0, s.length-s.chunkLength), s.original.Slice(0, s.offset))
s.offset += s.chunkLength
if s.offset < s.length {
value = reflect.AppendSlice(value, s.original.Slice(s.offset, s.length))
} else {
s.offset = 0
s.chunkLength >>= 1
}
return value.Interface(), true
}
示例8: loadSlice
// loadSlice loads url and decodes it into a []elemType, returning the []elemType and error.
func loadSlice(url string, elemType interface{}) (interface{}, error) {
t := reflect.TypeOf(elemType)
result := reflect.New(reflect.SliceOf(t)).Elem() // result is []elemType
link := url
for link != "" {
req, err := http.NewRequest("GET", link, nil)
if err != nil {
return result.Interface(), err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return result.Interface(), err
}
if resp.StatusCode > 299 {
lr := io.LimitReader(resp.Body, 1024)
bs, _ := ioutil.ReadAll(lr)
resp.Body.Close()
return result.Interface(), fmt.Errorf("http.Get: %v (%s)", resp.Status, bs)
}
tmp := reflect.New(reflect.SliceOf(t)) // tmp is *[]elemType
err = json.NewDecoder(resp.Body).Decode(tmp.Interface())
resp.Body.Close()
if err != nil {
return result.Interface(), err
}
result = reflect.AppendSlice(result, tmp.Elem())
link = parseRel(resp.Header.Get("Link"), "next")
}
return result.Interface(), nil
}
示例9: deStructSlice
func deStructSlice(dataValue reflect.Value) (interface{}, interface{}, map[string]interface{}) {
if dataValue.Kind() == reflect.Uint8 {
newDataValue := reflect.MakeSlice(dataValue.Type(), dataValue.Len(), dataValue.Cap())
newDataValue = reflect.AppendSlice(newDataValue, dataValue)
return newDataValue.Interface(), newDataValue.Interface(), nil
}
//TODO if the type inside the slice is not a struct, recreate the slice with the same definition
newData := make([]interface{}, dataValue.Len())
flatData := make(map[string]interface{})
for i := 0; i < dataValue.Len(); i++ {
subDataValue := dataValue.Index(i)
key := strconv.Itoa(i)
fieldCopy, fieldScalar, fieldMap := deStructValue(subDataValue)
newData[i] = fieldCopy
if fieldScalar != nil {
flatData[key] = fieldScalar
}
for fieldMapKey, fieldMapValue := range fieldMap {
flatData[key+"."+fieldMapKey] = fieldMapValue
}
}
return newData, nil, flatData
}
示例10: Execute
func (node *tagAppendNode) Execute(ctx *p2.ExecutionContext, writer p2.TemplateWriter) *p2.Error {
var values []interface{}
var reflectValues reflect.Value
if o := ctx.Public[node.name]; nil != o {
values, _ = o.([]interface{})
if nil == values {
reflectValues = reflect.ValueOf(o)
if reflectValues.Kind() == reflect.Ptr {
reflectValues = reflectValues.Elem()
}
if reflectValues.Kind() != reflect.Slice {
return ctx.Error("'"+node.name+"' isn't a slice.", nil)
}
}
}
for _, ev := range node.objectEvaluators {
obj, err := ev.Evaluate(ctx)
if err != nil {
return err
}
if reflectValues.IsNil() {
values = append(values, obj)
} else {
reflectValues = reflect.AppendSlice(reflectValues, reflect.ValueOf(obj))
}
}
if reflectValues.IsNil() {
ctx.Public[node.name] = values
} else {
ctx.Public[node.name] = reflectValues.Interface()
}
return nil
}
示例11: Delete
func Delete(element interface{}, slice interface{}) bool {
valElement := reflect.ValueOf(element)
typSlice := reflect.TypeOf(slice)
valSlice := reflect.ValueOf(slice)
if !valElement.IsValid() || !valSlice.IsValid() {
return false
}
switch typSlice.Kind() {
case reflect.Slice:
sliceLen := valSlice.Len()
for idx := 0; idx < sliceLen; idx++ {
val := valSlice.Index(idx)
if !val.IsValid() {
continue
}
if val.Interface() == valElement.Interface() {
if idx == sliceLen-1 {
valSlice = valSlice.Slice(0, idx)
} else {
valSlice = reflect.AppendSlice(valSlice.Slice(0, idx), valSlice.Slice(idx+1, sliceLen-1))
}
}
}
case reflect.Map:
}
return false
}
示例12: mergeValue
func mergeValue(values []reflect.Value) reflect.Value {
values = removeZeroValues(values)
l := len(values)
if l == 0 {
return reflect.Value{}
}
sample := values[0]
mergeable := isMergeable(sample)
t := sample.Type()
if mergeable {
t = t.Elem()
}
value := reflect.MakeSlice(reflect.SliceOf(t), 0, 0)
for i := 0; i < l; i++ {
if !values[i].IsValid() {
continue
}
if mergeable {
value = reflect.AppendSlice(value, values[i])
} else {
value = reflect.Append(value, values[i])
}
}
return value
}
示例13: mergeStruct
// A very limited merge. Merges the fields named in the fields parameter,
// replacing most values, but appending to arrays.
func mergeStruct(base, overlay interface{}, fields []string) error {
baseValue := reflect.ValueOf(base).Elem()
overlayValue := reflect.ValueOf(overlay).Elem()
if baseValue.Kind() != reflect.Struct {
return fmt.Errorf("Tried to merge something that wasn't a struct: type %v was %v",
baseValue.Type(), baseValue.Kind())
}
if baseValue.Type() != overlayValue.Type() {
return fmt.Errorf("Tried to merge two different types: %v and %v",
baseValue.Type(), overlayValue.Type())
}
for _, field := range fields {
overlayFieldValue := findField(field, overlayValue)
if !overlayFieldValue.IsValid() {
return fmt.Errorf("could not find field in %v matching %v",
overlayValue.Type(), field)
}
baseFieldValue := findField(field, baseValue)
if overlayFieldValue.Kind() == reflect.Slice {
baseFieldValue.Set(reflect.AppendSlice(baseFieldValue, overlayFieldValue))
} else {
baseFieldValue.Set(overlayFieldValue)
}
}
return nil
}
示例14: Stitch
// Stitch provides a function that may be used by polymer types to implement Stitcher.
// It makes use of reflection and so may be slower than type-specific implementations.
// This is the reference implementation and should be used to compare type-specific
// implementation against in testing.
func Stitch(pol interface{}, offset int, f feat.FeatureSet) (s interface{}, err error) {
t := interval.NewTree()
var i *interval.Interval
for _, feature := range f {
i, err = interval.New(emptyString, feature.Start, feature.End, 0, nil)
if err != nil {
return
} else {
t.Insert(i)
}
}
pv := reflect.ValueOf(pol)
pLen := pv.Len()
end := pLen + offset
span, err := interval.New(emptyString, offset, end, 0, nil)
if err != nil {
panic("Sequence.End() < Sequence.Start()")
}
fs, _ := t.Flatten(span, 0, 0)
l := 0
for _, seg := range fs {
l += util.Min(seg.End(), end) - util.Max(seg.Start(), offset)
}
tv := reflect.MakeSlice(pv.Type(), 0, l)
for _, seg := range fs {
tv = reflect.AppendSlice(tv, pv.Slice(util.Max(seg.Start()-offset, 0), util.Min(seg.End()-offset, pLen)))
}
return tv.Interface(), nil
}
示例15: appendStruct
// appendStruct is an internal helper function to AppendConfig. Given two values
// of structures (assumed to be the same type), recursively iterate over every
// field in the struct, appending slices, recursively appending structs, and
// overwriting old values with the new for all other types. Individual fields
// are able to override their merge strategy using the "merge" tag. Accepted
// values are "new" or "old": "new" uses the new value, "old" uses the old
// value. These are currently only used for "ignition.config" and
// "ignition.version".
func appendStruct(vOld, vNew reflect.Value) reflect.Value {
tOld := vOld.Type()
vRes := reflect.New(tOld)
for i := 0; i < tOld.NumField(); i++ {
vfOld := vOld.Field(i)
vfNew := vNew.Field(i)
vfRes := vRes.Elem().Field(i)
switch tOld.Field(i).Tag.Get("merge") {
case "old":
vfRes.Set(vfOld)
continue
case "new":
vfRes.Set(vfNew)
continue
}
switch vfOld.Type().Kind() {
case reflect.Struct:
vfRes.Set(appendStruct(vfOld, vfNew))
case reflect.Slice:
vfRes.Set(reflect.AppendSlice(vfOld, vfNew))
default:
vfRes.Set(vfNew)
}
}
return vRes.Elem()
}