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


Golang Value.FieldByIndex方法代码示例

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


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

示例1: encodeStruct

// encodeStruct encodes a single struct value.
func (enc *Encoder) encodeStruct(b *encBuffer, engine *encEngine, value reflect.Value) {
	if !valid(value) {
		return
	}
	state := enc.newEncoderState(b)
	defer enc.freeEncoderState(state)
	state.fieldnum = -1
	for i := 0; i < len(engine.instr); i++ {
		instr := &engine.instr[i]
		if i >= value.NumField() {
			// encStructTerminator
			instr.op(instr, state, reflect.Value{})
			break
		}
		field := value.FieldByIndex(instr.index)
		if instr.indir > 0 {
			field = encIndirect(field, instr.indir)
			// TODO: Is field guaranteed valid? If so we could avoid this check.
			if !valid(field) {
				continue
			}
		}
		instr.op(instr, state, field)
	}
}
开发者ID:sreis,项目名称:go,代码行数:26,代码来源:encode.go

示例2: structToMap

func structToMap(vstruct reflect.Value, schema Schema) (map[string]Value, error) {
	if vstruct.Kind() == reflect.Ptr {
		vstruct = vstruct.Elem()
	}
	if !vstruct.IsValid() {
		return nil, nil
	}
	m := map[string]Value{}
	if vstruct.Kind() != reflect.Struct {
		return nil, fmt.Errorf("bigquery: type is %s, need struct or struct pointer", vstruct.Type())
	}
	fields, err := fieldCache.Fields(vstruct.Type())
	if err != nil {
		return nil, err
	}
	for _, schemaField := range schema {
		// Look for an exported struct field with the same name as the schema
		// field, ignoring case.
		structField := fields.Match(schemaField.Name)
		if structField == nil {
			continue
		}
		val, err := structFieldToUploadValue(vstruct.FieldByIndex(structField.Index), schemaField)
		if err != nil {
			return nil, err
		}
		// Add the value to the map, unless it is nil.
		if val != nil {
			m[schemaField.Name] = val
		}
	}
	return m, nil
}
开发者ID:trythings,项目名称:trythings,代码行数:33,代码来源:value.go

示例3: marshal

// marshal is the internal version of Marshal.
func marshal(p *Params, xv reflect.Value, pt *requestType) error {
	xv = xv.Elem()
	for _, f := range pt.fields {
		fv := xv.FieldByIndex(f.index)
		if f.isPointer {
			if fv.IsNil() {
				continue
			}
			fv = fv.Elem()
		}
		// TODO store the field name in the field so
		// that we can produce a nice error message.
		if err := f.marshal(fv, p); err != nil {
			return errgo.WithCausef(err, ErrUnmarshal, "cannot marshal field")
		}
	}
	path, err := buildPath(p.Request.URL.Path, p.PathVar)
	if err != nil {
		return errgo.Mask(err)
	}
	p.Request.URL.Path = path
	if q := p.Request.Form.Encode(); q != "" && p.Request.URL.RawQuery != "" {
		p.Request.URL.RawQuery += "&" + q
	} else {
		p.Request.URL.RawQuery += q
	}
	return nil
}
开发者ID:cmars,项目名称:oo,代码行数:29,代码来源:marshal.go

示例4: marshalStruct

func marshalStruct(value reflect.Value) map[string]*dynamodb.AttributeValue {
	t := value.Type()

	numField := t.NumField()

	ret := make(map[string]*dynamodb.AttributeValue)
	for i := 0; i < numField; i++ {
		f := t.Field(i)

		if f.PkgPath != "" {
			continue
		}

		name, option := parseTag(f.Tag.Get("json"))
		if name == "-" {
			continue
		}
		if option == "omitifempty" {
			continue
		}
		if name == "" {
			name = f.Name
		}
		ret[name] = marshalValue(value.FieldByIndex(f.Index))
	}

	return ret
}
开发者ID:runtakun,项目名称:dynamodb-marshaler-go,代码行数:28,代码来源:marshal.go

示例5: unmarshalPaths

// unmarshalPaths walks down an XML structure looking for
// wanted paths, and calls unmarshal on them.
func (p *Parser) unmarshalPaths(sv reflect.Value, paths map[string]pathInfo, path string, start *StartElement) os.Error {
	if info, _ := paths[path]; info.complete {
		return p.unmarshal(sv.FieldByIndex(info.fieldIdx), start)
	}
	for {
		tok, err := p.Token()
		if err != nil {
			return err
		}
		switch t := tok.(type) {
		case StartElement:
			k := path + ">" + fieldName(t.Name.Local)
			if _, found := paths[k]; found {
				if err := p.unmarshalPaths(sv, paths, k, &t); err != nil {
					return err
				}
				continue
			}
			if err := p.Skip(); err != nil {
				return err
			}
		case EndElement:
			return nil
		}
	}
	panic("unreachable")
}
开发者ID:Quantumboost,项目名称:gcc,代码行数:29,代码来源:read.go

示例6: oneStruct

// oneStruct scans the result into a single struct type
func (r Result) oneStruct(columns []string, elem reflect.Value, obj interface{}) error {
	fields := DeepFields(obj)
	aligned := AlignFields(columns, fields)

	// Create an interface pointer for each column's destination.
	// Unmatched scanner values will be discarded
	dest := make([]interface{}, len(columns))

	// If nothing matched and the number of fields equals the number
	// columns, then blindly align columns and fields
	// TODO This may be too friendly of a feature
	if NoMatchingFields(aligned) && len(fields) == len(columns) {
		aligned = fields
	}
	for i, field := range aligned {
		if field.Exists() {
			dest[i] = elem.FieldByIndex(field.Type.Index).Addr().Interface()
		} else {
			dest[i] = &dest[i] // Discard
		}
	}

	if err := r.Scan(dest...); err != nil {
		return fmt.Errorf("sol: error scanning struct: %s", err)
	}
	return r.Err() // Check for delayed scan errors
}
开发者ID:aodin,项目名称:sol,代码行数:28,代码来源:result.go

示例7: Pack

func (f Fields) Pack(buf []byte, val reflect.Value) error {
	for val.Kind() == reflect.Ptr {
		val = val.Elem()
	}
	pos := 0
	for i, field := range f {
		if !field.CanSet {
			continue
		}
		v := val.Field(i)
		length := field.Len
		if field.Sizefrom != nil {
			length = int(val.FieldByIndex(field.Sizefrom).Int())
		}
		if length <= 0 && field.Slice {
			length = field.Size(v)
		}
		if field.Sizeof != nil {
			length := val.FieldByIndex(field.Sizeof).Len()
			v = reflect.ValueOf(length)
		}
		err := field.Pack(buf[pos:], v, length)
		if err != nil {
			return err
		}
		pos += field.Size(v)
	}
	return nil
}
开发者ID:bjyoungblood,项目名称:struc,代码行数:29,代码来源:fields.go

示例8: getField

// support multiple name casting: snake, lowercases
func (m Master) getField(v reflect.Value, schema string) (f reflect.Value, pos int) {
	// TODO: indirect(v) here is overkill?
	names := strings.Split(schema, m.SchemaSeparator)
	for _, name := range names {
		v = indirect(v)
		if v.Kind() != reflect.Struct {
			break
		}

		num := v.NumField()
		vt := v.Type()
		for i := 0; i < num; i++ {
			sf := vt.FieldByIndex([]int{i})
			options := strings.Split(sf.Tag.Get("sqlkungfu"), ",")
			if options[0] == name || strings.ToLower(sf.Name) == name {
				f = v.FieldByIndex([]int{i})
				break
			}

			if indirectT(sf.Type).Kind() == reflect.Struct && (sf.Anonymous || optionsContain(options[1:], "inline") || len(names) > 1) {
				if f, _ = m.getField(v.FieldByIndex([]int{i}), name); f.IsValid() {
					break
				}
			}
		}

		if f.IsValid() {
			v = f
			pos++
			continue
		}
	}

	return
}
开发者ID:valm0unt,项目名称:sqlkungfu,代码行数:36,代码来源:unmarshal.go

示例9: flattenStruct

func flattenStruct(args Args, v reflect.Value) Args {
	ss := structSpecForType(v.Type())
	for _, fs := range ss.l {
		fv := v.FieldByIndex(fs.index)
		if fv.CanAddr() {
			addr := fv.Addr().Interface()
			if ec, ok := addr.(gob.GobEncoder); ok {
				if buf, err := ec.GobEncode(); err == nil {
					args = append(args, fs.name, buf)
					return args
				}
			} else if ec, ok := addr.(json.Marshaler); ok {
				if buf, err := ec.MarshalJSON(); err == nil {
					args = append(args, fs.name, buf)
					return args
				}
			} else if ec, ok := addr.(encoding.BinaryMarshaler); ok {
				if buf, err := ec.MarshalBinary(); err != nil {
					args = append(args, fs.name, buf)
					return args
				}
			}
		}
		args = append(args, fs.name, fv.Interface())
	}
	return args
}
开发者ID:hongzhen,项目名称:redigo,代码行数:27,代码来源:scan.go

示例10: isSameStruct

// isSameUnknownStruct returns true if the two struct values are the same length
// and have the same contents as defined by IsSame. This function explicitly
// ignores the declared type of the struct.
func isSameStruct(x, y reflect.Value) bool {

	sx, okx := x.Interface().(StringConvertable)
	sy, oky := x.Interface().(StringConvertable)

	if okx && oky {
		//log.Println("Stringable", x, y)
		return sx.String() == sy.String()
	}

	numFields := x.NumField()

	if numFields != y.NumField() {
		return false
	}

	typeX := x.Type()

	for i := 0; i < numFields; i++ {
		path := []int{i}
		vx := x.FieldByIndex(path)
		vy := y.FieldByName(typeX.Field(i).Name)
		if vx.CanInterface() && vy.CanInterface() {
			if !IsSame(vx.Interface(), vy.Interface()) {
				return false
			}
		}
	}

	return true
}
开发者ID:russolsen,项目名称:same,代码行数:34,代码来源:same.go

示例11: GetColVals

func GetColVals(val reflect.Value, cols []string) (values []string, err error) {
	typ := val.Type()
	// if not struct, then must just have one column.
	if val.Kind() != reflect.Struct && len(cols) != 1 {
		return nil, fmt.Errorf("GetColVals> If not a struct(%s), must have one column: %v", val.Kind(), cols)
	}

	values = make([]string, len(cols))
	for i, col := range cols {
		var fieldVal reflect.Value
		if val.Kind() == reflect.Struct {
			fieldIndex := getFieldIndexByName(typ, col)
			if fieldIndex[0] < 0 {
				return nil, fmt.Errorf("GetColVals> Can't found struct field(column): '%s'\n", col)
			}
			fieldVal = val.FieldByIndex(fieldIndex)
		} else {
			fieldVal = val
		}

		if values[i], err = GetValQuoteStr(fieldVal); err != nil {
			return
		}
	}

	return
}
开发者ID:Carbyn,项目名称:sphinx,代码行数:27,代码来源:sphinxql.go

示例12: Delete

// execute delete sql dbQuerier with given struct reflect.Value.
// delete index is pk.
func (d *dbBase) Delete(q dbQuerier, mi *modelInfo, ind reflect.Value, tz *time.Location) (int64, error) {
	pkName, pkValue, ok := getExistPk(mi, ind)
	if ok == false {
		return 0, ErrMissPK
	}

	Q := d.ins.TableQuote()

	query := fmt.Sprintf("DELETE FROM %s%s%s WHERE %s%s%s = ?", Q, mi.table, Q, Q, pkName, Q)

	d.ins.ReplaceMarks(&query)
	res, err := q.Exec(query, pkValue)
	if err == nil {
		num, err := res.RowsAffected()
		if err != nil {
			return 0, err
		}
		if num > 0 {
			if mi.fields.pk.auto {
				if mi.fields.pk.fieldType&IsPositiveIntegerField > 0 {
					ind.FieldByIndex(mi.fields.pk.fieldIndex).SetUint(0)
				} else {
					ind.FieldByIndex(mi.fields.pk.fieldIndex).SetInt(0)
				}
			}
			err := d.deleteRels(q, mi, []interface{}{pkValue}, tz)
			if err != nil {
				return num, err
			}
		}
		return num, err
	}
	return 0, err
}
开发者ID:GrimTheReaper,项目名称:beego,代码行数:36,代码来源:db.go

示例13: encodeStruct

func (e *Encoder) encodeStruct(av *dynamodb.AttributeValue, v reflect.Value) error {

	// To maintain backwards compatibility with ConvertTo family of methods which
	// converted time.Time structs to strings
	if t, ok := v.Interface().(time.Time); ok {
		s := t.Format(time.RFC3339Nano)
		av.S = &s
		return nil
	}

	av.M = map[string]*dynamodb.AttributeValue{}
	fields := unionStructFields(v.Type(), e.MarshalOptions)
	for _, f := range fields {
		if f.Name == "" {
			return &InvalidMarshalError{msg: "map key cannot be empty"}
		}

		fv := v.FieldByIndex(f.Index)
		elem := &dynamodb.AttributeValue{}
		err := e.encode(elem, fv, f.tag)
		skip, err := keepOrOmitEmpty(f.OmitEmpty, elem, err)
		if err != nil {
			return err
		} else if skip {
			continue
		}

		av.M[f.Name] = elem
	}
	if len(av.M) == 0 {
		encodeNull(av)
	}

	return nil
}
开发者ID:Xercoy,项目名称:aws-sdk-go,代码行数:35,代码来源:encode.go

示例14: AppendValue

func (f *field) AppendValue(dst []byte, v reflect.Value, quote bool) []byte {
	fv := v.FieldByIndex(f.index)
	if f.Is(nullEmpty) && isEmptyValue(fv) {
		return appendNull(dst, quote)
	}
	return f.appender(dst, fv, quote)
}
开发者ID:nicholasray,项目名称:sandstone,代码行数:7,代码来源:types.go

示例15: HtmlView

func (t *structType) HtmlView(v reflect.Value) (html template.HTML, err error) {
	err = t.init()
	if err != nil {
		return
	}
	type templateRow struct {
		Path string
		Name string
		Html template.HTML
	}
	var templateData []templateRow
	for _, sf := range t.fields {
		var thisHtml template.HTML
		thisHtml, err = sf.Type.HtmlView(v.FieldByIndex(sf.Index))
		if err != nil {
			return
		}
		templateData = append(templateData, templateRow{
			Path: sf.Name,
			Name: sf.Name,
			Html: thisHtml,
		})
	}
	return theTemplate.ExecuteNameToHtml("Struct", templateData)
}
开发者ID:iizotop,项目名称:kmg,代码行数:25,代码来源:structType.go


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