本文整理汇总了Golang中reflect.MakeSlice函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeSlice函数的具体用法?Golang MakeSlice怎么用?Golang MakeSlice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MakeSlice函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: decodeSlice
func (d *Decoder) decodeSlice(s *decodStatus, v reflect.Value, t reflect.Type, tg tag) error {
if _, isInline := tg.Modifiers["inline"]; isInline {
val, ok := s.GetValue(d.env)
if !ok {
return nil
}
elements := d.arrSep.Split(val, -1)
slice := reflect.MakeSlice(t, 0, len(elements))
for _, s := range elements {
mv := reflect.New(t.Elem())
err := d.decodeField(mv.Elem(), s)
if err != nil {
return err
}
slice = reflect.Append(slice, mv.Elem())
}
v.Set(slice)
return nil
}
index := s.GetIndex()
slice := reflect.MakeSlice(t, 0, len(index))
for _, i := range index {
mv := reflect.New(t.Elem())
err := d.decodeElement(s, mv.Elem(), mv.Elem().Type(), tag{Name: strconv.Itoa(i), Modifiers: tg.Modifiers})
if err != nil {
return err
}
slice = reflect.Append(slice, mv.Elem())
}
v.Set(slice)
return nil
}
示例2: 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(count int) interface{} {
if count <= 0 || p.left() == 0 {
return reflect.MakeSlice(reflect.SliceOf(p.value.Type()), 0, 0).Interface()
}
cap := p.left()
if cap > count {
cap = count
}
result := reflect.MakeSlice(reflect.SliceOf(p.value.Type()), cap, cap)
length := 0
for index := 0; index < cap; index++ {
if _, ok := p.Next(); ok {
length++
list := p.copySliceValue()
result.Index(index).Set(list)
}
}
list := reflect.MakeSlice(result.Type(), length, length)
reflect.Copy(list, result)
return list.Interface()
}
示例3: mapForm
// Takes values from the form data and puts them into a struct
func mapForm(formStruct reflect.Value, form map[string][]string,
formfile map[string][]*multipart.FileHeader, errors Errors) {
if formStruct.Kind() == reflect.Ptr {
formStruct = formStruct.Elem()
}
typ := formStruct.Type()
for i := 0; i < typ.NumField(); i++ {
typeField := typ.Field(i)
structField := formStruct.Field(i)
if typeField.Type.Kind() == reflect.Ptr && typeField.Anonymous {
structField.Set(reflect.New(typeField.Type.Elem()))
mapForm(structField.Elem(), form, formfile, errors)
if reflect.DeepEqual(structField.Elem().Interface(), reflect.Zero(structField.Elem().Type()).Interface()) {
structField.Set(reflect.Zero(structField.Type()))
}
} else if typeField.Type.Kind() == reflect.Struct {
mapForm(structField, form, formfile, errors)
}
inputFieldName := parseFormName(typeField.Name, typeField.Tag.Get("form"))
if len(inputFieldName) == 0 || !structField.CanSet() {
continue
}
inputValue, exists := form[inputFieldName]
if exists {
numElems := len(inputValue)
if structField.Kind() == reflect.Slice && numElems > 0 {
sliceOf := structField.Type().Elem().Kind()
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for i := 0; i < numElems; i++ {
setWithProperType(sliceOf, inputValue[i], slice.Index(i), inputFieldName, errors)
}
formStruct.Field(i).Set(slice)
} else {
setWithProperType(typeField.Type.Kind(), inputValue[0], structField, inputFieldName, errors)
}
continue
}
inputFile, exists := formfile[inputFieldName]
if !exists {
continue
}
fhType := reflect.TypeOf((*multipart.FileHeader)(nil))
numElems := len(inputFile)
if structField.Kind() == reflect.Slice && numElems > 0 && structField.Type().Elem() == fhType {
slice := reflect.MakeSlice(structField.Type(), numElems, numElems)
for i := 0; i < numElems; i++ {
slice.Index(i).Set(reflect.ValueOf(inputFile[i]))
}
structField.Set(slice)
} else if structField.Type() == fhType {
structField.Set(reflect.ValueOf(inputFile[0]))
}
}
}
示例4: convertSlice
func convertSlice(in interface{}, val reflect.Value) *ConfigError {
if iary, ok := in.([]interface{}); !ok {
return &ConfigError{ErrInvalidType, ""}
} else if len(iary) > 0 {
var convertor ConvertFunc
ele := reflect.MakeSlice(val.Type(), 1, 1).Index(0)
convertor = convertFuncs.get(ele)
if convertor == nil {
return &ConfigError{ErrInvalidType, ""}
}
ary := reflect.MakeSlice(val.Type(), len(iary), len(iary))
for i, ele := range iary {
if err := convertor(ele, ary.Index(i)); err != nil {
if len(err.Field) > 0 {
err.Field = fmt.Sprintf("[%d].%s", i, err.Field)
} else {
err.Field = fmt.Sprintf("[%d]", i)
}
return err
}
}
val.Set(ary)
}
return nil
}
示例5: addSliceItem
// Adds item to a slice.
func addSliceItem(elem *reflect.Value, section, key, value string) (err error) {
//fmt.Printf("\tADD SLICE ITEM: [%s] %s %s\n", section, key, value)
section = toFieldName(section)
key = toFieldName(key)
field, err := findField(elem, section, key)
if err != nil {
return err
}
if err = isFieldModifiable(field, key, reflect.Slice); err != nil {
return
}
// First on consecutive add ?
if field.IsNil() {
// First add
field.Set(reflect.MakeSlice(field.Type(), 1, 1))
field.Index(0).Set( //reflect.ValueOf(value))
reflect.ValueOf(value).Convert(field.Type().Elem()))
} else {
// Consecutive adds copy slice and increase its size by 1
l := field.Len()
fieldNew := reflect.MakeSlice(field.Type(), l+1, l+1)
for i := 0; i < l; i++ {
fieldNew.Index(i).Set(field.Index(i))
}
fieldNew.Index(l).Set(
reflect.ValueOf(value).Convert(field.Type().Elem()))
field.Set(fieldNew)
}
return
}
示例6: SplitByEach
// SplitByEach splits a list into multiple lists. Each size of lists must be up to `each`
// e.g:
// SplitByEach([]int{0,1,2,3,4}, 2)
// -> [][]int{[]int{0,1}, []int{2, 3}, []int{4}}
func SplitByEach(list interface{}, eachSize int) interface{} {
a := reflect.ValueOf(list)
assertSlice(a)
// create and allocate lists
bucketType := a.Type()
bucketListType := reflect.SliceOf(bucketType)
tailSize := a.Len() % eachSize
bucketListLen := a.Len()/eachSize + tailSize%2
bucketList := reflect.MakeSlice(bucketListType, bucketListLen, bucketListLen)
for i := 0; i < bucketListLen-1; i++ {
bucket := bucketList.Index(i)
bucket.Set(reflect.MakeSlice(bucketType, eachSize, eachSize))
offset := i * eachSize
for j := 0; j < eachSize; j++ {
bucket.Index(j).Set(a.Index(offset + j))
}
}
if tailSize == 0 {
tailSize = eachSize
}
bucket := bucketList.Index(bucketListLen - 1)
bucket.Set(reflect.MakeSlice(bucketType, tailSize, tailSize))
offset := (bucketListLen - 1) * eachSize
for j := 0; j < tailSize; j++ {
bucket.Index(j).Set(a.Index(offset + j))
}
return bucketList.Interface()
}
示例7: DecoderContainer
// DecoderContainer supports common cases for decoding into a nil
// interface{} depending on the context.
//
// When decoding into a nil interface{}, the following rules apply as we have
// to make assumptions about the specific types you want.
// - Maps are decoded as map[interface{}]interface{}
// unless you provide a default map type when creating your decoder.
// option: MapType
// - Lists are always decoded as []interface{}
// unless you provide a default slice type when creating your decoder.
// option: SliceType
// - raw bytes are decoded into []byte or string depending on setting of:
// option: BytesStringMapValue (if within a map value, use this setting)
// option: BytesStringSliceElement (else if within a slice, use this setting)
// option: BytesStringLiteral (else use this setting)
func (d SimpleDecoderContainerResolver) DecoderContainer(
parentcontainer reflect.Value, parentkey interface{},
length int, ct ContainerType) (rvn reflect.Value) {
switch ct {
case ContainerMap:
if d.MapType != nil {
rvn = reflect.MakeMap(d.MapType)
} else {
rvn = reflect.MakeMap(mapIntfIntfTyp)
}
case ContainerList:
if d.SliceType != nil {
rvn = reflect.MakeSlice(d.SliceType, length, length)
} else {
rvn = reflect.MakeSlice(intfSliceTyp, length, length)
}
case ContainerRawBytes:
rk := parentcontainer.Kind()
if (rk == reflect.Invalid && d.BytesStringLiteral) ||
(rk == reflect.Slice && d.BytesStringSliceElement) ||
(rk == reflect.Map && d.BytesStringMapValue) {
rvm := ""
rvn = reflect.ValueOf(&rvm)
} else {
rvn = reflect.MakeSlice(byteSliceTyp, length, length)
}
}
// fmt.Printf("DecoderContainer: %T, %v\n", rvn.Interface(), rvn.Interface())
return
}
示例8: 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
}
}
示例9: _partition
func _partition(values []reflect.Value) []reflect.Value {
slice := interfaceToValue(values[0])
fn := values[1]
var t, f reflect.Value
if values[0].Kind() == reflect.Interface {
t = reflect.ValueOf(make([]interface{}, 0))
f = reflect.ValueOf(make([]interface{}, 0))
} else {
t = reflect.MakeSlice(slice.Type(), 0, 0)
f = reflect.MakeSlice(slice.Type(), 0, 0)
}
for i := 0; i < slice.Len(); i++ {
e := slice.Index(i)
r := fn.Call([]reflect.Value{e})
if r[0].Bool() {
t = reflect.Append(t, e)
} else {
f = reflect.Append(f, e)
}
}
return []reflect.Value{t, f}
}
示例10: kSlice
func (f *decFnInfo) kSlice(rv reflect.Value) {
// A slice can be set from a map or array in stream.
currEncodedType := f.dd.currentEncodedType()
switch currEncodedType {
case valueTypeBytes, valueTypeString:
if f.ti.rtid == uint8SliceTypId || f.ti.rt.Elem().Kind() == reflect.Uint8 {
if bs2, changed2 := f.dd.decodeBytes(rv.Bytes()); changed2 {
rv.SetBytes(bs2)
}
return
}
}
if shortCircuitReflectToFastPath && rv.CanAddr() {
switch f.ti.rtid {
case intfSliceTypId:
f.d.decSliceIntf(rv.Addr().Interface().(*[]interface{}), currEncodedType, f.array)
return
case uint64SliceTypId:
f.d.decSliceUint64(rv.Addr().Interface().(*[]uint64), currEncodedType, f.array)
return
case int64SliceTypId:
f.d.decSliceInt64(rv.Addr().Interface().(*[]int64), currEncodedType, f.array)
return
case strSliceTypId:
f.d.decSliceStr(rv.Addr().Interface().(*[]string), currEncodedType, f.array)
return
}
}
containerLen, containerLenS := decContLens(f.dd, currEncodedType)
// an array can never return a nil slice. so no need to check f.array here.
if rv.IsNil() {
rv.Set(reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS))
}
if containerLen == 0 {
return
}
if rvcap, rvlen := rv.Len(), rv.Cap(); containerLenS > rvcap {
if f.array { // !rv.CanSet()
decErr(msgDecCannotExpandArr, rvcap, containerLenS)
}
rvn := reflect.MakeSlice(f.ti.rt, containerLenS, containerLenS)
if rvlen > 0 {
reflect.Copy(rvn, rv)
}
rv.Set(rvn)
} else if containerLenS > rvlen {
rv.SetLen(containerLenS)
}
for j := 0; j < containerLenS; j++ {
f.d.decodeValue(rv.Index(j))
}
}
示例11: GetSliceConvert
func GetSliceConvert(c *Convertors) func(*Params, string, reflect.Type) reflect.Value {
return func(p *Params, name string, typ reflect.Type) reflect.Value {
var values ItemByIndex
var maxIdx = 0
var noindex = 0
processItem := func(key string, vals []string) {
var idx int
var err error
if !strings.HasPrefix(key, name+"[") {
return
}
lIdx, rIdx := len(name), strings.IndexByte(key[len(name):], ']')+len(name)
if rIdx == -1 {
//not have ] char in key
return
}
//process e.g. name[]
if lIdx == rIdx-1 {
noindex++
goto END
}
idx, err = strconv.Atoi(key[lIdx+1 : rIdx])
if err != nil {
return
}
if idx > maxIdx {
maxIdx = idx
}
END:
value := c.Convert(p, key[:rIdx+1], typ.Elem())
values = append(values, &item{idx, value})
}
for k, vals := range p.Values {
processItem(k, vals)
}
//if array len small than 10000, keep index
if maxIdx < 10000 {
slice := reflect.MakeSlice(typ, maxIdx+1, maxIdx+noindex+1)
for _, val := range values {
if val.index > -1 {
slice.Index(val.index).Set(val.value)
} else {
slice = reflect.Append(slice, val.value)
}
}
return slice
}
sort.Sort(values)
slice := reflect.MakeSlice(typ, 0, len(values))
for _, val := range values {
slice = reflect.Append(slice, val.value)
}
return slice
}
}
示例12: 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()
}
示例13: MakeSlice
// MakeSlice creates a new, empty slice value for the given type. The
// parameter is expected to be an exemplar of the slice type to make.
func MakeSlice(i interface{}) reflect.Value {
ut := Indirect(i).Type()
if ut.Kind() == reflect.Slice {
return reflect.MakeSlice(ut, 0, 0)
}
st := reflect.SliceOf(ut)
return reflect.MakeSlice(st, 0, 0)
}
示例14: array
//FIXME: fix when v is invalid
// type(1) | name length(1) | item size(4) | raw name bytes | 0x00
// | element number(4) | element1 | ... | elementN
func (d *decodeState) array(v reflect.Value) {
d.off += 1 // type
klen := int(Int8(d.data[d.off:]))
d.off += 1 // name length
// vlen := int(Int32(d.data[d.off:]))
d.off += 4 // content length
//var key string
if klen > 0 {
key := d.data[d.off : d.off+klen-1]
d.off += klen
v = fieldByTag(v, key)
u, pv := d.indirect(v, false)
if u != nil {
d.off -= 1 + 1 + 4 + klen
if err := u.UnmarshalMCPACK(d.next()); err != nil {
d.error(err)
}
return
}
v = pv
}
n := int(Int32(d.data[d.off:]))
d.off += 4 // member number
if v.Kind() == reflect.Slice {
if n > v.Cap() {
newv := reflect.MakeSlice(v.Type(), n, n)
v.Set(newv)
}
v.SetLen(n)
}
for i := 0; i < n; i++ {
if i < v.Len() {
d.value(v.Index(i))
} else {
d.value(reflect.Value{})
}
}
if n < v.Len() {
if v.Kind() == reflect.Array {
z := reflect.Zero(v.Type().Elem())
for i := 0; i < v.Len(); i++ {
v.Index(i).Set(z)
}
}
}
if n == 0 && v.Kind() == reflect.Slice {
v.Set(reflect.MakeSlice(v.Type(), 0, 0))
}
}
示例15: unmarshalSlice
// unmarshal for when rv's Kind is Slice
func unmarshalSlice(av *dynamodb.AttributeValue, rv reflect.Value) error {
switch {
case av.B != nil:
rv.SetBytes(av.B)
return nil
case av.L != nil:
slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
for _, innerAV := range av.L {
innerRV := reflect.New(rv.Type().Elem()).Elem()
if err := unmarshalReflect(innerAV, innerRV); err != nil {
return err
}
slicev = reflect.Append(slicev, innerRV)
}
rv.Set(slicev)
return nil
// there's probably a better way to do these
case av.BS != nil:
slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
for _, b := range av.BS {
innerRV := reflect.New(rv.Type().Elem()).Elem()
if err := unmarshalReflect(&dynamodb.AttributeValue{B: b}, innerRV); err != nil {
return err
}
slicev = reflect.Append(slicev, innerRV)
}
rv.Set(slicev)
return nil
case av.SS != nil:
slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
for _, str := range av.SS {
innerRV := reflect.New(rv.Type().Elem()).Elem()
if err := unmarshalReflect(&dynamodb.AttributeValue{S: str}, innerRV); err != nil {
return err
}
slicev = reflect.Append(slicev, innerRV)
}
rv.Set(slicev)
return nil
case av.NS != nil:
slicev := reflect.MakeSlice(rv.Type(), 0, len(av.L))
for _, n := range av.NS {
innerRV := reflect.New(rv.Type().Elem()).Elem()
if err := unmarshalReflect(&dynamodb.AttributeValue{N: n}, innerRV); err != nil {
return err
}
slicev = reflect.Append(slicev, innerRV)
}
rv.Set(slicev)
return nil
}
return errors.New("dynamo: unmarshal slice: B, L, BS, SS, NS are nil")
}