Structs: added Fields() method into Field struct for listing all the Fields of the given field if it is a struct.
This commit is contained in:
parent
8292271263
commit
852670f7c6
11
field.go
11
field.go
@ -85,6 +85,17 @@ func (f *Field) Set(val interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fields returns a slice of Fields. A struct tag with the content of "-"
|
||||
// ignores the checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// It panics if s's kind is not struct.
|
||||
func (f *Field) Fields() []*Field {
|
||||
return getFields(f.value)
|
||||
}
|
||||
|
||||
// Field returns the field from a nested struct. It panics if the nested struct
|
||||
// is not exported or if the field was not found.
|
||||
func (f *Field) Field(name string) *Field {
|
||||
|
||||
@ -257,6 +257,15 @@ func TestField_Field(t *testing.T) {
|
||||
_ = s.Field("Bar").Field("e")
|
||||
}
|
||||
|
||||
func TestField_Fields(t *testing.T) {
|
||||
s := newStruct()
|
||||
fields := s.Field("Bar").Fields()
|
||||
|
||||
if len(fields) != 3 {
|
||||
t.Errorf("We expect 3 fields in embedded struct, was: %d", len(fields))
|
||||
}
|
||||
}
|
||||
|
||||
func TestField_FieldOk(t *testing.T) {
|
||||
s := newStruct()
|
||||
|
||||
|
||||
12
structs.go
12
structs.go
@ -128,7 +128,15 @@ func (s *Struct) Values() []interface{} {
|
||||
//
|
||||
// It panics if s's kind is not struct.
|
||||
func (s *Struct) Fields() []*Field {
|
||||
t := s.value.Type()
|
||||
return getFields(s.value)
|
||||
}
|
||||
|
||||
func getFields(v reflect.Value) []*Field {
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
t := v.Type()
|
||||
|
||||
var fields []*Field
|
||||
|
||||
@ -141,7 +149,7 @@ func (s *Struct) Fields() []*Field {
|
||||
|
||||
f := &Field{
|
||||
field: field,
|
||||
value: s.value.FieldByName(field.Name),
|
||||
value: v.FieldByName(field.Name),
|
||||
}
|
||||
|
||||
fields = append(fields, f)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user