当前位置: 首页>>代码示例>>Golang>>正文


Golang reflect.SliceOf函数代码示例

本文整理汇总了Golang中reflect.SliceOf函数的典型用法代码示例。如果您正苦于以下问题:Golang SliceOf函数的具体用法?Golang SliceOf怎么用?Golang SliceOf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了SliceOf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: First

func (q *queryT) First() error {
	q.op = otQuery
	l := 1
	q.limit = &l

	rv := reflect.ValueOf(q.inst)
	rvi := reflect.Indirect(rv)

	if rvi.Kind() == reflect.Struct {
		dv := reflect.New(reflect.SliceOf(rvi.Type()))
		dv.Elem().Set(reflect.MakeSlice(reflect.SliceOf(rvi.Type()), 0, 1))

		if b, err := defaultClient.doRequest(q); err != nil {
			return err
		} else if err := handleResponse(b, dv.Interface()); err != nil {
			return err
		}

		dvi := reflect.Indirect(dv)
		if dvi.Len() > 0 {
			rv.Elem().Set(dv.Elem().Index(0))
		}
	} else if rvi.Kind() == reflect.Slice {
		if b, err := defaultClient.doRequest(q); err != nil {
			return err
		} else if err := handleResponse(b, q.inst); err != nil {
			return err
		}
	} else {
		return fmt.Errorf("expected struct or slice, got %s", rvi.Kind())
	}
	return nil
}
开发者ID:BoldSoftStudios,项目名称:parse,代码行数:33,代码来源:query.go

示例2: FindAll

// FindAll finds the first len(values) matches of the regex in s.
// valuesSlice must be a slice of structs (or pointers to structs) of the same type as passed to Compile.
// Nil elements are skipped.
// Returns the number of matches found. Note that not all valuesSlice[:n] may have been
// set from the regexp, if some of the matches didn't match on any of the fields.
//
// Calling FindAll with a slice of len 1 is basically same as passing a pointer to that struct
// to Find().
func (r *TypedRegexp) FindAll(s string, valuesSlice interface{}) (n int) {
	t := reflect.TypeOf(r.captureGroups)
	slice := reflect.ValueOf(valuesSlice)

	sliceType := slice.Type()
	expectedType := reflect.SliceOf(t)
	expectedPtrType := reflect.SliceOf(reflect.PtrTo(t))
	if sliceType != expectedType && sliceType != expectedPtrType {
		panic(fmt.Errorf("values must be %s or %s, is %s", expectedType, expectedPtrType, sliceType))
	}

	if slice.Len() == 0 {
		return 0
	}

	allSubmatches := r.pattern.FindAllStringSubmatch(s, slice.Len())
	n = len(allSubmatches)
	for submatchIndex, submatches := range allSubmatches {
		v := slice.Index(submatchIndex)

		if v.Kind() == reflect.Ptr && v.IsNil() {
			continue
		}

		r.assignSubmatchesToStruct(submatches, &v)
		//		slice.Index(submatchIndex).Set(v)
	}
	return
}
开发者ID:zach-klippenstein,项目名称:go-typedregexp,代码行数:37,代码来源:typedregexp.go

示例3: getColumnsAsScope

func (scope *Scope) getColumnsAsScope(column string) *Scope {
	values := scope.IndirectValue()
	switch values.Kind() {
	case reflect.Slice:
		modelType := values.Type().Elem()
		if modelType.Kind() == reflect.Ptr {
			modelType = modelType.Elem()
		}
		fieldStruct, _ := modelType.FieldByName(column)
		var columns reflect.Value
		if fieldStruct.Type.Kind() == reflect.Slice || fieldStruct.Type.Kind() == reflect.Ptr {
			columns = reflect.New(reflect.SliceOf(reflect.PtrTo(fieldStruct.Type.Elem()))).Elem()
		} else {
			columns = reflect.New(reflect.SliceOf(reflect.PtrTo(fieldStruct.Type))).Elem()
		}
		for i := 0; i < values.Len(); i++ {
			column := reflect.Indirect(values.Index(i)).FieldByName(column)
			if column.Kind() == reflect.Ptr {
				column = column.Elem()
			}
			if column.Kind() == reflect.Slice {
				for i := 0; i < column.Len(); i++ {
					columns = reflect.Append(columns, column.Index(i).Addr())
				}
			} else {
				columns = reflect.Append(columns, column.Addr())
			}
		}
		return scope.New(columns.Interface())
	case reflect.Struct:
		return scope.New(values.FieldByName(column).Addr().Interface())
	}
	return nil
}
开发者ID:useidel,项目名称:notary,代码行数:34,代码来源:preload.go

示例4: 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
}
开发者ID:calmh,项目名称:ghbinmirror,代码行数:36,代码来源:github.go

示例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(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()
}
开发者ID:Coderrob,项目名称:permutation,代码行数:28,代码来源:permutation.go

示例6: GroupBy

func (p Pages) GroupBy(key string, order ...string) (PagesGroup, error) {
	if len(p) < 1 {
		return nil, nil
	}

	direction := "asc"

	if len(order) > 0 && (strings.ToLower(order[0]) == "desc" || strings.ToLower(order[0]) == "rev" || strings.ToLower(order[0]) == "reverse") {
		direction = "desc"
	}

	ppt := reflect.TypeOf(&Page{})
	ft, ok := ppt.Elem().FieldByName(key)
	if !ok {
		return nil, errors.New("No such field in Page struct")
	}
	tmp := reflect.MakeMap(reflect.MapOf(ft.Type, reflect.SliceOf(ppt)))

	for _, e := range p {
		ppv := reflect.ValueOf(e)
		fv := ppv.Elem().FieldByName(key)
		if !tmp.MapIndex(fv).IsValid() {
			tmp.SetMapIndex(fv, reflect.MakeSlice(reflect.SliceOf(ppt), 0, 0))
		}
		tmp.SetMapIndex(fv, reflect.Append(tmp.MapIndex(fv), ppv))
	}

	var r []PageGroup
	for _, k := range sortKeys(tmp.MapKeys(), direction) {
		r = append(r, PageGroup{Key: k.Interface(), Pages: tmp.MapIndex(k).Interface().([]*Page)})
	}

	return r, nil
}
开发者ID:juicelink,项目名称:hugo,代码行数:34,代码来源:pageGroup.go

示例7: GroupBy

func (p Pages) GroupBy(key, order string) ([]PageGroup, error) {
	if len(p) < 1 {
		return nil, nil
	}

	if order != "asc" && order != "desc" {
		return nil, errors.New("order argument must be 'asc' or 'desc'")
	}

	ppt := reflect.TypeOf(&Page{})
	ft, ok := ppt.Elem().FieldByName(key)
	if !ok {
		return nil, errors.New("No such field in Page struct")
	}
	tmp := reflect.MakeMap(reflect.MapOf(ft.Type, reflect.SliceOf(ppt)))

	for _, e := range p {
		ppv := reflect.ValueOf(e)
		fv := ppv.Elem().FieldByName(key)
		if !tmp.MapIndex(fv).IsValid() {
			tmp.SetMapIndex(fv, reflect.MakeSlice(reflect.SliceOf(ppt), 0, 0))
		}
		tmp.SetMapIndex(fv, reflect.Append(tmp.MapIndex(fv), ppv))
	}

	var r []PageGroup
	for _, k := range sortKeys(tmp.MapKeys(), order) {
		r = append(r, PageGroup{Key: k.Interface(), Data: tmp.MapIndex(k).Interface().([]*Page)})
	}

	return r, nil
}
开发者ID:hugo-alves,项目名称:hugo,代码行数:32,代码来源:pageGroup.go

示例8: 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()
}
开发者ID:michaelzhd,项目名称:CMPE273,代码行数:61,代码来源:permutation.go

示例9: newPool

func newPool(size int, tp reflect.Type) *pool {
	return &pool{
		size: size,
		cur:  0,
		pool: reflect.MakeSlice(reflect.SliceOf(tp), size, size),
		tp:   reflect.SliceOf(tp),
	}
}
开发者ID:GOGOGO7,项目名称:tango,代码行数:8,代码来源:pool.go

示例10: newPool

func newPool(size int, tp reflect.Type) *pool {
	return &pool{
		size: size,
		cur:  0,
		pool: reflect.MakeSlice(reflect.SliceOf(tp), 0, 0), // init for don't allocate memory
		tp:   reflect.SliceOf(tp),
		stp:  tp,
	}
}
开发者ID:yangxiaoyi-git,项目名称:tango,代码行数:9,代码来源:pool.go

示例11: FindManyByField

func (sr *SQL) FindManyByField(r *Request, rp RequestParams, field, value string) ([]*Record, error) {
	p := rp.Paginator
	vs := reflect.New(reflect.SliceOf(reflect.PtrTo(sr.Type))).Interface()
	field, err := sr.GetTableFieldFromStructField(field)
	if err != nil {
		return nil, err
	}
	offset_and_limit := ""
	if p.ShouldPaginate {
		offset_and_limit = fmt.Sprintf("LIMIT %d OFFSET %d",
			p.MaxPerPage,
			p.CurPage*p.MaxPerPage,
		)
	}
	// TODO: find a way to parameterize field in this query
	// right now, field is always a trusted string, but some
	// later relationship behaviors might change that, and it's
	// better to be safe than sorry
	// dropping in ? instead of field does not work :/
	q := fmt.Sprintf("SELECT * FROM %s WHERE %s=? %s", sr.Table, field, offset_and_limit)
	r.API.Logger.Debugf("Query: %#v %#v\n", q, value)
	err = meddler.QueryAll(
		sr.DB,
		vs,
		q,
		value,
	)
	if err == sql.ErrNoRows {
		return nil, nil
	}
	r.API.Logger.Debugf("RES: %#v\n", vs)
	return sr.ConvertInterfaceSliceToRecordSlice(vs), err
}
开发者ID:liamzdenek,项目名称:go-jsonapi,代码行数:33,代码来源:SQL.go

示例12: toReflectType

// toReflectType converts the DataType to reflect.Type.
func toReflectType(dtype DataType) reflect.Type {
	switch dtype.Kind() {
	case BooleanKind:
		return reflect.TypeOf(true)
	case IntegerKind:
		return reflect.TypeOf(int(0))
	case NumberKind:
		return reflect.TypeOf(float64(0))
	case StringKind:
		return reflect.TypeOf("")
	case DateTimeKind:
		return reflect.TypeOf(time.Time{})
	case ObjectKind, UserTypeKind, MediaTypeKind:
		return reflect.TypeOf(map[string]interface{}{})
	case ArrayKind:
		return reflect.SliceOf(toReflectType(dtype.ToArray().ElemType.Type))
	case HashKind:
		hash := dtype.ToHash()
		// avoid complication: not allow object as the hash key
		var ktype reflect.Type
		if !hash.KeyType.Type.IsObject() {
			ktype = toReflectType(hash.KeyType.Type)
		} else {
			ktype = reflect.TypeOf([]interface{}{}).Elem()
		}
		return reflect.MapOf(ktype, toReflectType(hash.ElemType.Type))
	default:
		return reflect.TypeOf([]interface{}{}).Elem()
	}
}
开发者ID:ajoulie,项目名称:goa,代码行数:31,代码来源:types.go

示例13: 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()
}
开发者ID:speedland,项目名称:service,代码行数:34,代码来源:slice.go

示例14: GetAll

// GetAll fetches all items that we want to watch from the state.
func (b *allWatcherStateBacking) GetAll(all *multiwatcherStore) error {
	db, closer := b.st.newDB()
	defer closer()

	// TODO(rog) fetch collections concurrently?
	for _, c := range b.collectionByName {
		if c.subsidiary {
			continue
		}
		col, closer := db.GetCollection(c.name)
		defer closer()
		infoSlicePtr := reflect.New(reflect.SliceOf(c.infoType))
		if err := col.Find(nil).All(infoSlicePtr.Interface()); err != nil {
			return fmt.Errorf("cannot get all %s: %v", c.name, err)
		}
		infos := infoSlicePtr.Elem()
		for i := 0; i < infos.Len(); i++ {
			info := infos.Index(i).Addr().Interface().(backingEntityDoc)
			id := info.mongoId()
			err := info.updated(b.st, all, id)
			if err != nil {
				return errors.Annotatef(err, "failed to initialise backing for %s:%v", c.name, id)
			}
		}
	}
	return nil
}
开发者ID:claudiu-coblis,项目名称:juju,代码行数:28,代码来源:allwatcher.go

示例15: setSliceFieldValue

func (p *untypedParamBinder) setSliceFieldValue(target reflect.Value, defaultValue interface{}, data []string) error {
	if len(data) == 0 && p.parameter.Required && p.parameter.Default == nil {
		return errors.Required(p.Name, p.parameter.In)
	}
	defVal := reflect.Zero(target.Type())
	if defaultValue != nil {
		defVal = reflect.ValueOf(defaultValue)
	}
	if len(data) == 0 {
		target.Set(defVal)
		return nil
	}

	sz := len(data)
	value := reflect.MakeSlice(reflect.SliceOf(target.Type().Elem()), sz, sz)

	for i := 0; i < sz; i++ {
		if err := p.setFieldValue(value.Index(i), nil, data[i]); err != nil {
			return err
		}
	}

	target.Set(value)

	return nil
}
开发者ID:jason-xxl,项目名称:go-swagger,代码行数:26,代码来源:parameter.go


注:本文中的reflect.SliceOf函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。