Merge pull request #14 from cihangir/fields
Structs: added Fields() method into Field struct for listing all the Fie...
This commit is contained in:
commit
1c1b7ed9a8
12
field.go
12
field.go
@ -85,6 +85,18 @@ func (f *Field) Set(val interface{}) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Fields returns a slice of Fields. This is particular handy to get the fields
|
||||
// of a nested struct . A struct tag with the content of "-" ignores the
|
||||
// checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field *http.Request `structs:"-"`
|
||||
//
|
||||
// It panics if field is not exported or if field'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