本文整理汇总了Golang中reflect.Value.FieldByName方法的典型用法代码示例。如果您正苦于以下问题:Golang Value.FieldByName方法的具体用法?Golang Value.FieldByName怎么用?Golang Value.FieldByName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reflect.Value
的用法示例。
在下文中一共展示了Value.FieldByName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: SetValue
func (cfg *PageHeader) SetValue(key string, value string, s *reflect.Value) {
// put unknown fields into a map
if _, ok := s.Type().FieldByName(key); !ok {
cfg.Other[key] = strings.TrimSpace(value)
return
}
// Set value
f := s.FieldByName(key)
switch f.Interface().(type) {
default:
errhandle(fmt.Errorf("Unknown type of field %s", key))
case string:
f.SetString(value)
case []string:
values := strings.Split(value, ",")
for i, v := range values {
values[i] = strings.TrimSpace(v)
}
f.Set(reflect.ValueOf(values))
case time.Time:
var t time.Time
var err error
for _, fmt := range DATEFORMATS {
t, err = time.Parse(fmt, value)
if err == nil {
break
}
}
errhandle(err)
f.Set(reflect.ValueOf(t))
}
}
示例2: ScanToStruct
func (scan *Scan) ScanToStruct(rows *sql.Rows, record reflect.Value) error {
columns, err := rows.Columns()
if err != nil {
return err
}
values := make([]interface{}, len(columns))
for i, column := range columns {
var field reflect.Value
fieldName := scan.SQLColumnDict[column]
if scan.ToPointers {
field = record.Elem().FieldByName(fieldName)
} else {
field = record.FieldByName(fieldName)
}
if field.IsValid() {
values[i] = field.Addr().Interface()
} else {
values[i] = &values[i]
}
}
return rows.Scan(values...)
}
示例3: findPopulatePath
func (q *Query) findPopulatePath(path string) {
parts := strings.Split(path, ".")
resultVal := reflect.ValueOf(q.parentStruct).Elem()
var refVal reflect.Value
partsLen := len(parts)
for i := 0; i < partsLen; i++ {
elem := parts[i]
if i == 0 {
refVal = resultVal.FieldByName(elem)
structTag, _ := resultVal.Type().FieldByName(elem)
q.popSchema = structTag.Tag.Get(q.z.modelTag)
} else if i == partsLen-1 {
structTag, _ := refVal.Type().FieldByName(elem)
q.popSchema = structTag.Tag.Get(q.z.modelTag)
refVal = refVal.FieldByName(elem)
} else {
//refVal = handleSlice(refVal, elem, path)
refVal = refVal.FieldByName(elem)
}
if !refVal.IsValid() {
panic("field `" + elem + "` not found in populate path `" + path + "`")
}
}
if refVal.Kind() == reflect.Slice {
q.isSlice = true
}
q.populateField = refVal.Interface()
}
示例4: getFields
func getFields(v reflect.Value, tagName string) []*Field {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
t := v.Type()
var fields []*Field
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if tag := field.Tag.Get(tagName); tag == "-" {
continue
}
f := &Field{
field: field,
value: v.FieldByName(field.Name),
}
fields = append(fields, f)
}
return fields
}
示例5: 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
}
示例6: unmarshalSettings
// unmarshalSettings sets for all its settings the relating field of v.
func unmarshalSettings(settings SettingList, v reflect.Value) {
for _, s := range settings {
field := v.FieldByName(upperFirst(s.Name()))
if !field.CanSet() {
continue
}
switch s.Type() {
case String:
if field.Kind() == reflect.String {
field.SetString(s.AsString())
}
case Integer:
switch field.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if s.AsInteger() >= 0 {
field.SetUint(uint64(s.AsInteger()))
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
field.SetInt(s.AsInteger())
}
case Real:
if field.Kind() == reflect.Float32 || field.Kind() == reflect.Float64 {
field.SetFloat(s.AsReal())
}
}
}
}
示例7: 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...))
}
}
示例8: DelQuery
// DelQuery will delete (from datastore and memcache) all entities of type src that matches q.
// src must be a pointer to a struct type.
func DelQuery(c PersistenceContext, src interface{}, q *datastore.Query) (err error) {
var dataIds []*datastore.Key
results := reflect.New(reflect.SliceOf(reflect.TypeOf(src).Elem()))
dataIds, err = q.GetAll(c, results.Interface())
if err = FilterOkErrors(err); err != nil {
return
}
memcacheKeys := []string{}
var el reflect.Value
resultsSlice := results.Elem()
for index, dataId := range dataIds {
el = resultsSlice.Index(index)
var k key.Key
if k, err = gaekey.FromGAE(dataId); err != nil {
return
}
el.FieldByName("Id").Set(reflect.ValueOf(k))
if _, err = MemcacheKeys(c, el.Addr().Interface(), &memcacheKeys); err != nil {
return
}
if err = runProcess(c, el.Addr().Interface(), BeforeDeleteName, nil); err != nil {
return
}
}
if err = datastore.DeleteMulti(c, dataIds); err != nil {
return
}
for index, _ := range dataIds {
el = resultsSlice.Index(index)
if err = runProcess(c, el.Addr().Interface(), AfterDeleteName, nil); err != nil {
return
}
}
return memcache.Del(c, memcacheKeys...)
}
示例9: setFieldDefaults
func setFieldDefaults(v reflect.Value, sf reflect.StructField, s reflect.Value) {
if v.CanInterface() && reflect.DeepEqual(
v.Interface(), reflect.Zero(v.Type()).Interface()) {
tag := sf.Tag.Get("ebmldef")
if tag != "" {
switch v.Kind() {
case reflect.Int, reflect.Int64:
u, _ := strconv.ParseInt(tag, 10, 0)
v.SetInt(int64(u))
case reflect.Uint, reflect.Uint64:
u, _ := strconv.ParseUint(tag, 10, 0)
v.SetUint(u)
case reflect.Float32, reflect.Float64:
f, _ := strconv.ParseFloat(tag, 64)
v.SetFloat(f)
case reflect.String:
v.SetString(tag)
default:
log.Panic("Unsupported default value")
}
}
ltag := sf.Tag.Get("ebmldeflink")
if ltag != "" {
v.Set(s.FieldByName(ltag))
}
}
}
示例10: decodeStruct
func (d *decoder) decodeStruct(src hl7.Data, dst reflect.Value) {
typ := dst.Type()
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
fieldName := field.Name
fieldValue := dst.FieldByName(fieldName)
// So just skip it.
if !fieldValue.CanSet() {
d.err.append(fmt.Errorf("%s.%s is not settable", typ.Name(), fieldName))
continue
}
index := i
if _, ok := src.(hl7.Segment); ok {
index += 1
}
newSrc, ok := src.Index(index)
if !ok {
//d.err.append(fmt.Errorf("could not find src index for %s.%s", typ.Name(), fieldName))
continue
}
d.decode(newSrc, fieldValue)
}
}
示例11: encodeStruct
func (e *encoder) encodeStruct(val reflect.Value) {
fmt.Fprint(e, "<struct>")
t := val.Type()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
v := val.FieldByName(f.Name)
if e.isNil(v) {
continue
}
fmt.Fprintf(e, "<member>")
name := f.Tag.Get("xmlrpc")
if name == "" {
name = f.Name
}
fmt.Fprintf(e, "<name>%s</name>", name)
e.encodeValue(v)
fmt.Fprintf(e, "</member>")
}
fmt.Fprint(e, "</struct>")
}
示例12: applyToStruct
func applyToStruct(obj reflect.Value, head P, mid string, tail P, ctx *Context) error {
if mid != "*" {
result := obj.FieldByName(mid)
if result.Kind() == reflect.Invalid {
result = obj.MethodByName(mid)
}
if result.Kind() == reflect.Invalid {
return fmt.Errorf("no field '%s' in type '%s' at '%s'", mid, obj.Type(), head)
}
return apply(result, append(head, mid), tail, ctx)
}
typ := obj.Type()
for i := 0; i < typ.NumField() && !ctx.stop; i++ {
if err := applyToStruct(obj, head, typ.Field(i).Name, tail, ctx); err != nil && err != ErrMissing {
return err
}
}
return nil
}
示例13: skipField
func skipField(v reflect.Value, f reflect.StructField) bool {
// no tag on the structure field
name := f.Tag.Get("when")
if name == "" {
return false
}
// invalid field in tag
f1 := v.FieldByName(name)
if !f1.IsValid() {
return false
}
// target field is not a string
if f1.Type().Kind() != reflect.String {
return false
}
target := f1.String()
value := f.Tag.Get("value")
switch f.Tag.Get("cond") {
case "is":
// skip when target equals value
return (target == value)
case "not":
return (target != value)
}
return false
}
示例14: setDefaults
func setDefaults(properties []PropertyDocs, defaults reflect.Value) {
for i := range properties {
prop := &properties[i]
fieldName := proptools.FieldNameForProperty(prop.Name)
f := defaults.FieldByName(fieldName)
if (f == reflect.Value{}) {
panic(fmt.Errorf("property %q does not exist in %q", fieldName, defaults.Type()))
}
if reflect.DeepEqual(f.Interface(), reflect.Zero(f.Type()).Interface()) {
continue
}
if f.Type().Kind() == reflect.Interface {
f = f.Elem()
}
if f.Type().Kind() == reflect.Ptr {
f = f.Elem()
}
if f.Type().Kind() == reflect.Struct {
setDefaults(prop.Properties, f)
} else {
prop.Default = fmt.Sprintf("%v", f.Interface())
}
}
}
示例15: Models2Intslice
// model中类型提取其中的 idField(int 类型) 属性组成 slice 返回
func Models2Intslice(models interface{}, idField string) []int {
if models == nil {
return []int{}
}
// 类型检查
modelsValue := reflect.ValueOf(models)
if modelsValue.Kind() != reflect.Slice {
return []int{}
}
var modelValue reflect.Value
length := modelsValue.Len()
ids := make([]int, 0, length)
for i := 0; i < length; i++ {
modelValue = reflect.Indirect(modelsValue.Index(i))
if modelValue.Kind() != reflect.Struct {
continue
}
val := modelValue.FieldByName(idField)
if val.Kind() != reflect.Int {
continue
}
ids = append(ids, int(val.Int()))
}
return ids
}