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


Golang Type.Field方法代码示例

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


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

示例1: ToJson

func ToJson(_struct interface{}) (map[string]interface{}, error) {
	var (
		v reflect.Value
		t reflect.Type
	)

	result := make(map[string]interface{})

	if reflect.TypeOf(_struct).Kind() == reflect.Ptr {
		v = reflect.ValueOf(_struct).Elem()
		t = reflect.TypeOf(_struct).Elem()
	} else {
		v = reflect.ValueOf(_struct)
		t = reflect.TypeOf(_struct)
	}

	if t.Kind() != reflect.Struct {
		panic(errors.New("excepted a pointer of struct or a struct"))
	}

	for i := 0; i < v.NumField(); i++ {
		//fieldName := strings.ToLower(t.Field(i).Name)
		fieldName := t.Field(i).Name
		result[fieldName] = v.Field(i).Interface()
	}

	val, _ := json.MarshalIndent(result, "", "\t")

	fmt.Printf("%v\n", (string)(val))

	return result, nil
}
开发者ID:EyciaZhou,项目名称:configparser,代码行数:32,代码来源:conf.go

示例2: MakeTypeInfo

func MakeTypeInfo(rt reflect.Type) *TypeInfo {
	info := &TypeInfo{Type: rt}

	// If struct, register field name options
	if rt.Kind() == reflect.Struct {
		numFields := rt.NumField()
		structFields := []StructFieldInfo{}
		for i := 0; i < numFields; i++ {
			field := rt.Field(i)
			if field.PkgPath != "" {
				continue
			}
			skip, opts := getOptionsFromField(field)
			if skip {
				continue
			}
			structFields = append(structFields, StructFieldInfo{
				Index:   i,
				Type:    field.Type,
				Options: opts,
			})
		}
		info.Fields = structFields
	}

	return info
}
开发者ID:huangjiehua,项目名称:tendermint,代码行数:27,代码来源:reflect.go

示例3: validateListType

func validateListType(target reflect.Type) error {
	// exceptions
	if listTypeExceptions.Has(target.Name()) {
		return nil
	}
	hasListSuffix := strings.HasSuffix(target.Name(), "List")
	hasMetadata := false
	hasItems := false
	for i := 0; i < target.NumField(); i++ {
		field := target.Field(i)
		tag := field.Tag.Get("json")
		switch {
		case strings.HasPrefix(tag, "metadata"):
			hasMetadata = true
		case tag == "items":
			hasItems = true
			if field.Type.Kind() != reflect.Slice {
				return fmt.Errorf("Expected items to be slice, got %s", field.Type.Kind())
			}
		}
	}
	if hasListSuffix && !hasMetadata {
		return fmt.Errorf("Expected type %s to contain \"metadata\"", target.Name())
	}
	if hasListSuffix && !hasItems {
		return fmt.Errorf("Expected type %s to contain \"items\"", target.Name())
	}
	// if a type contains field Items with JSON tag "items", its name should end with List.
	if !hasListSuffix && hasItems {
		return fmt.Errorf("Type %s has Items, its name is expected to end with \"List\"", target.Name())
	}
	return nil
}
开发者ID:CodeJuan,项目名称:kubernetes,代码行数:33,代码来源:scheme_test.go

示例4: getTableColumns

func getTableColumns(thing interface{}, typ reflect.Type) []*columnMap {
	columns := make([]*columnMap, 0, typ.NumField())

	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)
		tag := strings.Split(field.Tag.Get("db"), ",")
		if len(tag) > 0 && tag[0] != "" {
			col := &columnMap{Field: i}
			for _, flag := range tag {
				switch flag {
				case "pk":
					col.PrimaryKey = true
				case "serialize":
					col.Serialize = true
				default:
					if col.Name == "" {
						col.Name = flag
					}
				}
			}
			columns = append(columns, col)
		}
	}

	return columns
}
开发者ID:kelsieflynn,项目名称:m,代码行数:26,代码来源:mapper.go

示例5: Indexes

func (c *structCache) Indexes(typ reflect.Type) map[string][]int {
	c.l.RLock()
	indxs, ok := c.m[typ]
	c.l.RUnlock()
	if ok {
		return indxs
	}

	numField := typ.NumField()
	indxs = make(map[string][]int, numField)
	for i := 0; i < numField; i++ {
		f := typ.Field(i)
		if f.PkgPath != "" {
			continue
		}

		tokens := strings.Split(f.Tag.Get("pg"), ",")
		name := tokens[0]
		if name == "-" {
			continue
		}
		if name == "" {
			name = formatColumnName(f.Name)
		}
		indxs[name] = f.Index
	}

	c.l.Lock()
	c.m[typ] = indxs
	c.l.Unlock()

	return indxs
}
开发者ID:rsrsps,项目名称:pg,代码行数:33,代码来源:typeinfo.go

示例6: getFields

func getFields(typ reflect.Type) *fields {
	numField := typ.NumField()
	fs := newFields(numField)

	for i := 0; i < numField; i++ {
		f := typ.Field(i)
		if f.PkgPath != "" && !f.Anonymous {
			continue
		}

		name, opts := parseTag(f.Tag.Get("msgpack"))
		if name == "-" {
			continue
		}

		if opts.Contains("inline") {
			inlineFields(fs, f)
			continue
		}

		if name == "" {
			name = f.Name
		}
		field := field{
			name:      name,
			index:     f.Index,
			omitEmpty: opts.Contains("omitempty"),
			encoder:   getEncoder(f.Type),
			decoder:   getDecoder(f.Type),
		}
		fs.Add(&field)
	}
	return fs
}
开发者ID:vodka-contrib,项目名称:cache,代码行数:34,代码来源:types.go

示例7: rawSelectByStruct

func (db *DB) rawSelectByStruct(structType reflect.Type, qi SqlQueryInfo) (rows *sql.Rows, fields []string, err error) {
	// nums of struct's fields
	lf := structType.NumField()
	// type's fields
	fields = make([]string, 0, lf)
	// sql select columns, it's Snake Cased
	columns := make([]string, 0, lf)

	// get fields in structType,
	// and convert to sql query column name
	for i := 0; i < lf; i++ {
		structField := structType.Field(i)
		fieldName := structField.Name
		fields = append(fields, fieldName)
		columns = append(columns, utils.SnakeCasedName(fieldName))
	}

	// tableName := utils.SnakeCasedName(utils.StructName(s))
	tableName := utils.SnakeCasedName(structType.Name())
	// TODO: check the fileds has specified ?
	qi.Fields = strings.Join(columns, ", ")
	// run query from db
	rows, err = db.Select(tableName, qi)
	return
}
开发者ID:seacoastboy,项目名称:goku,代码行数:25,代码来源:db.go

示例8: visit

// visit calls the visitor function for each string it finds, and will descend
// recursively into structures and slices. If any visitor returns an error then
// the search will stop and that error will be returned.
func visit(path string, v reflect.Value, t reflect.Type, fn visitor) error {
	switch v.Kind() {
	case reflect.String:
		return fn(path, v)
	case reflect.Struct:
		for i := 0; i < v.NumField(); i++ {
			vf := v.Field(i)
			tf := t.Field(i)
			newPath := fmt.Sprintf("%s.%s", path, tf.Name)
			if err := visit(newPath, vf, tf.Type, fn); err != nil {
				return err
			}
		}
	case reflect.Slice:
		for i := 0; i < v.Len(); i++ {
			vi := v.Index(i)
			ti := vi.Type()
			newPath := fmt.Sprintf("%s[%d]", path, i)
			if err := visit(newPath, vi, ti, fn); err != nil {
				return err
			}
		}
	}
	return nil
}
开发者ID:rchicoli,项目名称:consul,代码行数:28,代码来源:walk.go

示例9: getFieldInfos

func getFieldInfos(rType reflect.Type, parentIndexChain []int) []fieldInfo {
	fieldsCount := rType.NumField()
	fieldsList := make([]fieldInfo, 0, fieldsCount)
	for i := 0; i < fieldsCount; i++ {
		field := rType.Field(i)
		if field.PkgPath != "" {
			continue
		}
		indexChain := append(parentIndexChain, i)
		// if the field is an embedded struct, create a fieldInfo for each of its fields
		if field.Anonymous && field.Type.Kind() == reflect.Struct {
			fieldsList = append(fieldsList, getFieldInfos(field.Type, indexChain)...)
			continue
		}
		fieldInfo := fieldInfo{IndexChain: indexChain}
		fieldTag := field.Tag.Get("csv")
		fieldTags := strings.Split(fieldTag, TagSeparator)
		filteredTags := []string{}
		for _, fieldTagEntry := range fieldTags {
			if fieldTagEntry != "omitempty" {
				filteredTags = append(filteredTags, fieldTagEntry)
			}
		}

		if len(filteredTags) == 1 && filteredTags[0] == "-" {
			continue
		} else if len(filteredTags) > 0 && filteredTags[0] != "" {
			fieldInfo.keys = filteredTags
		} else {
			fieldInfo.keys = []string{field.Name}
		}
		fieldsList = append(fieldsList, fieldInfo)
	}
	return fieldsList
}
开发者ID:YaSuenag,项目名称:hsbeat,代码行数:35,代码来源:reflect.go

示例10: readFromStruct

func (p *property) readFromStruct(t reflect.Type) {
	p.Type = "object"
	p.Properties = make(map[string]*property, 0)
	p.AdditionalProperties = false

	count := t.NumField()
	for i := 0; i < count; i++ {
		field := t.Field(i)

		tag := field.Tag.Get("json")
		name, opts := parseTag(tag)
		if name == "" {
			name = field.Name
		}

		p.Properties[name] = &property{}
		p.Properties[name].read(field.Type, opts)

		comment, ok := commentMap[field.Name]
		if ok {
			p.Properties[name].Description = comment
		}

		if !opts.Contains("omitempty") {
			p.Required = append(p.Required, name)
		}
	}
}
开发者ID:sushil,项目名称:go-jsonschema-generator,代码行数:28,代码来源:jsonschema.go

示例11: getFieldmap

// Create a fieldmap for a given type and return its fieldmap (or error)
func getFieldmap(t reflect.Type) (fm fieldmap, err error) {
	// if we have a fieldmap cached, return it
	t, err = BaseStructType(t)
	if err != nil {
		return nil, err
	}
	fm, ok := fieldmapCache[t]
	if ok {
		return fm, nil
	} else {
		fm = fieldmap{}
	}

	var f reflect.StructField
	var name string

	for i := 0; i < t.NumField(); i++ {
		f = t.Field(i)
		name = strings.ToLower(f.Name)
		if tag := f.Tag.Get("db"); tag != "" {
			name = tag
		}
		fm[name] = i
	}
	fieldmapCache[t] = fm
	return fm, nil
}
开发者ID:natefinch,项目名称:sqlx,代码行数:28,代码来源:sqlx.go

示例12: yamlTags

// yamlTags returns a map from yaml tag to the field index for the string fields in the given type.
func yamlTags(t reflect.Type) map[string]int {
	if t.Kind() != reflect.Struct {
		panic(errors.Errorf("cannot get yaml tags on type %s", t))
	}
	tags := make(map[string]int)
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		if f.Type != reflect.TypeOf("") {
			continue
		}
		if tag := f.Tag.Get("yaml"); tag != "" {
			if i := strings.Index(tag, ","); i >= 0 {
				tag = tag[0:i]
			}
			if tag == "-" {
				continue
			}
			if tag != "" {
				f.Name = tag
			}
		}
		tags[f.Name] = i
	}
	return tags
}
开发者ID:kat-co,项目名称:juju,代码行数:26,代码来源:clouds.go

示例13: serialiseStruct

func serialiseStruct(out io.Writer, v reflect.Value, t reflect.Type, context string, level uint, entities map[uint32][]byte) {
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		if f.Name == "XXX_unrecognized" {
			continue
		}
		fv := v.Field(i)

		switch f.Type.Kind() {
		case reflect.Slice:
			if f.Type.Elem().Kind() == reflect.Uint8 {
				serialiseValue(out, f.Name, fv, f.Type, context, level, entities)
			} else {
				if f.Type.Elem().Kind() == reflect.Ptr {
					for i := 0; i < fv.Len(); i++ {
						serialiseValue(out, f.Name, fv.Index(i).Elem(), f.Type.Elem().Elem(), context, level, entities)
					}
				} else {
					for i := 0; i < fv.Len(); i++ {
						serialiseValue(out, f.Name, fv.Index(i), f.Type.Elem(), context, level, entities)
					}
				}
			}
		case reflect.Ptr:
			if !fv.IsNil() {
				serialiseValue(out, f.Name, fv.Elem(), f.Type.Elem(), context, level, entities)
			}
		default:
			panic(fmt.Sprintf("Don't know how to serialize %s", f))
		}
	}
}
开发者ID:nico,项目名称:pond,代码行数:32,代码来源:editstate.go

示例14: QueryBuilder

func QueryBuilder(clause, tablename, input string, TableModel interface{}) (retVal string) {
	clause = strings.ToUpper(clause)
	retVal = ""

	if clause == "INSERT" {
		retVal += clause + " INTO " + tablename + " VALUES ("
	} else if clause == "ADD COLUMN" {
		retVal += "ALTER TABLE" + tablename + " ADD COLUMNS ("
	} else if clause == "SELECT" {
		retVal += "SELECT * FROM " + tablename + ";"
	}

	var v reflect.Type
	v = reflect.TypeOf(TableModel).Elem()

	if v.Kind() == reflect.Struct {
		for i := 0; i < v.NumField(); i++ {
			if clause == "INSERT" {
				retVal += input + ");"
				break
			} else if clause == "ADD COLUMN" {
				retVal += reflect.ValueOf(TableModel).Elem().Field(i).String() + " " + v.Field(i).Type.String()
			}

			if i < v.NumField()-1 {
				retVal += ","
			} else {
				retVal += ");"
			}
		}
	}
	return retVal
}
开发者ID:ranggaeaciit,项目名称:hdc,代码行数:33,代码来源:hive.go

示例15: addFields

func addFields(m *Model, t reflect.Type, v reflect.Value) {
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		sqlTag := field.Tag.Get("sql")
		if sqlTag == "-" {
			continue
		}
		if field.Anonymous && field.Type.Kind() == reflect.Struct {
			addFields(m, field.Type, v.Field(i))
			continue
		}
		parsedSqlTags := parseTags(sqlTag)
		rawValidateTag := field.Tag.Get("validate")
		parsedValidateTags := make(map[string]string)
		if len(rawValidateTag) > 0 {
			if rawValidateTag[:1] == "^" {
				parsedValidateTags["regexp"] = rawValidateTag
			} else {
				parsedValidateTags = parseTags(rawValidateTag)
			}
		}
		fd := &ModelField{
			Name:         toSnake(field.Name),
			Value:        v.FieldByName(field.Name).Interface(),
			SqlTags:      parsedSqlTags,
			ValidateTags: parsedValidateTags,
			RawTag:       field.Tag,
		}
		if fd.PrimaryKey() {
			m.Pk = fd
		}
		m.Fields = append(m.Fields, fd)
	}
}
开发者ID:kspector,项目名称:hood,代码行数:34,代码来源:hood.go


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