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


Golang reflect.MapOf函数代码示例

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


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

示例1: 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

示例2: Uniq

func Uniq(source, selector interface{}) interface{} {
	if selector == nil {
		selector = func(value, _ interface{}) Facade {
			return Facade{reflect.ValueOf(value)}
		}
	}

	var mapRV reflect.Value
	var arrRV reflect.Value
	each(source, selector, func(resRV, valueRv, _ reflect.Value) bool {
		if !mapRV.IsValid() {
			mapRT := reflect.MapOf(resRV.Type(), reflect.TypeOf(false))
			mapRV = reflect.MakeMap(mapRT)

			arrRT := reflect.SliceOf(valueRv.Type())
			arrRV = reflect.MakeSlice(arrRT, 0, 0)
		}

		mapValueRV := mapRV.MapIndex(resRV)
		if !mapValueRV.IsValid() {
			mapRV.SetMapIndex(resRV, reflect.ValueOf(true))
			arrRV = reflect.Append(arrRV, valueRv)
		}
		return false
	})
	if mapRV.IsValid() {
		return arrRV.Interface()
	}

	return nil
}
开发者ID:ahl5esoft,项目名称:golang-underscore,代码行数:31,代码来源:uniq.go

示例3: Map

func (w *walker) Map(m reflect.Value) error {
	t := m.Type()
	newMap := reflect.MakeMap(reflect.MapOf(t.Key(), t.Elem()))
	w.cs = append(w.cs, newMap)
	w.valPush(newMap)
	return nil
}
开发者ID:svend,项目名称:terraform-provider-stingray,代码行数:7,代码来源:copystructure.go

示例4: GetReflectType

func (r *RuleWrapper) GetReflectType() (reflect.Type, error) {

	if r.Struct != nil && r.Struct.Interface {
		typ, ok := r.Parent.GetReflectInterface(r.Ctx)
		if !ok {
			return nil, kerr.New("QGUVEUTXAN", "Type interface for %s not found", r.Parent.Id.Value())
		}
		return typ, nil
	}

	if c, ok := r.Interface.(CollectionRule); ok {
		itemsRule := c.GetItemsRule()
		if itemsRule != nil {
			items := WrapRule(r.Ctx, itemsRule)
			itemsType, err := items.GetReflectType()
			if err != nil {
				return nil, kerr.Wrap("LMKEHHWHKL", err)
			}
			if r.Parent.NativeJsonType(r.Ctx) == J_MAP {
				return reflect.MapOf(reflect.TypeOf(""), itemsType), nil
			}
			return reflect.SliceOf(itemsType), nil
		}
	}

	typ, ok := r.Parent.GetReflectType(r.Ctx)
	if !ok {
		return nil, kerr.New("DLAJJPJDPL", "Type %s not found", r.Parent.Id.Value())
	}

	return typ, nil

}
开发者ID:kego,项目名称:ke,代码行数:33,代码来源:rule.go

示例5: 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

示例6: MakeMap

// MakeMap examines the key type from a Hash and create a map with builtin type if possible.
// The idea is to avoid generating map[interface{}]interface{}, which cannot be handled by json.Marshal.
func (h *Hash) MakeMap(pair map[interface{}]interface{}) interface{} {
	if !h.KeyType.Type.IsPrimitive() {
		// well, a type can't be handled by json.Marshal... not much we can do
		return pair
	}
	if len(pair) == 0 {
		// figure out the map type manually
		switch h.KeyType.Type.Kind() {
		case BooleanKind:
			return map[bool]interface{}{}
		case IntegerKind:
			return map[int]interface{}{}
		case NumberKind:
			return map[float64]interface{}{}
		case StringKind:
			return map[string]interface{}{}
		case DateTimeKind:
			return map[time.Time]interface{}{}
		default:
			return pair
		}
	}
	var newMap reflect.Value
	for key, value := range pair {
		rkey, rvalue := reflect.ValueOf(key), reflect.ValueOf(value)
		if !newMap.IsValid() {
			newMap = reflect.MakeMap(reflect.MapOf(rkey.Type(), rvalue.Type()))
		}
		newMap.SetMapIndex(rkey, rvalue)
	}
	return newMap.Interface()
}
开发者ID:DavyC,项目名称:goa,代码行数:34,代码来源:types.go

示例7: decode

func (d *mapAsMapDecoder) decode(dv, sv reflect.Value) {
	dt := dv.Type()
	dv.Set(reflect.MakeMap(reflect.MapOf(dt.Key(), dt.Elem())))

	var mapKey reflect.Value
	var mapElem reflect.Value

	keyType := dv.Type().Key()
	elemType := dv.Type().Elem()

	for _, sElemKey := range sv.MapKeys() {
		var dElemKey reflect.Value
		var dElemVal reflect.Value

		if !mapKey.IsValid() {
			mapKey = reflect.New(keyType).Elem()
		} else {
			mapKey.Set(reflect.Zero(keyType))
		}
		dElemKey = mapKey

		if !mapElem.IsValid() {
			mapElem = reflect.New(elemType).Elem()
		} else {
			mapElem.Set(reflect.Zero(elemType))
		}
		dElemVal = mapElem

		d.keyDec(dElemKey, sElemKey)
		d.elemDec(dElemVal, sv.MapIndex(sElemKey))

		dv.SetMapIndex(dElemKey, dElemVal)
	}
}
开发者ID:kakamessi99,项目名称:shipyard,代码行数:34,代码来源:decoder_types.go

示例8: 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

示例9: tysubst

// tysubst attempts to substitute all type variables within a single return
// type with their corresponding Go type from the type environment.
//
// tysubst will panic if a type variable is unbound, or if it encounters a
// type that cannot be dynamically created. Such types include arrays,
// functions and structs. (A limitation of the `reflect` package.)
func (rt returnType) tysubst(typ reflect.Type) reflect.Type {
	if tyname := tyvarName(typ); len(tyname) > 0 {
		if thetype, ok := rt.tyenv[tyname]; !ok {
			rt.panic("Unbound type variable %s.", tyname)
		} else {
			return thetype
		}
	}

	switch typ.Kind() {
	case reflect.Array:
		rt.panic("Cannot dynamically create Array types.")
	case reflect.Chan:
		return reflect.ChanOf(typ.ChanDir(), rt.tysubst(typ.Elem()))
	case reflect.Func:
		rt.panic("Cannot dynamically create Function types.")
	case reflect.Interface:
		rt.panic("TODO")
	case reflect.Map:
		return reflect.MapOf(rt.tysubst(typ.Key()), rt.tysubst(typ.Elem()))
	case reflect.Ptr:
		return reflect.PtrTo(rt.tysubst(typ.Elem()))
	case reflect.Slice:
		return reflect.SliceOf(rt.tysubst(typ.Elem()))
	case reflect.Struct:
		rt.panic("Cannot dynamically create Struct types.")
	case reflect.UnsafePointer:
		rt.panic("Cannot dynamically create unsafe.Pointer types.")
	}

	// We've covered all the composite types, so we're only left with
	// base types.
	return typ
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:40,代码来源:type-check.go

示例10: byOutputMap

func byOutputMap(iterable interface{}, field string, fn string, slices bool) (itr reflect.Value, f reflect.StructField, out reflect.Value, err error) {
	itr = reflect.ValueOf(iterable)
	if itr.Kind() != reflect.Slice && itr.Kind() != reflect.Array {
		err = fmt.Errorf("first argument to %s must be slice or array, not %T", fn, iterable)
		return
	}
	elem := itr.Type().Elem()
	s := elem
	for s.Kind() == reflect.Ptr {
		s = s.Elem()
	}
	if s.Kind() != reflect.Struct {
		err = fmt.Errorf("first argument to %s must contain structs or pointers to structs, not %v", fn, elem)
		return
	}
	var ok bool
	f, ok = s.FieldByName(field)
	if !ok {
		err = fmt.Errorf("type %v does not have a field named %q", elem, field)
		return
	}
	if slices {
		elem = reflect.SliceOf(elem)
	}
	mapType := reflect.MapOf(f.Type, elem)
	out = reflect.MakeMap(mapType)
	return
}
开发者ID:rainycape,项目名称:gondola,代码行数:28,代码来源:slice.go

示例11: goType

func goType(t *TypeInfo) reflect.Type {
	switch t.Type {
	case TypeVarchar, TypeAscii, TypeInet:
		return reflect.TypeOf(*new(string))
	case TypeBigInt, TypeCounter:
		return reflect.TypeOf(*new(int64))
	case TypeTimestamp:
		return reflect.TypeOf(*new(time.Time))
	case TypeBlob:
		return reflect.TypeOf(*new([]byte))
	case TypeBoolean:
		return reflect.TypeOf(*new(bool))
	case TypeFloat:
		return reflect.TypeOf(*new(float32))
	case TypeDouble:
		return reflect.TypeOf(*new(float64))
	case TypeInt:
		return reflect.TypeOf(*new(int))
	case TypeDecimal:
		return reflect.TypeOf(*new(*inf.Dec))
	case TypeUUID, TypeTimeUUID:
		return reflect.TypeOf(*new(UUID))
	case TypeList, TypeSet:
		return reflect.SliceOf(goType(t.Elem))
	case TypeMap:
		return reflect.MapOf(goType(t.Key), goType(t.Elem))
	case TypeVarint:
		return reflect.TypeOf(*new(*big.Int))
	default:
		return nil
	}
}
开发者ID:dankennedy,项目名称:gocql,代码行数:32,代码来源:helpers.go

示例12: GroupBy

// If op is Operator of "[]T", type of f must be "func(T) T2".
// And GroupBy(f) returns value of "map[T2] []T"
func (op *Op) GroupBy(f interface{}) interface{} {
	vs := reflect.ValueOf(op.Slice)
	vf := reflect.ValueOf(f)

	tf := vf.Type()
	if tf.NumIn() != 1 {
		panic("Number of Argument must be 1")
	}
	if tf.NumOut() != 1 {
		panic("Number of return value must be 1")
	}

	tif := tf.In(0)
	tof := tf.Out(0)
	if tif != vs.Type().Elem() {
		panic("Mismatch function type")
	}

	len := vs.Len()
	vom := reflect.MakeMap(reflect.MapOf(tof, vs.Type()))
	for i := 0; i < len; i++ {
		v := vs.Index(i)
		vk := vf.Call([]reflect.Value{v})[0]
		vi := vom.MapIndex(vk)
		if vi.IsValid() {
			vom.SetMapIndex(vk, reflect.Append(vi, v))
		} else {
			vom.SetMapIndex(vk, reflect.Append(reflect.MakeSlice(vs.Type(), 0, len), v))
		}
	}

	return vom.Interface()
}
开发者ID:okzk,项目名称:slices,代码行数:35,代码来源:slices.go

示例13: groupByChan

func groupByChan(dataChan interface{}, f interface{}) (result interface{}) {
	fType := reflect.TypeOf(f)
	fInType := fType.In(0)
	fRetType := fType.Out(0)

	sliceOfFInTypes := reflect.SliceOf(fInType)
	resultValue := reflect.MakeMap(reflect.MapOf(fRetType, sliceOfFInTypes))

	fVal := reflect.ValueOf(f)
	chanValue := reflect.ValueOf(dataChan)
	value, ok := chanValue.Recv()
	for ok {
		idx := fVal.Call([]reflect.Value{value})[0]
		existingValue := resultValue.MapIndex(idx)
		if !existingValue.IsValid() {
			existingValue = reflect.MakeSlice(sliceOfFInTypes, 0, defaultCapacity)
		}
		existingValue = reflect.Append(existingValue, value)
		resultValue.SetMapIndex(idx, existingValue)
		value, ok = chanValue.Recv()
	}

	result = resultValue.Interface()
	return
}
开发者ID:benashford,项目名称:go-func,代码行数:25,代码来源:func.go

示例14: Memoize

// Memoize takes a function and returns a function of the same type. The
// returned function remembers the return value(s) of the function call.
// Any pointer values will be used as an address, so functions that modify
// their arguments or programs that modify returned values will not work.
//
// The returned function is safe to call from multiple goroutines if the
// original function is. Panics are handled, so calling panic from a function
// will call panic with the same value on future invocations with the same
// arguments.
//
// The arguments to the function must be of comparable types. Slices, maps,
// functions, and structs or arrays that contain slices, maps, or functions
// cause a runtime panic if they are arguments to a memoized function.
// See also: https://golang.org/ref/spec#Comparison_operators
//
// As a special case, variadic functions (func(x, y, ...z)) are allowed.
func Memoize(fn interface{}) interface{} {
	v := reflect.ValueOf(fn)
	t := v.Type()

	keyType := reflect.ArrayOf(t.NumIn(), interfaceType)
	cache := reflect.MakeMap(reflect.MapOf(keyType, valueType))
	var mtx sync.Mutex

	return reflect.MakeFunc(t, func(args []reflect.Value) (results []reflect.Value) {
		key := reflect.New(keyType).Elem()
		for i, v := range args {
			if i == len(args)-1 && t.IsVariadic() {
				a := reflect.New(reflect.ArrayOf(v.Len(), v.Type().Elem())).Elem()
				for j, l := 0, v.Len(); j < l; j++ {
					a.Index(j).Set(v.Index(j))
				}
				v = a
			}
			vi := v.Interface()
			key.Index(i).Set(reflect.ValueOf(&vi).Elem())
		}
		mtx.Lock()
		val := cache.MapIndex(key)
		if val.IsValid() {
			mtx.Unlock()
			c := val.Interface().(*call)
			<-c.wait
			if c.panicked.IsValid() {
				panic(c.panicked.Interface())
			}
			return c.results
		}
		w := make(chan struct{})
		c := &call{wait: w}
		cache.SetMapIndex(key, reflect.ValueOf(c))
		mtx.Unlock()

		panicked := true
		defer func() {
			if panicked {
				p := recover()
				c.panicked = reflect.ValueOf(p)
				close(w)
				panic(p)
			}
		}()

		if t.IsVariadic() {
			results = v.CallSlice(args)
		} else {
			results = v.Call(args)
		}
		panicked = false
		c.results = results
		close(w)

		return
	}).Interface()
}
开发者ID:BenLubar,项目名称:memoize,代码行数:75,代码来源:memoize.go

示例15: ExtendMap

func (s *Common) ExtendMap(i interface{}, with interface{}) {
	name := fmt.Sprintf("%v", i)
	m, ok := s.data[name]
	if !ok {
		m = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(with)))
	}
	m.SetMapIndex(reflect.ValueOf(name), reflect.ValueOf(with))
	s.data[name] = m
}
开发者ID:jacobmoe,项目名称:swagger,代码行数:9,代码来源:common.go


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