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


Golang Type.AssignableTo方法代码示例

本文整理汇总了Golang中reflect.Type.AssignableTo方法的典型用法代码示例。如果您正苦于以下问题:Golang Type.AssignableTo方法的具体用法?Golang Type.AssignableTo怎么用?Golang Type.AssignableTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在reflect.Type的用法示例。


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

示例1: Run

// Run recevies the argument and
func (m *mqueSub) Run(d interface{}, ctype reflect.Type) {
	if !m.has {
		for _, tm := range m.tms {
			tm.Call([]reflect.Value{})
		}

		return
	}

	var configVal reflect.Value

	if !ctype.AssignableTo(m.am) {
		if !ctype.ConvertibleTo(m.am) {
			return
		}

		vum := reflect.ValueOf(d)
		configVal = vum.Convert(m.am)
	} else {
		configVal = reflect.ValueOf(d)
	}

	for _, tm := range m.tms {
		tm.Call([]reflect.Value{configVal})
	}
}
开发者ID:influx6,项目名称:gu,代码行数:27,代码来源:mque.go

示例2: makeDecoder

func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) {
	kind := typ.Kind()
	switch {
	case typ == rawValueType:
		return decodeRawValue, nil
	case typ.Implements(decoderInterface):
		return decodeDecoder, nil
	case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(decoderInterface):
		return decodeDecoderNoPtr, nil
	case typ.AssignableTo(reflect.PtrTo(bigInt)):
		return decodeBigInt, nil
	case typ.AssignableTo(bigInt):
		return decodeBigIntNoPtr, nil
	case isUint(kind):
		return decodeUint, nil
	case kind == reflect.Bool:
		return decodeBool, nil
	case kind == reflect.String:
		return decodeString, nil
	case kind == reflect.Slice || kind == reflect.Array:
		return makeListDecoder(typ, tags)
	case kind == reflect.Struct:
		return makeStructDecoder(typ)
	case kind == reflect.Ptr:
		if tags.nilOK {
			return makeOptionalPtrDecoder(typ)
		}
		return makePtrDecoder(typ)
	case kind == reflect.Interface:
		return decodeInterface, nil
	default:
		return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
	}
}
开发者ID:expanse-project,项目名称:go-expanse,代码行数:34,代码来源:decode.go

示例3: makeWriter

// makeWriter creates a writer function for the given type.
func makeWriter(typ reflect.Type) (writer, error) {
	kind := typ.Kind()
	switch {
	case typ.Implements(encoderInterface):
		return writeEncoder, nil
	case kind != reflect.Ptr && reflect.PtrTo(typ).Implements(encoderInterface):
		return writeEncoderNoPtr, nil
	case kind == reflect.Interface:
		return writeInterface, nil
	case typ.AssignableTo(reflect.PtrTo(bigInt)):
		return writeBigIntPtr, nil
	case typ.AssignableTo(bigInt):
		return writeBigIntNoPtr, nil
	case isUint(kind):
		return writeUint, nil
	case kind == reflect.Bool:
		return writeBool, nil
	case kind == reflect.String:
		return writeString, nil
	case kind == reflect.Slice && isByte(typ.Elem()):
		return writeBytes, nil
	case kind == reflect.Array && isByte(typ.Elem()):
		return writeByteArray, nil
	case kind == reflect.Slice || kind == reflect.Array:
		return makeSliceWriter(typ)
	case kind == reflect.Struct:
		return makeStructWriter(typ)
	case kind == reflect.Ptr:
		return makePtrWriter(typ)
	default:
		return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ)
	}
}
开发者ID:este-xx,项目名称:go-expanse,代码行数:34,代码来源:encode.go

示例4: mustBeCompatible

func mustBeCompatible(a, b reflect.Type) {
	if !a.ConvertibleTo(b) || !a.AssignableTo(b) {
		panic(errors.New(fmt.Sprintf(
			"Types '%v' and '%v' is not compatile to each other! "+
				"It is no possible to make a swap function that "+
				"return or receive different kinds of objects!", a.Name(), b.Name())))
	}
}
开发者ID:darciopacifico,项目名称:enablecache,代码行数:8,代码来源:cache_aop_utils.go

示例5: assignable

func assignable(to, from reflect.Type) bool {
	if from == nil {
		switch to.Kind() {
		case reflect.Chan, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Func:
			return true
		}
		return false
	}
	return from.AssignableTo(to)
}
开发者ID:langxj,项目名称:gxui,代码行数:10,代码来源:event_base.go

示例6: CanRun

// CanRun returns whether the argument can be used with this subscriber.
func (m *mqueSub) CanRun(d reflect.Type) bool {
	if !d.AssignableTo(m.am) {
		// if d.ConvertibleTo(m.am) {
		// 	return true
		// }

		return false
	}

	return true
}
开发者ID:influx6,项目名称:gu,代码行数:12,代码来源:mque.go

示例7: CanSetForType

// CanSetForType checks if a val reflect.Type can be used for the target type.
// It returns true bool, where the first returns if the value can be used and if
// it must be converted into the type first.
func CanSetForType(target, val reflect.Type) (canSet bool, mustConvert bool) {
	if val.AssignableTo(target) {
		canSet = true
		return
	}

	if val.ConvertibleTo(target) {
		canSet = true
		mustConvert = true
		return
	}

	return
}
开发者ID:influx6,项目名称:gu,代码行数:17,代码来源:reflection.go

示例8: unmarshalToType

func unmarshalToType(typ reflect.Type, value string) (val interface{}, err error) {
	// If we get a pointer in, we'll return a pointer out
	if typ.Kind() == reflect.Ptr {
		val = reflect.New(typ.Elem()).Interface()
	} else {
		val = reflect.New(typ).Interface()
	}
	defer func() {
		if err == nil && typ.Kind() != reflect.Ptr {
			val = reflect.Indirect(reflect.ValueOf(val)).Interface()
		}
	}()

	// If we can just assign the value, return the value
	if typ.AssignableTo(reflect.TypeOf(value)) {
		return value, nil
	}

	// Try Unmarshalers
	if um, ok := val.(encoding.TextUnmarshaler); ok {
		if err = um.UnmarshalText([]byte(value)); err == nil {
			return val, nil
		}
	}
	if um, ok := val.(json.Unmarshaler); ok {
		if err = um.UnmarshalJSON([]byte(value)); err == nil {
			return val, nil
		}
	}

	// Try conversion
	if typ.ConvertibleTo(reflect.TypeOf(value)) {
		return reflect.ValueOf(value).Convert(typ).Interface(), nil
	}

	// Try JSON
	if err = json.Unmarshal([]byte(value), val); err == nil {
		return val, nil
	}

	// Return error if we have one
	if err != nil {
		return nil, err
	}

	return val, fmt.Errorf("No way to unmarshal \"%s\" to %s", value, typ.Name())
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:47,代码来源:decoder.go

示例9: check

func (s *schemaField) check(ft reflect.Type, v interface{}) error {
	t := reflect.TypeOf(v)
	if !ft.AssignableTo(t) {
		if !ft.ConvertibleTo(t) {
			return fmt.Errorf("type %s (%v) cannot be converted to %T", ft.Name(), ft.Kind(), t.Name())
		}

		s.marshalType = t
	}

	if !t.AssignableTo(ft) {
		if !t.ConvertibleTo(ft) {
			return fmt.Errorf("type %s (%v) cannot be converted to %T", t.Name(), t.Kind(), ft.Name())
		}

		s.unmarshalType = ft
	}
	return nil
}
开发者ID:pkf,项目名称:ql,代码行数:19,代码来源:introspection.go

示例10: typeConv

// converts in to an expression of type OutT.
// also serves as type check (not convertible == type error)
// pos is used for error message on impossible conversion.
func typeConv(pos token.Pos, in Expr, outT reflect.Type) Expr {
	inT := in.Type()
	switch {
	default:
		panic(err(pos, "type mismatch: can not use type", inT, "as", outT))

	// treat 'void' (type nil) separately:
	case inT == nil && outT != nil:
		panic(err(pos, "void used as value"))
	case inT != nil && outT == nil:
		panic("script internal bug: void input type")

	// strict go conversions:
	case inT == outT:
		return in
	case inT.AssignableTo(outT):
		return in

	// extra conversions for ease-of-use:
	// int -> float64
	case outT == float64_t && inT == int_t:
		return &intToFloat64{in}

	// float64 -> int
	case outT == int_t && inT == float64_t:
		return &float64ToInt{in}

	case outT == float64_t && inT.AssignableTo(ScalarIf_t):
		return &getScalar{in.Eval().(ScalarIf)}
	case outT == float64_t && inT.AssignableTo(VectorIf_t):
		return &getVector{in.Eval().(VectorIf)}

	// magical expression -> function conversions
	case inT == float64_t && outT.AssignableTo(ScalarFunction_t):
		return &scalFn{in}
	case inT == int_t && outT.AssignableTo(ScalarFunction_t):
		return &scalFn{&intToFloat64{in}}
	case inT == vector_t && outT.AssignableTo(VectorFunction_t):
		return &vecFn{in}
	case inT == bool_t && outT == func_bool_t:
		return &boolToFunc{in}
	}
}
开发者ID:callistoaz,项目名称:3,代码行数:46,代码来源:typeconv.go

示例11: isDurationField

func isDurationField(t reflect.Type) bool {
	return t.AssignableTo(durationType)
}
开发者ID:remeh,项目名称:reddit-audiences,代码行数:3,代码来源:envconfig.go

示例12: unmarshalValue

func (state *unmarshalState) unmarshalValue(cfObj cfTypeRef, v reflect.Value) error {
	vType := v.Type()
	var unmarshaler Unmarshaler
	if u, ok := v.Interface().(Unmarshaler); ok {
		unmarshaler = u
	} else if vType.Kind() != reflect.Ptr && vType.Name() != "" && v.CanAddr() {
		// matching the encoding/json behavior here
		// If v is a named type and is addressable, check its address for Unmarshaler.
		vA := v.Addr()
		if u, ok := vA.Interface().(Unmarshaler); ok {
			unmarshaler = u
		}
	}
	if unmarshaler != nil {
		// flip over to the dumb conversion routine so we have something to give UnmarshalPlist()
		plist, err := convertCFTypeToInterface(cfObj)
		if err != nil {
			return err
		}
		if vType.Kind() == reflect.Ptr && v.IsNil() {
			v.Set(reflect.New(vType.Elem()))
			unmarshaler = v.Interface().(Unmarshaler)
		}
		return unmarshaler.UnmarshalPlist(plist)
	}
	if vType.Kind() == reflect.Ptr {
		if v.IsNil() {
			v.Set(reflect.New(vType.Elem()))
		}
		return state.unmarshalValue(cfObj, v.Elem())
	}
	typeID := C.CFGetTypeID(C.CFTypeRef(cfObj))
	vSetter := v      // receiver of any Set* calls
	vAddr := v.Addr() // used for re-setting v for maps/slices
	if vType.Kind() == reflect.Interface {
		if v.IsNil() {
			// pick an appropriate type based on the cfobj
			var typ reflect.Type
			if typeID == cfNumberTypeID {
				typ = cfNumberTypeToType(C.CFNumberGetType(C.CFNumberRef(cfObj)))
			} else {
				var ok bool
				typ, ok = cfTypeMap[typeID]
				if !ok {
					return &UnknownCFTypeError{typeID}
				}
			}
			if !typ.AssignableTo(vType) {
				// v must be some interface that our object doesn't conform to
				state.recordError(&UnmarshalTypeError{cfTypeNames[typeID], vType})
				return nil
			}
			vSetter.Set(reflect.Zero(typ))
		}
		vAddr = v
		v = v.Elem()
		vType = v.Type()
	}
	switch typeID {
	case cfArrayTypeID:
		if vType.Kind() != reflect.Slice && vType.Kind() != reflect.Array {
			state.recordError(&UnmarshalTypeError{cfTypeNames[typeID], vType})
			return nil
		}
		return convertCFArrayToSliceHelper(C.CFArrayRef(cfObj), func(elem cfTypeRef, idx, count int) (bool, error) {
			if idx == 0 && vType.Kind() == reflect.Slice {
				vSetter.Set(reflect.MakeSlice(vType, count, count))
				v = vAddr.Elem()
			} else if vType.Kind() == reflect.Array && idx >= v.Len() {
				return false, nil
			}
			if err := state.unmarshalValue(elem, v.Index(idx)); err != nil {
				return false, err
			}
			return true, nil
		})
	case cfBooleanTypeID:
		if vType.Kind() != reflect.Bool {
			state.recordError(&UnmarshalTypeError{cfTypeNames[typeID], vType})
			return nil
		}
		vSetter.Set(reflect.ValueOf(C.CFBooleanGetValue(C.CFBooleanRef(cfObj)) != C.false))
		return nil
	case cfDataTypeID:
		if !byteSliceType.AssignableTo(vType) {
			state.recordError(&UnmarshalTypeError{cfTypeNames[typeID], vType})
			return nil
		}
		vSetter.Set(reflect.ValueOf(convertCFDataToBytes(C.CFDataRef(cfObj))))
		return nil
	case cfDateTypeID:
		if !timeType.AssignableTo(vType) {
			state.recordError(&UnmarshalTypeError{cfTypeNames[typeID], vType})
			return nil
		}
		vSetter.Set(reflect.ValueOf(convertCFDateToTime(C.CFDateRef(cfObj))))
		return nil
	case cfDictionaryTypeID:
		if vType.Kind() == reflect.Map {
			// it's a map. Check its key type first
//.........这里部分代码省略.........
开发者ID:kballard,项目名称:go-osx-plist,代码行数:101,代码来源:marshal.go

示例13: suitableMethods

// suitableMethods returns suitable Rpc methods of typ, it will report
// error using logger if reportErr is true.
func (server *Server) suitableMethods(rcvr interface{}, s *service, typ reflect.Type, reportErr bool, rcvrFns ...interface{}) map[uint32]*methodType {
	methods := s.method

	if typ.AssignableTo(reflect.TypeOf((**lua.LTable)(nil)).Elem()) {

		if len(rcvrFns) > 0 {

			rcvrFns[0].(*lua.LTable).ForEach(func(key, value lua.LValue) {
				//logger.Debug("ForEach LTable :%v, %v", key, value)
				if key.Type() == lua.LTString && value.Type() == lua.LTFunction && value.(*lua.LFunction).Proto.NumParameters == 3 {
					method, ok := reflect.TypeOf(server).MethodByName("CallLua")

					if !ok {
						logger.Debug("regist MethodByName error :%v", key.String())
					}

					mtype := method.Type
					mname := method.Name

					// Second arg need not be a pointer.
					argType := mtype.In(2)
					if !isExportedOrBuiltinType(argType) {
						if reportErr {
							logger.Info("%s argument type not exported: %s", mname, argType)
						}
						//continue
					}

					methods[server.protocol[key.String()]] = &methodType{method: method, ArgType: argType, luaMethod: value.(*lua.LFunction)}

					logger.Debug("regist %v", key.String())
				}
			})

		}

	} else {

		for m := 0; m < typ.NumMethod(); m++ {
			method := typ.Method(m)
			mtype := method.Type
			mname := method.Name

			//fmt.Printf("suitableMethods %s, %s, %s, %d \n", mtype, mname, method.PkgPath, mtype.NumIn())
			// Method must be exported.
			if method.PkgPath != "" {
				continue
			}

			// Method needs three ins: receiver, connid, *args.
			if mtype.NumIn() != 3 {
				if reportErr {
					logger.Info("method %s has wrong number of ins: %v", mname, mtype.NumIn())
				}
				continue
			}

			idType := mtype.In(1)

			if !idType.AssignableTo(reflect.TypeOf((*RpcConn)(nil)).Elem()) {
				if reportErr {
					logger.Info("%s conn %s must be %s", mname, idType.Name(), reflect.TypeOf((*RpcConn)(nil)).Elem().Name())
				}
				continue
			}

			// Second arg need not be a pointer.
			argType := mtype.In(2)
			if !isExportedOrBuiltinType(argType) {
				if reportErr {
					logger.Info("%s argument type not exported: %s", mname, argType)
				}
				continue
			}

			// Method needs one out.
			if mtype.NumOut() != 1 {
				if reportErr {
					logger.Info("method %s has wrong number of outs: %v", mname, mtype.NumOut())
				}
				continue
			}
			// The return type of the method must be error.
			if returnType := mtype.Out(0); returnType != typeOfError {
				if reportErr {
					logger.Info("method %s returns %s not error", mname, returnType.String())
				}
				continue
			}
			methods[server.protocol[mname]] = &methodType{method: method, ArgType: argType}
			logger.Debug("suitableMethods protocol %v, %d, %v", mname, server.protocol[mname], methods[server.protocol[mname]])
		}
	}

	return methods
}
开发者ID:bodogbo,项目名称:OSG-Server-Go,代码行数:98,代码来源:Server.go

示例14: areTypesCompatible

// Determines if two types can be automatically converted between.
func areTypesCompatible(xt, yt reflect.Type) bool {
	return xt.AssignableTo(unhackType(yt)) || yt.AssignableTo(unhackType(xt))
}
开发者ID:rocky,项目名称:go-eval,代码行数:4,代码来源:errors.go

示例15: newTypeDecoder

// newTypeDecoder constructs an decoderFunc for a type.
func newTypeDecoder(dt, st reflect.Type, blank bool) decoderFunc {
	if reflect.PtrTo(dt).Implements(unmarshalerType) ||
		dt.Implements(unmarshalerType) {
		return unmarshalerDecoder
	}

	if st.Kind() == reflect.Interface {
		return newInterfaceAsTypeDecoder(blank)
	}

	switch dt.Kind() {
	case reflect.Bool:
		switch st.Kind() {
		case reflect.Bool:
			return boolAsBoolDecoder
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return intAsBoolDecoder
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			return uintAsBoolDecoder
		case reflect.Float32, reflect.Float64:
			return floatAsBoolDecoder
		case reflect.String:
			return stringAsBoolDecoder
		default:
			return decodeTypeError
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		switch st.Kind() {
		case reflect.Bool:
			return boolAsIntDecoder
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return intAsIntDecoder
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			return uintAsIntDecoder
		case reflect.Float32, reflect.Float64:
			return floatAsIntDecoder
		case reflect.String:
			return stringAsIntDecoder
		default:
			return decodeTypeError
		}
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		switch st.Kind() {
		case reflect.Bool:
			return boolAsUintDecoder
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return intAsUintDecoder
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			return uintAsUintDecoder
		case reflect.Float32, reflect.Float64:
			return floatAsUintDecoder
		case reflect.String:
			return stringAsUintDecoder
		default:
			return decodeTypeError
		}
	case reflect.Float32, reflect.Float64:
		switch st.Kind() {
		case reflect.Bool:
			return boolAsFloatDecoder
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return intAsFloatDecoder
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			return uintAsFloatDecoder
		case reflect.Float32, reflect.Float64:
			return floatAsFloatDecoder
		case reflect.String:
			return stringAsFloatDecoder
		default:
			return decodeTypeError
		}
	case reflect.String:
		switch st.Kind() {
		case reflect.Bool:
			return boolAsStringDecoder
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			return intAsStringDecoder
		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
			return uintAsStringDecoder
		case reflect.Float32, reflect.Float64:
			return floatAsStringDecoder
		case reflect.String:
			return stringAsStringDecoder
		default:
			return decodeTypeError
		}
	case reflect.Interface:
		if !st.AssignableTo(dt) {
			return decodeTypeError
		}

		return interfaceDecoder
	case reflect.Ptr:
		return newPtrDecoder(dt, st, blank)
	case reflect.Map:
		if st.AssignableTo(dt) {
			return interfaceDecoder
		}

//.........这里部分代码省略.........
开发者ID:freedmand,项目名称:doc.vu,代码行数:101,代码来源:decoder_types.go


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