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


Golang Type.String方法代码示例

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


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

示例1: instructiveMessage

// Since it's easy to pass the wrong method to a middleware/handler route, and since the user can't rely on static type checking since we use reflection,
// lets be super helpful about what they did and what they need to do.
// Arguments:
//  - vfn is the failed method
//  - addingType is for "You are adding {addingType} to a router...". Eg, "middleware" or "a handler" or "an error handler"
//  - yourType is for "Your {yourType} function can have...". Eg, "middleware" or "handler" or "error handler"
//  - args is like "rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc"
//    - NOTE: args can be calculated if you pass in each type. BUT, it doesn't have example argument name, so it has less copy/paste value.
func instructiveMessage(vfn reflect.Value, addingType string, yourType string, args string, ctxType reflect.Type) string {
	// Get context type without package.
	ctxString := ctxType.String()
	splitted := strings.Split(ctxString, ".")
	if len(splitted) <= 1 {
		ctxString = splitted[0]
	} else {
		ctxString = splitted[1]
	}

	str := "\n" + strings.Repeat("*", 120) + "\n"
	str += "* You are adding " + addingType + " to a router with context type '" + ctxString + "'\n"
	str += "*\n*\n"
	str += "* Your " + yourType + " function can have one of these signatures:\n"
	str += "*\n"
	str += "* // If you don't need context:\n"
	str += "* func YourFunctionName(" + args + ")\n"
	str += "*\n"
	str += "* // If you want your " + yourType + " to accept a context:\n"
	str += "* func (c *" + ctxString + ") YourFunctionName(" + args + ")  // or,\n"
	str += "* func YourFunctionName(c *" + ctxString + ", " + args + ")\n"
	str += "*\n"
	str += "* Unfortunately, your function has this signature: " + vfn.Type().String() + "\n"
	str += "*\n"
	str += strings.Repeat("*", 120) + "\n"

	return str
}
开发者ID:nikai3d,项目名称:web,代码行数:36,代码来源:router_setup.go

示例2: addImportForType

// Add an import for the supplied type, without recursing.
func addImportForType(imports importMap, t reflect.Type) {
	// If there is no package path, this is a built-in type and we don't need an
	// import.
	pkgPath := t.PkgPath()
	if pkgPath == "" {
		return
	}

	// Work around a bug in Go:
	//
	//     http://code.google.com/p/go/issues/detail?id=2660
	//
	var errorPtr *error
	if t == reflect.TypeOf(errorPtr).Elem() {
		return
	}

	// Use the identifier that's part of the type's string representation as the
	// import identifier. This means that we'll do the right thing for package
	// "foo/bar" with declaration "package baz".
	match := typePackageIdentifierRegexp.FindStringSubmatch(t.String())
	if match == nil {
		return
	}

	imports[match[1]] = pkgPath
}
开发者ID:BanzaiMan,项目名称:gcsfuse,代码行数:28,代码来源:generate.go

示例3: createArguments

// Get all the parameters setup for invocation.
func (method ApiMethod) createArguments(userId UserId, userName UserName, token Token, response http.ResponseWriter, request *http.Request) (bool, []reflect.Value) {
	var handlerType reflect.Type = reflect.TypeOf(method.handler)
	var numParams int = handlerType.NumIn()

	var apiParamIndex = 0
	var paramValues []reflect.Value = make([]reflect.Value, numParams)

	for i := 0; i < numParams; i++ {
		var ParamType reflect.Type = handlerType.In(i)

		// The user id, token, request, and response get handled specially.
		if method.auth && ParamType.String() == "goapi.Token" {
			paramValues[i] = reflect.ValueOf(token)
		} else if method.auth && ParamType.String() == "goapi.UserId" {
			paramValues[i] = reflect.ValueOf(userId)
		} else if method.auth && ParamType.String() == "goapi.UserName" {
			paramValues[i] = reflect.ValueOf(userName)
		} else if ParamType.String() == "*http.Request" {
			paramValues[i] = reflect.ValueOf(request)
		} else if ParamType.String() == "http.ResponseWriter" {
			paramValues[i] = reflect.ValueOf(response)
		} else {
			// Normal param, fetch the next api parameter and pass it along.
			ok, val := method.fetchParam(apiParamIndex, request)
			if !ok {
				return false, []reflect.Value{}
			}

			paramValues[i] = val
			apiParamIndex++
		}
	}

	return true, paramValues
}
开发者ID:eriq-augustine,项目名称:goapi,代码行数:36,代码来源:apimethod.go

示例4: makePacker

// Returns the number of bits packed
// as the second return value
func makePacker(lsb uint64, strct reflect.Type) (packer, uint64, error) {
	ptrType := strct.Kind() == reflect.Ptr
	if ptrType {
		strct = strct.Elem()
	}
	if strct.Kind() != reflect.Struct {
		return nil, 0, Error{fmt.Errorf("gopack: non-struct type %v", strct.String())}
	}
	n := strct.NumField()
	packers := make([]packer, 0)
	var bitsPacked uint64
	for i := 0; i < n; i++ {
		field := strct.Field(i)
		if isExported(field) {
			f, bits, err := makeFieldPacker(lsb, field)
			if err != nil {
				return nil, 0, err
			}
			lsb += bits
			bitsPacked += bits
			packers = append(packers, f)
		} else {
			packers = append(packers, noOpPacker)
		}
	}
	return makeCallAllPackers(packers, ptrType), bitsPacked, nil
}
开发者ID:tsuna,项目名称:gopack,代码行数:29,代码来源:gopack-impl.go

示例5: decodeStruct

func (d *Decoder) decodeStruct(s *decodStatus, v reflect.Value, t reflect.Type, tg tag) error {
	switch t.String() {
	case "time.Time":
		val, ok := s.GetValue(d.env)
		if !ok {
			return nil
		}
		tf := tg.Modifiers["timeformat"]
		if tf == "" {
			tf = "2006-01-02 15:04:05"
		}
		t, err := time.Parse(tf, val)
		if err != nil {
			return err
		}
		v.Set(reflect.ValueOf(t))
	default:
		for i := 0; i < t.NumField(); i++ {
			f := t.Field(i)
			fv := v.Field(i)
			if !fv.CanSet() {
				continue
			}
			err := d.decodeElement(s, fv, f.Type, newTag(f))
			if err != nil {
				return err
			}
		}
	}
	return nil
}
开发者ID:klaidliadon,项目名称:pongo,代码行数:31,代码来源:decode.go

示例6: ensureInInnerType

// Check if the inInnerType is of type struct
func (encode *encoder) ensureInInnerType(outInnerType reflect.Type) error {
	switch outInnerType.Kind() {
	case reflect.Struct:
		return nil
	}
	return fmt.Errorf("cannot use " + outInnerType.String() + ", only struct supported")
}
开发者ID:kurtzhong,项目名称:gocsv,代码行数:8,代码来源:encode.go

示例7: getTypeDescribe

func getTypeDescribe(typ reflect.Type) *typeDescribe {
	key := typ.String()
	if td, ok := typeDescribes[key]; ok {
		return td
	}
	return createTypeDescribe(typ)
}
开发者ID:cobersky,项目名称:gioc,代码行数:7,代码来源:typeDescribe.go

示例8: coerce

func coerce(v interface{}, typ reflect.Type) (reflect.Value, error) {
	var err error
	if typ.Kind() == reflect.Ptr {
		return reflect.ValueOf(v), nil
	}
	switch typ.String() {
	case "string":
		v, err = coerceString(v)
	case "int", "int16", "int32", "int64":
		v, err = coerceInt64(v)
	case "uint", "uint16", "uint32", "uint64":
		v, err = coerceUint64(v)
	case "float32", "float64":
		v, err = coerceFloat64(v)
	case "bool":
		v, err = coerceBool(v)
	case "time.Duration":
		v, err = coerceDuration(v)
	case "net.Addr":
		v, err = coerceAddr(v)
	case "nsq.BackoffStrategy":
		v, err = coerceBackoffStrategy(v)
	default:
		v = nil
		err = fmt.Errorf("invalid type %s", typ.String())
	}
	return valueTypeCoerce(v, typ), err
}
开发者ID:absolute8511,项目名称:go-nsq,代码行数:28,代码来源:config.go

示例9: MustFindParamName

// MustFindParamName return param name by given reflect type.
// Panic if param name not found.
func (e *ExecutionCoordinator) MustFindParamName(typ reflect.Type) string {
	name, ok := e.paramTypeRegister.findTypeName(typ)
	if !ok {
		panic("Find Param Name Panic: " + typ.String())
	}
	return name
}
开发者ID:lysu,项目名称:go-saga,代码行数:9,代码来源:coordinator.go

示例10: generateUid

func generateUid(typ reflect.Type, name string) string {
	if len(name) > 0 {
		return typ.String() + ":" + name
	} else {
		return typ.String() + ":-"
	}
}
开发者ID:cobersky,项目名称:gioc,代码行数:7,代码来源:injector.go

示例11: getAlias

func (this *FileInfo) getAlias(packet string, fieldType reflect.Type) (string, bool) {
	stdType := true
	alias := fieldType.String()
	pktPath := fieldType.PkgPath()
	if len(pktPath) > 0 {
		stdType = false
		if fieldType.Kind() == reflect.Ptr {
			if pktPath != "" && pktPath != packet {
				if packet, found := this.Imports[pktPath]; !found {
					ref := alias
					if idx := strings.Index(ref, "."); idx >= 0 {
						ref = ref[:idx]
					}
					if _, found := this.RefImport[ref]; found {
						ref = genPacketAliasMD5(pktPath)
						alias = ref + "." + fieldType.Name()
					}
					this.RefImport[ref] = pktPath
					this.Imports[pktPath] = packet
				} else {
					alias = packet + "." + pktPath
				}
			}
		}
	}

	return alias, stdType
}
开发者ID:darvik80,项目名称:go-msgpack,代码行数:28,代码来源:reflect.go

示例12: decPtr

func (t *TGen) decPtr(name string, val reflect.Type) {
	t.decNilBegin(name)
	t.src += name + "= new(" + TypeName(val.String(), false) + ")\n"
	t.stackName.Push("(*" + name + ")")
	t.decode(val.Elem())
	t.decNilEnd()
}
开发者ID:catgatp,项目名称:gol,代码行数:7,代码来源:decoder.go

示例13: Contains

// String 根据名称和类型返回相应的字符串值,返回的bool表示该值是否存在
func (this *ContextValueContainer) Contains(name string, t reflect.Type) (meta.ValueProvider, bool) {
	// 查找 web.Processor.Finders
	var finder, ok = this.Context.Processor.Finders[t.String()]
	if ok {
		ok = finder.Contains(this.Context, name, t)
	}
	if !ok {
		// 查找 web.Processor.MutiTypeFinders
		for _, f := range this.Context.Processor.MutiTypeFinders {
			if f.Contains(this.Context, name, t) {
				finder = f
				ok = true
				break
			}
		}
	}
	if ok {
		return &ContextValueProvider{
			this.Context,
			finder,
			name,
			t,
		}, true
	}
	var vc = this.Context.Processor.DefaultValueContainer
	if vc != nil {
		return vc.Contains(name, t)
	}
	return nil, false
}
开发者ID:kdada,项目名称:tinygo,代码行数:31,代码来源:provider.go

示例14: newControllerInfo

func newControllerInfo(namespace string, t reflect.Type, defaultAction string) *controllerInfo {
	typeName := t.String()
	if strings.HasPrefix(typeName, "*") {
		panic(errInvalidCtrlType(typeName))
	}
	numMethod := t.NumMethod()
	if numMethod < 1 {
		panic(errCtrlNoAction(typeName))
	}
	methods := make([]string, 0, numMethod)
	for i := 0; i < numMethod; i++ {
		methodInfo := t.Method(i)
		numIn := methodInfo.Type.NumIn()
		numOut := methodInfo.Type.NumOut()
		if numIn != 1 || numOut != 1 {
			continue
		}
		methodName := methodInfo.Name
		methods = append(methods, methodName)
	}
	if len(methods) < 1 {
		panic(errCtrlNoAction(typeName))
	}
	actions := make(map[string]string, len(methods))
	for _, m := range methods {
		actions[strings.ToLower(m)] = m
	}
	return &controllerInfo{
		NsName:        namespace,
		CtrlName:      getControllerName(t),
		CtrlType:      t,
		Actions:       actions,
		DefaultAction: defaultAction,
	}
}
开发者ID:Simbory,项目名称:wemvc,代码行数:35,代码来源:route_test.go

示例15: CompatibleSqlTypes

func (d mysqlDialect) CompatibleSqlTypes(f reflect.Type) []string {
	switch f.Kind() {
	case reflect.Struct:
		if f.String() == "time.Time" {
			return []string{"timestamp"}
		}
	case reflect.Bool:
		return []string{"boolean"}
	case reflect.Int, reflect.Int32, reflect.Uint, reflect.Uint32:
		return []string{"int", "integer", "bigint"}
	case reflect.Int64, reflect.Uint64:
		return []string{"bigint"}
	case reflect.Int8, reflect.Uint8:
		return []string{"tinyint", "smallint", "mediumint", "int", "integer", "bigint"}
	case reflect.Int16, reflect.Uint16:
		return []string{"mediumint", "int", "integer", "bigint"}
	case reflect.Float32:
		return []string{"double", "float"}
	case reflect.Float64:
		return []string{"double"}
	case reflect.Slice:
		if f.String() == "[]uint8" { //[]byte
			return []string{"varbinary", "longblob"}
		}
	case reflect.String:
		return []string{"varchar", "text", "longtext"}
	}
	panic("invalid sql type")
}
开发者ID:acsellers,项目名称:db,代码行数:29,代码来源:mysql.go


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