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


Golang Value.NumField方法代码示例

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


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

示例1: encodePacketValue

func encodePacketValue(buf []byte, v reflect.Value) (int, error) {
	n := 0
	switch v.Kind() {
	default:
		return n, ErrUnhandledFieldType
	case reflect.Struct:
		for i := 0; i < v.NumField(); i++ {
			field := v.Field(i)
			n2, err := encodePacketValue(buf[n:], field)
			n += n2
			if err != nil {
				return n, err
			}
		}
	case reflect.Bool:
		if v.Bool() {
			buf[n] = 1
		} else {
			buf[n] = 0
		}
		n += 1
	case reflect.Int32:
		binary.BigEndian.PutUint32(buf[n:n+4], uint32(v.Int()))
		n += 4
	case reflect.Int64:
		binary.BigEndian.PutUint64(buf[n:n+8], uint64(v.Int()))
		n += 8
	case reflect.String:
		str := v.String()
		binary.BigEndian.PutUint32(buf[n:n+4], uint32(len(str)))
		copy(buf[n+4:n+4+len(str)], []byte(str))
		n += 4 + len(str)
	case reflect.Slice:
		switch v.Type().Elem().Kind() {
		default:
			count := v.Len()
			startN := n
			n += 4
			for i := 0; i < count; i++ {
				n2, err := encodePacketValue(buf[n:], v.Index(i))
				n += n2
				if err != nil {
					return n, err
				}
			}
			binary.BigEndian.PutUint32(buf[startN:startN+4], uint32(count))
		case reflect.Uint8:
			if v.IsNil() {
				binary.BigEndian.PutUint32(buf[n:n+4], uint32(0xffffffff))
				n += 4
			} else {
				bytes := v.Bytes()
				binary.BigEndian.PutUint32(buf[n:n+4], uint32(len(bytes)))
				copy(buf[n+4:n+4+len(bytes)], bytes)
				n += 4 + len(bytes)
			}
		}
	}
	return n, nil
}
开发者ID:dboek,项目名称:go-zookeeper,代码行数:60,代码来源:structs.go

示例2: getSqlFieldsFromJson

func getSqlFieldsFromJson(updateData map[string]interface{}, v reflect.Value, sqlData map[string]interface{}) error {
	for i := 0; i < v.NumField(); i++ {
		if v.Type().Field(i).Type.Kind() == reflect.Struct {
			subUpdateData := updateData
			if tag := v.Type().Field(i).Tag.Get("json"); tag != "" {
				maybeSubUpdateData := updateData[tag]
				if yesSubUpdateData, ok := maybeSubUpdateData.(map[string]interface{}); ok {
					subUpdateData = yesSubUpdateData
				}
			}
			getSqlFieldsFromJson(subUpdateData, v.Field(i), sqlData)
			continue
		}

		fieldName := v.Type().Field(i).Name
		columnName := sqlCase(fieldName)
		if tag := v.Type().Field(i).Tag.Get("sql"); tag != "" {
			columnName = tag
		}
		jsonName := fieldName
		if tag := v.Type().Field(i).Tag.Get("json"); tag != "" {
			jsonName = tag
		}
		if val, ok := updateData[jsonName]; ok {
			sqlData[columnName] = val
		}
	}
	return nil
}
开发者ID:lental,项目名称:office-mapper,代码行数:29,代码来源:orm.go

示例3: isZero

func isZero(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Func, reflect.Map, reflect.Slice:
		return v.IsNil()
	case reflect.Array:
		z := true
		for i := 0; i < v.Len(); i++ {
			z = z && isZero(v.Index(i))
		}
		return z
	case reflect.Struct:
		if v.Type() == reflect.TypeOf(t) {
			if v.Interface().(time.Time).IsZero() {
				return true
			}
			return false
		}
		z := true
		for i := 0; i < v.NumField(); i++ {
			z = z && isZero(v.Field(i))
		}
		return z
	}
	// Compare other types directly:
	z := reflect.Zero(v.Type())
	return v.Interface() == z.Interface()
}
开发者ID:hortonworks,项目名称:kubernetes-yarn,代码行数:27,代码来源:params.go

示例4: isZero

// isZero reports whether the value is the zero of its type.
func isZero(val reflect.Value) bool {
	switch val.Kind() {
	case reflect.Array:
		for i := 0; i < val.Len(); i++ {
			if !isZero(val.Index(i)) {
				return false
			}
		}
		return true
	case reflect.Map, reflect.Slice, reflect.String:
		return val.Len() == 0
	case reflect.Bool:
		return !val.Bool()
	case reflect.Complex64, reflect.Complex128:
		return val.Complex() == 0
	case reflect.Chan, reflect.Func, reflect.Ptr:
		return val.IsNil()
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return val.Int() == 0
	case reflect.Float32, reflect.Float64:
		return val.Float() == 0
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return val.Uint() == 0
	case reflect.Struct:
		for i := 0; i < val.NumField(); i++ {
			if !isZero(val.Field(i)) {
				return false
			}
		}
		return true
	}
	panic("unknown type in isZero " + val.Type().String())
}
开发者ID:ds2dev,项目名称:gcc,代码行数:34,代码来源:encode.go

示例5: mergeStruct

func mergeStruct(out, in reflect.Value) {
	sprop := GetProperties(in.Type())
	for i := 0; i < in.NumField(); i++ {
		f := in.Type().Field(i)
		if strings.HasPrefix(f.Name, "XXX_") {
			continue
		}
		mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
	}

	if emIn, ok := in.Addr().Interface().(extensionsMap); ok {
		emOut := out.Addr().Interface().(extensionsMap)
		mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
	} else if emIn, ok := in.Addr().Interface().(extensionsBytes); ok {
		emOut := out.Addr().Interface().(extensionsBytes)
		bIn := emIn.GetExtensions()
		bOut := emOut.GetExtensions()
		*bOut = append(*bOut, *bIn...)
	}

	uf := in.FieldByName("XXX_unrecognized")
	if !uf.IsValid() {
		return
	}
	uin := uf.Bytes()
	if len(uin) > 0 {
		out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
	}
}
开发者ID:GaizkaRubio,项目名称:mesos-dns,代码行数:29,代码来源:clone.go

示例6: getTemplateFields

func getTemplateFields(keys []string, s reflect.Value) []TemplateField {
	var fields []TemplateField

	typeOfSpec := s.Type()
	for i := 0; i < s.NumField(); i++ {
		f := s.Field(i)
		t := typeOfSpec.Field(i)
		if f.CanSet() {
			fieldName := typeOfSpec.Field(i).Name

			if f.Kind() == reflect.Struct {
				keys = append(keys, fieldName)
				fields = append(fields, getTemplateFields(keys, f)...)
				continue
			}

			fields = append(fields, TemplateField{
				Name:   fieldName,
				Value:  f.Interface(),
				String: fmt.Sprintf("%#v", f.Interface()),
				Type:   t.Type,
				Tags:   getTags(t.Tag),
			})
		}
	}

	return fields
}
开发者ID:jmunson,项目名称:factorcfg,代码行数:28,代码来源:render.go

示例7: marshal

func marshal(buf []byte, prefix string, rv reflect.Value, inArray, arrayTable bool) ([]byte, error) {
	rt := rv.Type()
	for i := 0; i < rv.NumField(); i++ {
		ft := rt.Field(i)
		if !ast.IsExported(ft.Name) {
			continue
		}
		colName, rest := extractTag(rt.Field(i).Tag.Get(fieldTagName))
		if colName == tagSkip {
			continue
		}
		if colName == "" {
			colName = stringutil.ToSnakeCase(ft.Name)
		}
		fv := rv.Field(i)
		switch rest {
		case tagOmitempty:
			if fv.Interface() == reflect.Zero(ft.Type).Interface() {
				continue
			}
		}
		var err error
		if buf, err = encodeValue(buf, prefix, colName, fv, inArray, arrayTable); err != nil {
			return nil, err
		}
	}
	return buf, nil
}
开发者ID:ZhuZhengyi,项目名称:eris-db,代码行数:28,代码来源:encode.go

示例8: mapColumns

// mapColumns creates a list of field addresses and column maps, to
// make looking up the column for a field address easier.  Note that
// it doesn't do any special handling for overridden fields, because
// passing the address of a field that has been overridden is
// difficult to do accidentally.
func (plan *QueryPlan) mapColumns(table *TableMap, value reflect.Value) (err error) {
	value = value.Elem()
	valueType := value.Type()
	if plan.colMap == nil {
		plan.colMap = make(structColumnMap, 0, value.NumField())
	}
	quotedTableName := table.dbmap.Dialect.QuotedTableForQuery(table.SchemaName, table.TableName)
	for i := 0; i < value.NumField(); i++ {
		fieldType := valueType.Field(i)
		fieldVal := value.Field(i)
		if fieldType.Anonymous {
			if fieldVal.Kind() != reflect.Ptr {
				fieldVal = fieldVal.Addr()
			}
			plan.mapColumns(table, fieldVal)
		} else if fieldType.PkgPath == "" {
			col := table.ColMap(fieldType.Name)
			quotedCol := table.dbmap.Dialect.QuoteField(col.ColumnName)
			fieldMap := fieldColumnMap{
				addr:         fieldVal.Addr().Interface(),
				column:       col,
				quotedTable:  quotedTableName,
				quotedColumn: quotedCol,
			}
			plan.colMap = append(plan.colMap, fieldMap)
		}
	}
	return
}
开发者ID:Radiobox,项目名称:gorp,代码行数:34,代码来源:query_plans.go

示例9: writeStruct

func writeStruct(w io.Writer, val reflect.Value) (err error) {
	_, err = fmt.Fprint(w, "d")
	if err != nil {
		return
	}

	typ := val.Type()

	numFields := val.NumField()
	svList := make(stringValueArray, numFields)

	for i := 0; i < numFields; i++ {
		field := typ.Field(i)
		bencodeKey(field, &svList[i])
		// The tag `bencode:"-"` should mean that this field must be ignored
		// See https://golang.org/pkg/encoding/json/#Marshal or https://golang.org/pkg/encoding/xml/#Marshal
		// We set a zero value so that it is ignored by the writeSVList() function
		if svList[i].key == "-" {
			svList[i].value = reflect.Value{}
		} else {
			svList[i].value = val.Field(i)
		}
	}

	err = writeSVList(w, svList)
	if err != nil {
		return
	}

	_, err = fmt.Fprint(w, "e")
	if err != nil {
		return
	}
	return
}
开发者ID:skycoin,项目名称:skycoin,代码行数:35,代码来源:struct.go

示例10: azureStateRefreshFunc

func azureStateRefreshFunc(resourceURI string, client *ArmClient, command riviera.APICall) resource.StateRefreshFunc {
	return func() (interface{}, string, error) {
		req := client.rivieraClient.NewRequestForURI(resourceURI)
		req.Command = command

		res, err := req.Execute()
		if err != nil {
			return nil, "", fmt.Errorf("Error executing %T command in azureStateRefreshFunc", req.Command)
		}

		var value reflect.Value
		if reflect.ValueOf(res.Parsed).Kind() == reflect.Ptr {
			value = reflect.ValueOf(res.Parsed).Elem()
		} else {
			value = reflect.ValueOf(res.Parsed)
		}

		for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
			tag := value.Type().Field(i).Tag // returns the tag string
			tagValue := tag.Get("mapstructure")
			if tagValue == "provisioningState" {
				return res.Parsed, value.Field(i).Elem().String(), nil
			}
		}

		panic(fmt.Errorf("azureStateRefreshFunc called on structure %T with no mapstructure:provisioningState tag. This is a bug", res.Parsed))
	}
}
开发者ID:partamonov,项目名称:terraform,代码行数:28,代码来源:provider.go

示例11: approxDataSize

func approxDataSize(rv reflect.Value) (sum int) {
	switch rk := rv.Kind(); rk {
	case reflect.Invalid:
	case reflect.Ptr, reflect.Interface:
		sum += int(rv.Type().Size())
		sum += approxDataSize(rv.Elem())
	case reflect.Slice:
		sum += int(rv.Type().Size())
		for j := 0; j < rv.Len(); j++ {
			sum += approxDataSize(rv.Index(j))
		}
	case reflect.String:
		sum += int(rv.Type().Size())
		sum += rv.Len()
	case reflect.Map:
		sum += int(rv.Type().Size())
		for _, mk := range rv.MapKeys() {
			sum += approxDataSize(mk)
			sum += approxDataSize(rv.MapIndex(mk))
		}
	case reflect.Struct:
		//struct size already includes the full data size.
		//sum += int(rv.Type().Size())
		for j := 0; j < rv.NumField(); j++ {
			sum += approxDataSize(rv.Field(j))
		}
	default:
		//pure value types
		sum += int(rv.Type().Size())
	}
	return
}
开发者ID:winsx,项目名称:libnetwork,代码行数:32,代码来源:helper_test.go

示例12: readStruct

func readStruct(value reflect.Value, parentName string, optional bool) (err error) {
	for i := 0; i < value.NumField(); i++ {
		field := value.Field(i)
		name := value.Type().Field(i).Name

		tag := parseTag(value.Type().Field(i).Tag.Get("envconfig"))

		var combinedName string
		if tag.customName != "" {
			combinedName = tag.customName
		} else {
			combinedName = combineName(parentName, name)
		}

	doRead:
		switch field.Kind() {
		case reflect.Ptr:
			// it's a pointer, create a new value and restart the switch
			field.Set(reflect.New(field.Type().Elem()))
			field = field.Elem()
			goto doRead
		case reflect.Struct:
			err = readStruct(field, combinedName, optional || tag.optional)
		default:
			err = setField(field, combinedName, tag.customName != "", optional || tag.optional)
		}

		if err != nil {
			return err
		}
	}

	return
}
开发者ID:bfontaine,项目名称:stargazer,代码行数:34,代码来源:envconfig.go

示例13: Whitelist

func Whitelist(from interface{}, fields []string) map[string]interface{} {
	out := make(map[string]interface{})

	var v reflect.Value
	var t reflect.Type
	v = reflect.ValueOf(from)
	t = reflect.TypeOf(from)

	if reflect.Ptr == t.Kind() {
		v = v.Elem()
		t = t.Elem()
	}

	for i := 0; i < v.NumField(); i++ {
		valueOfField := v.Field(i)
		typeOfField := t.Field(i)

		val := valueOfField.Interface()
		name := strings.Split(typeOfField.Tag.Get("json"), ",")[0]

		if len(fields) > 0 && fields[0] != "" {
			if slice.StringInSlice(name, fields) {
				out[name] = val
			}
		} else {
			out[name] = val
		}
	}
	return out
}
开发者ID:gregory90,项目名称:go-webutils,代码行数:30,代码来源:web.go

示例14: 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

示例15: encodeStruct

func (e *Encoder) encodeStruct(rv reflect.Value, name string, inlist bool) error {
	err := e.emit(tagCompound, name, inlist)
	if err != nil {
		return err
	}

	rt := rv.Type()

	for i := 0; i < rv.NumField(); i++ {
		fv := rv.Field(i)
		ft := rt.Field(i)

		if hasField(ft.Tag.Get("nbt"), "omitempty") && isEmpty(fv) {
			continue
		}

		fname := tagField(ft.Tag.Get("nbt"), 0)
		if len(fname) == 0 {
			fname = ft.Name
		}

		// Special-case time.Time
		if e.isTime(ft.Type) {
			t := fv.Interface().(time.Time).Unix()
			fv = reflect.ValueOf(t)
		}

		err = e.encode(fv, fname, false)
		if err != nil {
			return err
		}
	}

	return e.writeU8(uint8(tagEnd))
}
开发者ID:trichner,项目名称:mctools,代码行数:35,代码来源:encoder.go


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