本文整理汇总了Golang中reflect.Type.FieldByName方法的典型用法代码示例。如果您正苦于以下问题:Golang Type.FieldByName方法的具体用法?Golang Type.FieldByName怎么用?Golang Type.FieldByName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reflect.Type
的用法示例。
在下文中一共展示了Type.FieldByName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: lookupType
func lookupType(ty reflect.Type, path ...string) (reflect.Type, bool) {
if len(path) == 0 {
return ty, true
}
switch ty.Kind() {
case reflect.Slice, reflect.Array, reflect.Map:
if hasIndex(path[0]) {
return lookupType(ty.Elem(), path[1:]...)
}
// Aggregate.
return lookupType(ty.Elem(), path...)
case reflect.Ptr:
return lookupType(ty.Elem(), path...)
case reflect.Interface:
// We can't know from here without a value. Let's just return this type.
return ty, true
case reflect.Struct:
f, ok := ty.FieldByName(path[0])
if ok {
return lookupType(f.Type, path[1:]...)
}
}
return nil, false
}
示例2: 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))
}
示例3: parseGofigureField
func (gfg *gofiguration) parseGofigureField(t reflect.Type) error {
gf, ok := t.FieldByName("gofigure")
if ok {
tags := getStructTags(string(gf.Tag))
for name, value := range tags {
if name == "order" {
oParts := strings.Split(value, ",")
for _, p := range oParts {
if _, ok := Sources[p]; !ok {
return ErrInvalidOrder
}
}
gfg.order = oParts
continue
}
// Parse orderKey:"value" tags, e.g.
// envPrefix, which gets split into
// gfg.params["env"]["prefix"] = "value"
// gfg.params["env"] is then passed to
// source registered with that key
match := argRe.FindStringSubmatch(name)
if len(match) > 1 {
if _, ok := gfg.params[match[1]]; !ok {
gfg.params[match[1]] = make(map[string]string)
}
gfg.params[match[1]][strings.ToLower(match[2])] = value
}
}
}
return nil
}
示例4: StructPtr
// StructPtr generates pointers to a given struct type.
// rt has to be the reflect type of the struct, gens contains a map of field generators.
// Note that the result types of the generators in gen have to match the type of the correspoinding
// field in the struct. Also note that only public fields of a struct can be generated
func StructPtr(rt reflect.Type, gens map[string]gopter.Gen) gopter.Gen {
if rt.Kind() == reflect.Ptr {
rt = rt.Elem()
}
if rt.Kind() != reflect.Struct {
return Fail(rt)
}
return func(genParams *gopter.GenParameters) *gopter.GenResult {
result := reflect.New(rt)
for name, gen := range gens {
field, ok := rt.FieldByName(name)
if !ok {
continue
}
value, ok := gen(genParams).Retrieve()
if !ok {
return gopter.NewEmptyResult(rt)
}
result.Elem().FieldByIndex(field.Index).Set(reflect.ValueOf(value))
}
return gopter.NewGenResult(result.Interface(), gopter.NoShrinker)
}
}
示例5: typeToParamsSpecFromPath
func typeToParamsSpecFromPath(t reflect.Type, path string) (
map[string]*ApiRequestParamSpec, error) {
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf(
"typeToParamsSpec: Only structs are supported, got: %v", t)
}
params := make(map[string]*ApiRequestParamSpec)
pathKeys, err := parsePath(path)
if err != nil {
return nil, err
}
for _, k := range pathKeys {
k = strings.Title(k)
field, found := t.FieldByName(k)
if !found {
return nil, fmt.Errorf(
"typeToParamsSpec: Can't find field %q in %v (from path %q)", k, t, path)
}
param, err := fieldToParamSpec(&field)
if err != nil {
return nil, err
}
param.Required = true
params[field.Name] = param
}
return params, nil
}
示例6: isList
func isList(t reflect.Type) bool {
if t.Kind() != reflect.Struct {
return false
}
_, hasListMeta := t.FieldByName("ListMeta")
return hasListMeta
}
示例7: CheckField
func CheckField(t *testing.T, typ reflect.Type, name string, typName string, typVal interface{}) {
field, found := typ.FieldByName(name)
if !found {
t.Fatalf("Pas de champ '%s'", name)
}
if field.Type != reflect.TypeOf(typVal) {
t.Fatalf("Le champ '%s' n'est pas de type %s", name, typName)
}
}
示例8: getExportedField
func getExportedField(t reflect.Type, field string) reflect.StructField {
f, ok := t.FieldByName(field)
if !ok {
panic("field " + field + " is not found")
}
if len(f.PkgPath) != 0 {
panic("field " + field + " is unexported")
}
return f
}
示例9: resolveKeyForField
// resolveKeyForField either returns lowercase version of the name if the field
// was found or the key found in a bson struct tag or "" if the field wasn't found
func resolveKeyForField(Struct reflect.Type, name string) string {
if f, ok := Struct.FieldByName(name); ok {
tag := f.Tag.Get("bson")
parts := strings.Split(tag, ",")
if len(parts) > 0 && parts[0] != "" && parts[0] != "-" {
return parts[0]
} else {
return strings.ToLower(f.Name)
}
}
return ""
}
示例10: columnToFieldIndex
func columnToFieldIndex(m *DbMap, t reflect.Type, cols []string) ([][]int, error) {
colToFieldIndex := make([][]int, len(cols))
// check if type t is a mapped table - if so we'll
// check the table for column aliasing below
tableMapped := false
table := tableOrNil(m, t)
if table != nil {
tableMapped = true
}
// Loop over column names and find field in i to bind to
// based on column name. all returned columns must match
// a field in the i struct
missingColNames := []string{}
for x := range cols {
colName := strings.ToLower(cols[x])
field, found := t.FieldByNameFunc(func(fieldName string) bool {
field, _ := t.FieldByName(fieldName)
cArguments := strings.Split(field.Tag.Get("db"), ",")
fieldName = cArguments[0]
if fieldName == "-" {
return false
} else if fieldName == "" {
fieldName = field.Name
}
if tableMapped {
colMap := colMapOrNil(table, fieldName)
if colMap != nil {
fieldName = colMap.ColumnName
}
}
return colName == strings.ToLower(fieldName)
})
if found {
colToFieldIndex[x] = field.Index
}
if colToFieldIndex[x] == nil {
missingColNames = append(missingColNames, colName)
}
}
if len(missingColNames) > 0 {
return colToFieldIndex, &NoFieldInTypeError{
TypeName: t.Name(),
MissingColNames: missingColNames,
}
}
return colToFieldIndex, nil
}
示例11: writeAccessorMethods
func writeAccessorMethods(rt reflect.Type) (accSrc string) {
var (
nameCases []string
sf reflect.StructField
sfType reflect.Type
isSid bool
sfName string
numCase, pos int
)
if _, hasSid := rt.FieldByName("HasSid"); !spref(rt.Name(), "ParamOrSid") {
accSrc += sfmt("func (me *%s) AccessField(fn string) interface{} {\n\tswitch fn {\n", rt.Name())
for i := 0; i < rt.NumField(); i++ {
if sf = rt.Field(i); (len(sf.Name) > 0) && (sf.Name != "Def") && (sf.Name != "Kind") && !sf.Anonymous {
if isSid, sfName, sfType = spref(sf.Type.Name(), "Sid"), sf.Name, sf.Type; isSid || (hasSid && (!anyOf(sfType, reflect.Invalid, reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Struct, reflect.UnsafePointer)) && ((sfType.Kind() != reflect.Ptr) || elemType(sfType).Kind() != reflect.Struct)) {
if numCase++; isSid {
switch sfType.Name() {
case "SidBool":
sfName += ".B"
case "SidString":
sfName += ".S"
case "SidVec3":
sfName += ".Vec3"
default:
sfName += ".F"
}
}
nameCases = append(nameCases, sf.Name)
accSrc += sfmt("\tcase %#v:\n\t\treturn %sme.%s\n", sf.Name, ustr.Ifs(sfType.Kind() == reflect.Ptr, "", "&"), sfName)
} else if pos = strings.Index(sfType.String(), "ParamOr"); pos > 0 {
// numCase++
switch sfType.String()[pos+len("ParamOr"):] {
case "Bool":
case "RefSid":
case "Float":
case "SidFloat":
case "Float2":
case "Int":
}
// println(rt.Name() + "." + sf.Name + " => " + sfType.String())
}
}
}
if accSrc += "\t}\n\treturn nil\n}\n\n"; numCase == 0 {
accSrc = ""
} else {
accSrc = sfmt("//\tRefSidFielder implementation.\n//\tSupported field names: \"%v\".\n", strings.Join(nameCases, "\", \"")) + accSrc
}
}
return
}
示例12: generateConversionsForStruct
func (g *conversionGenerator) generateConversionsForStruct(inType, outType reflect.Type) error {
for i := 0; i < inType.NumField(); i++ {
inField := inType.Field(i)
outField, found := outType.FieldByName(inField.Name)
if !found {
return fmt.Errorf("couldn't find a corresponding field %v in %v", inField.Name, outType)
}
if isComplexType(inField.Type) {
if err := g.generateConversionsBetween(inField.Type, outField.Type); err != nil {
return err
}
}
}
return nil
}
示例13: findField
func findField(value reflect.Value, typ reflect.Type, k string, v string) (reflect.Value, reflect.StructField) {
field := value.FieldByName(v)
if field.IsValid() {
tfield, _ := typ.FieldByName(v)
return field, tfield
}
for ix := 0; ix < value.NumField(); ix++ {
field := value.Field(ix)
tfield := typ.Field(ix)
if tfield.Tag.Get("AMI") == k && field.String() == v {
return field, tfield
}
}
return field, reflect.StructField{}
}
示例14: checkForInputError
func checkForInputError(fieldType reflect.Type, value interface{}) error {
// We always want to check the pointer to the value (and never the
// pointer to the pointer to the value) for interface matching.
var emptyValue reflect.Value
if fieldType.Kind() == reflect.Ptr {
emptyValue = reflect.New(fieldType.Elem())
} else {
emptyValue = reflect.New(fieldType)
}
// A type switch would look cleaner here, but we want a very
// specific order of preference for these interfaces. A type
// switch does not guarantee any preferred order, just that
// one valid case will be executed.
emptyInter := emptyValue.Interface()
if validator, ok := emptyInter.(InputValidator); ok {
return validator.ValidateInput(value)
}
if receiver, ok := emptyInter.(web_request_readers.RequestValueReceiver); ok {
return receiver.Receive(value)
}
fieldTypeName := fieldType.Name()
if fieldType.Kind() == reflect.Struct && strings.HasPrefix(fieldTypeName, SqlNullablePrefix) {
// database/sql defines many Null* types,
// where the fields are Valid (a bool) and the
// name of the type (everything after Null).
// We're trying to support them (somewhat)
// here.
typeName := fieldTypeName[len(SqlNullablePrefix):]
nullField, ok := fieldType.FieldByName(typeName)
if ok {
// This is almost definitely an sql.Null* type.
if value == nil {
return nil
}
fieldType = nullField.Type
}
}
if !reflect.TypeOf(value).ConvertibleTo(fieldType) {
return errors.New("Input is of the wrong type and cannot be converted")
}
return nil
}
示例15: columnToFieldIndex
func columnToFieldIndex(m *DbMap, t reflect.Type, cols []string) ([][]int, error) {
colToFieldIndex := make([][]int, len(cols))
// check if type t is a mapped table - if so we'll
// check the table for column aliasing below
tableMapped := false
table := tableOrNil(m, t)
if table != nil {
tableMapped = true
}
// Loop over column names and find field in i to bind to
// based on column name. all returned columns must match
// a field in the i struct
for x := range cols {
colName := strings.ToLower(cols[x])
field, found := t.FieldByNameFunc(func(fieldName string) bool {
field, _ := t.FieldByName(fieldName)
fieldName = field.Tag.Get("db")
if fieldName == "-" {
return false
} else if fieldName == "" {
fieldName = field.Name
}
if tableMapped {
colMap := colMapOrNil(table, fieldName)
if colMap != nil {
fieldName = colMap.ColumnName
}
}
return colName == strings.ToLower(fieldName)
})
if found {
colToFieldIndex[x] = field.Index
}
if colToFieldIndex[x] == nil {
return nil, fmt.Errorf("gorp: No field %s in type %s", colName, t.Name())
}
}
return colToFieldIndex, nil
}