當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。