本文整理汇总了Golang中reflect.Value.Field方法的典型用法代码示例。如果您正苦于以下问题:Golang Value.Field方法的具体用法?Golang Value.Field怎么用?Golang Value.Field使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reflect.Value
的用法示例。
在下文中一共展示了Value.Field方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: WriteValue
func (par field) WriteValue(out io.Writer, valueOf reflect.Value) error {
if (par.Flags & (fieldNotAny | fieldFollowedBy)) != 0 {
return nil
}
if par.Index < 0 { // We can not out this value in all cases but if it was literal we can do it
// TODO: Check if it is string and output only in case it is literal
p := par.Parse
v := valueOf
for {
switch tp := p.(type) {
case *ptrParser:
p = tp.Parser
if v.IsNil() {
if tp.Optional {
return nil
}
return errors.New("Ptr value is nil")
}
v = v.Elem()
break
case *literalParser:
_, err := out.Write([]byte(tp.Literal))
return err
default:
return errors.New("Could not out anonymous field if it is not literal")
}
}
} else {
f := valueOf.Field(par.Index)
return par.Parse.WriteValue(out, f)
}
}
示例2: 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))
}
示例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()
}
示例4: readStruct
func readStruct(in io.Reader, obj reflect.Value) {
for i := 0; i < obj.Type().NumField(); i++ {
if obj.Type().Field(i).PkgPath == "" {
readAny(in, obj.Field(i))
}
}
}
示例5: addStruct
func (e *encoder) addStruct(v reflect.Value) {
sinfo, err := getStructInfo(v.Type())
if err != nil {
panic(err)
}
var value reflect.Value
if sinfo.InlineMap >= 0 {
m := v.Field(sinfo.InlineMap)
if m.Len() > 0 {
for _, k := range m.MapKeys() {
ks := k.String()
if _, found := sinfo.FieldsMap[ks]; found {
panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", ks))
}
e.addElem(ks, m.MapIndex(k), false)
}
}
}
for _, info := range sinfo.FieldsList {
if info.Inline == nil {
value = v.Field(info.Num)
} else {
value = v.FieldByIndex(info.Inline)
}
if info.OmitEmpty && isZero(value) {
continue
}
e.addElem(info.Key, value, info.MinSize)
}
}
示例6: 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)
}
}
示例7: findFieldInValue
func (j *JSONPath) findFieldInValue(value *reflect.Value, node *FieldNode) (reflect.Value, error) {
t := value.Type()
var inlineValue *reflect.Value
for ix := 0; ix < t.NumField(); ix++ {
f := t.Field(ix)
jsonTag := f.Tag.Get("json")
parts := strings.Split(jsonTag, ",")
if len(parts) == 0 {
continue
}
if parts[0] == node.Value {
return value.Field(ix), nil
}
if len(parts[0]) == 0 {
val := value.Field(ix)
inlineValue = &val
}
}
if inlineValue != nil {
if inlineValue.Kind() == reflect.Struct {
// handle 'inline'
match, err := j.findFieldInValue(inlineValue, node)
if err != nil {
return reflect.Value{}, err
}
if match.IsValid() {
return match, nil
}
}
}
return value.FieldByName(node.Value), nil
}
示例8: 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
}
示例9: 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
}
示例10: addNode
// 向tree.nodes中添加元素。
// originV v的原始值,比如originV可能是指针,而v绝对不会是指针。
func (t *tree) addNode(field reflect.StructField, v, originV reflect.Value) error {
name := tag.MustGet(field.Tag.Get("ini"), "name", field.Name)[0]
t.nodes[name] = make(map[string]*elem)
typ := v.Type()
for i := 0; i < typ.NumField(); i++ {
f := v.Field(i)
if f.Kind() == reflect.Ptr {
f = f.Elem()
}
if f.Kind() == reflect.Ptr {
return fmt.Errorf("[%v]的值为指针的指针", name)
}
if f.Kind() == reflect.Struct {
return errors.New("不支持多层嵌套")
}
if err := addElem(t.nodes[name], typ.Field(i), v.Field(i), originV); err != nil {
return err
}
}
return nil
}
示例11: marshalStruct
func (state *marshalState) marshalStruct(v reflect.Value) error {
state.writeString("<< ")
t := v.Type()
n := v.NumField()
for i := 0; i < n; i++ {
f := t.Field(i)
if f.PkgPath != "" {
continue
}
tag, omitEmpty := f.Name, false
if tv := f.Tag.Get("pdf"); tv != "" {
if tv == "-" {
continue
}
name, options := parseTag(tv)
if name != "" {
tag = name
}
omitEmpty = options.Contains("omitempty")
}
fieldValue := v.Field(i)
if omitEmpty && isEmptyValue(fieldValue) {
continue
}
state.marshalKeyValue(name(tag), fieldValue)
}
state.writeString(">>")
return nil
}
示例12: 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
}
示例13: structValue
func structValue(m map[string]reflect.Value, value reflect.Value) {
if value.Type().Implements(typeValuer) {
return
}
switch value.Kind() {
case reflect.Ptr:
if value.IsNil() {
return
}
structValue(m, value.Elem())
case reflect.Struct:
t := value.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" && !field.Anonymous {
// unexported
continue
}
tag := field.Tag.Get("db")
if tag == "-" {
// ignore
continue
}
if tag == "" {
// no tag, but we can record the field name
tag = camelCaseToSnakeCase(field.Name)
}
fieldValue := value.Field(i)
if _, ok := m[tag]; !ok {
m[tag] = fieldValue
}
structValue(m, fieldValue)
}
}
}
示例14: setStruct
func (c *Client) setStruct(directory string, value *reflect.Value) (err error) {
tv := value.Type()
for i := 0; i < value.NumField(); i++ {
if tagv := tv.Field(i).Tag.Get(c.tag); tagv != "" {
field := value.Field(i)
if field.Kind() == reflect.Struct {
if err := c.setStruct(path.Join(directory, tagv), &field); err != nil {
return err
}
} else {
key := path.Join(directory, tagv)
response, err := c.client.Get(key, false, false)
if err != nil {
return err
}
value := response.Node.Value
switch field.Kind() {
case reflect.String:
field.SetString(value)
case reflect.Int64:
i, _ := strconv.Atoi(value)
field.SetInt(int64(i))
case reflect.Int:
i, _ := strconv.Atoi(value)
field.SetInt(int64(i))
}
}
}
}
return nil
}
示例15: appendStruct
// appendStruct is an internal helper function to AppendConfig. Given two values
// of structures (assumed to be the same type), recursively iterate over every
// field in the struct, appending slices, recursively appending structs, and
// overwriting old values with the new for all other types. Individual fields
// are able to override their merge strategy using the "merge" tag. Accepted
// values are "new" or "old": "new" uses the new value, "old" uses the old
// value. These are currently only used for "ignition.config" and
// "ignition.version".
func appendStruct(vOld, vNew reflect.Value) reflect.Value {
tOld := vOld.Type()
vRes := reflect.New(tOld)
for i := 0; i < tOld.NumField(); i++ {
vfOld := vOld.Field(i)
vfNew := vNew.Field(i)
vfRes := vRes.Elem().Field(i)
switch tOld.Field(i).Tag.Get("merge") {
case "old":
vfRes.Set(vfOld)
continue
case "new":
vfRes.Set(vfNew)
continue
}
switch vfOld.Type().Kind() {
case reflect.Struct:
vfRes.Set(appendStruct(vfOld, vfNew))
case reflect.Slice:
vfRes.Set(reflect.AppendSlice(vfOld, vfNew))
default:
vfRes.Set(vfNew)
}
}
return vRes.Elem()
}