本文整理匯總了Golang中reflect.Type.Key方法的典型用法代碼示例。如果您正苦於以下問題:Golang Type.Key方法的具體用法?Golang Type.Key怎麽用?Golang Type.Key使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類reflect.Type
的用法示例。
在下文中一共展示了Type.Key方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: typeIsOrContainsVerbotenImpl
func typeIsOrContainsVerbotenImpl(t reflect.Type, verboten reflect.Kind) bool {
switch t.Kind() {
case verboten:
return true
case reflect.Map:
if typeIsOrContainsVerbotenLocked(t.Key(), verboten) || typeIsOrContainsVerbotenLocked(t.Elem(), verboten) {
return true
}
case reflect.Array, reflect.Ptr, reflect.Slice:
if typeIsOrContainsVerbotenLocked(t.Elem(), verboten) {
return true
}
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
if typeIsOrContainsVerbotenLocked(t.Field(i).Type, verboten) {
return true
}
}
case reflect.Chan, reflect.Func, reflect.Interface:
// Not strictly correct, but cloning these kinds is not allowed.
return true
}
return false
}
示例2: verifyHandler
// verifyHandler ensures that the given t is a function with the following signature:
// func(json.Context, *ArgType)(*ResType, error)
func verifyHandler(t reflect.Type) error {
if t.NumIn() != 2 || t.NumOut() != 2 {
return fmt.Errorf("handler should be of format func(json.Context, *ArgType) (*ResType, error)")
}
isStructPtr := func(t reflect.Type) bool {
return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
}
isMap := func(t reflect.Type) bool {
return t.Kind() == reflect.Map && t.Key().Kind() == reflect.String
}
validateArgRes := func(t reflect.Type, name string) error {
if !isStructPtr(t) && !isMap(t) {
return fmt.Errorf("%v should be a pointer to a struct, or a map[string]interface{}", name)
}
return nil
}
if t.In(0) != typeOfContext {
return fmt.Errorf("arg0 should be of type json.Context")
}
if err := validateArgRes(t.In(1), "second argument"); err != nil {
return err
}
if err := validateArgRes(t.Out(0), "first return value"); err != nil {
return err
}
if !t.Out(1).AssignableTo(typeOfError) {
return fmt.Errorf("second return value should be an error")
}
return nil
}
示例3: getOrCreateSchema
func getOrCreateSchema(definitions Definitions, t reflect.Type) *Schema {
var result Schema
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Map {
if t.Key().Kind() != reflect.String {
panic("swagger supports only maps with string keys")
}
result.Type = "object"
result.AdditionalProperties = getOrCreateSchema(definitions, t.Elem())
return &result
}
if t.Kind() == reflect.Interface {
result.Type = "object"
return &result
}
result.Type = typeName(t)
if result.Type == "object" {
name := t.String()
if _, ok := definitions[name]; ok {
result = Schema{Ref: "#/definitions/" + name}
return &result
}
definitions[name] = result
if t.NumField() > 0 {
result.Properties = Properties{}
}
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" {
continue
}
name := field.Tag.Get("json")
if name == "" {
name = field.Tag.Get("key")
if name == "" {
name = field.Name
}
}
if field.Type.Kind() != reflect.Ptr {
result.Required = append(result.Required, name)
}
fieldSchema := getOrCreateSchema(definitions, field.Type)
fieldSchema.Description = field.Tag.Get("description")
result.Properties[name] = fieldSchema
}
definitions[name] = result
result = Schema{Ref: "#/definitions/" + name}
} else if result.Type == "array" {
itemsSchema := getOrCreateSchema(definitions, t.Elem())
result.Items = &Items{*itemsSchema}
}
return &result
}
示例4: copyTableToMap
func copyTableToMap(L *lua.State, t reflect.Type, idx int, visited map[uintptr]interface{}) interface{} {
if t == nil {
t = tmap
}
te, tk := t.Elem(), t.Key()
m := reflect.MakeMap(t)
// See copyTableToSlice.
ptr := L.ToPointer(idx)
if !luaIsEmpty(L, idx) {
visited[ptr] = m.Interface()
}
L.PushNil()
if idx < 0 {
idx--
}
for L.Next(idx) != 0 {
// key at -2, value at -1
key := reflect.ValueOf(luaToGo(L, tk, -2, visited))
val := reflect.ValueOf(luaToGo(L, te, -1, visited))
if val.Interface() == nullv.Interface() {
val = reflect.Zero(te)
}
m.SetMapIndex(key, val)
L.Pop(1)
}
return m.Interface()
}
示例5: addImportsForType
// Add all necessary imports for the type, recursing as appropriate.
func addImportsForType(imports importMap, t reflect.Type) {
// Add any import needed for the type itself.
addImportForType(imports, t)
// Handle special cases where recursion is needed.
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Ptr, reflect.Slice:
addImportsForType(imports, t.Elem())
case reflect.Func:
// Input parameters.
for i := 0; i < t.NumIn(); i++ {
addImportsForType(imports, t.In(i))
}
// Return values.
for i := 0; i < t.NumOut(); i++ {
addImportsForType(imports, t.Out(i))
}
case reflect.Map:
addImportsForType(imports, t.Key())
addImportsForType(imports, t.Elem())
}
}
示例6: typeName
func (g *conversionGenerator) typeName(inType reflect.Type) string {
switch inType.Kind() {
case reflect.Map:
return fmt.Sprintf("map[%s]%s", g.typeName(inType.Key()), g.typeName(inType.Elem()))
case reflect.Slice:
return fmt.Sprintf("[]%s", g.typeName(inType.Elem()))
case reflect.Ptr:
return fmt.Sprintf("*%s", g.typeName(inType.Elem()))
default:
typeWithPkg := fmt.Sprintf("%s", inType)
slices := strings.Split(typeWithPkg, ".")
if len(slices) == 1 {
// Default package.
return slices[0]
}
if len(slices) == 2 {
pkg := slices[0]
if val, found := g.pkgOverwrites[pkg]; found {
pkg = val
}
if pkg != "" {
pkg = pkg + "."
}
return pkg + slices[1]
}
panic("Incorrect type name: " + typeWithPkg)
}
}
示例7: newMapEncoder
func newMapEncoder(t reflect.Type) encoderFunc {
if t.Key().Kind() != reflect.String && !t.Key().Implements(textMarshalerType) {
return unsupportedTypeEncoder
}
me := &mapEncoder{typeEncoder(t.Elem())}
return me.encode
}
示例8: evalCompositeLitMap
func evalCompositeLitMap(ctx *Ctx, t reflect.Type, lit *CompositeLit, env *Env) (reflect.Value, error) {
m := reflect.MakeMap(t)
kT := knownType{t.Key()}
vT := knownType{t.Elem()}
for _, elt := range lit.Elts {
kv := elt.(*KeyValueExpr)
k, err := evalTypedExpr(ctx, kv.Key.(Expr), kT, env)
if err != nil {
return reflect.Value{}, err
}
if kT[0].Kind() == reflect.Interface {
dynamicT := k[0].Elem().Type()
if !isStaticTypeComparable(dynamicT) {
return reflect.Value{}, PanicUnhashableType{dynamicT}
}
}
v, err := evalTypedExpr(ctx, kv.Value.(Expr), vT, env)
if err != nil {
return reflect.Value{}, err
}
m.SetMapIndex(k[0], v[0])
}
return m, nil
}
示例9: typeName
func (g *conversionGenerator) typeName(inType reflect.Type) string {
switch inType.Kind() {
case reflect.Slice:
return fmt.Sprintf("[]%s", g.typeName(inType.Elem()))
case reflect.Ptr:
return fmt.Sprintf("*%s", g.typeName(inType.Elem()))
case reflect.Map:
if len(inType.Name()) == 0 {
return fmt.Sprintf("map[%s]%s", g.typeName(inType.Key()), g.typeName(inType.Elem()))
}
fallthrough
default:
pkg, name := inType.PkgPath(), inType.Name()
if len(name) == 0 && inType.Kind() == reflect.Struct {
return "struct{}"
}
if len(pkg) == 0 {
// Default package.
return name
}
if val, found := g.pkgOverwrites[pkg]; found {
pkg = val
}
if len(pkg) == 0 {
return name
}
short := g.addImportByPath(pkg)
if len(short) > 0 {
return fmt.Sprintf("%s.%s", short, name)
}
return name
}
}
示例10: mapEncodeScratch
// mapEncodeScratch returns a new reflect.Value matching the map's value type,
// and a structPointer suitable for passing to an encoder or sizer.
func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
// Prepare addressable doubly-indirect placeholders for the key and value types.
// This is needed because the element-type encoders expect **T, but the map iteration produces T.
keycopy = reflect.New(mapType.Key()).Elem() // addressable K
keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
keyptr.Set(keycopy.Addr()) //
keybase = toStructPointer(keyptr.Addr()) // **K
// Value types are more varied and require special handling.
switch mapType.Elem().Kind() {
case reflect.Slice:
// []byte
var dummy []byte
valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
valbase = toStructPointer(valcopy.Addr())
case reflect.Ptr:
// message; the generated field type is map[K]*Msg (so V is *Msg),
// so we only need one level of indirection.
valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
valbase = toStructPointer(valcopy.Addr())
default:
// everything else
valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
valptr.Set(valcopy.Addr()) //
valbase = toStructPointer(valptr.Addr()) // **V
}
return
}
示例11: newMapEncoder
func newMapEncoder(t reflect.Type, vx reflect.Value) encoderFunc {
if t.Key().Kind() != reflect.String {
return unsupportedTypeEncoder
}
me := &mapEncoder{typeEncoder(vx.Type().Elem(), reflect.Value{})}
return me.encode
}
示例12: unify
// unify attempts to satisfy a pair of types, where the `param` type is the
// expected type of a function argument and the `input` type is the known
// type of a function argument. The `param` type may be parametric (that is,
// it may contain a type that is convertible to TypeVariable) but the
// `input` type may *not* be parametric.
//
// Any failure to unify the two types results in a panic.
//
// The end result of unification is a type environment: a set of substitutions
// from type variable to a Go type.
func (tp typePair) unify(param, input reflect.Type) error {
if tyname := tyvarName(input); len(tyname) > 0 {
return tp.error("Type variables are not allowed in the types of " +
"arguments.")
}
if tyname := tyvarName(param); len(tyname) > 0 {
if cur, ok := tp.tyenv[tyname]; ok && cur != input {
return tp.error("Type variable %s expected type '%s' but got '%s'.",
tyname, cur, input)
} else if !ok {
tp.tyenv[tyname] = input
}
return nil
}
if param.Kind() != input.Kind() {
return tp.error("Cannot unify different kinds of types '%s' and '%s'.",
param, input)
}
switch param.Kind() {
case reflect.Array:
return tp.unify(param.Elem(), input.Elem())
case reflect.Chan:
if param.ChanDir() != input.ChanDir() {
return tp.error("Cannot unify '%s' with '%s' "+
"(channel directions are different: '%s' != '%s').",
param, input, param.ChanDir(), input.ChanDir())
}
return tp.unify(param.Elem(), input.Elem())
case reflect.Func:
if param.NumIn() != input.NumIn() || param.NumOut() != input.NumOut() {
return tp.error("Cannot unify '%s' with '%s'.", param, input)
}
for i := 0; i < param.NumIn(); i++ {
if err := tp.unify(param.In(i), input.In(i)); err != nil {
return err
}
}
for i := 0; i < param.NumOut(); i++ {
if err := tp.unify(param.Out(i), input.Out(i)); err != nil {
return err
}
}
case reflect.Map:
if err := tp.unify(param.Key(), input.Key()); err != nil {
return err
}
return tp.unify(param.Elem(), input.Elem())
case reflect.Ptr:
return tp.unify(param.Elem(), input.Elem())
case reflect.Slice:
return tp.unify(param.Elem(), input.Elem())
}
// The only other container types are Interface and Struct.
// I am unsure about what to do with interfaces. Mind is fuzzy.
// Structs? I don't think it really makes much sense to use type
// variables inside of them.
return nil
}
示例13: 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
}
示例14: compileField
func compileField(typ reflect.Type, name string, args []parse.Node, final reflect.Type) (fn lookupFn, elem reflect.Type) {
if isNilType(typ) {
fn = compileFieldDynamic(name, args)
return
}
if m, exist := typ.MethodByName(name); exist {
fn = compileMethodCall(typ, m.Func, args, final)
elem = m.Type.Out(0)
return
}
switch typ.Kind() {
case reflect.Struct:
structField, found := typ.FieldByName(name)
if !found {
panic(fmt.Errorf("%s has no field %s", typ, name))
}
fn = func(s state, v reflect.Value, final interface{}) reflect.Value {
return v.FieldByIndex(structField.Index)
}
elem = structField.Type
return
case reflect.Map:
k := reflect.ValueOf(name)
fn = func(s state, v reflect.Value, final interface{}) reflect.Value {
return v.MapIndex(k)
}
elem = typ.Key()
return
}
panic(fmt.Errorf("struct or map expected, but got %s", typ))
}
示例15: newMapEncoder
func newMapEncoder(t reflect.Type) encoderFunc {
if t.Key().Kind() != reflect.String {
return unsupportedTypeEncoder
}
me := &mapEncoder{typeEncoder(t.Elem())}
return me.encode
}