diff --git a/field.go b/field.go index c394f65..2758eeb 100644 --- a/field.go +++ b/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 { diff --git a/field_test.go b/field_test.go index ec728f9..fbecffb 100644 --- a/field_test.go +++ b/field_test.go @@ -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() diff --git a/structs.go b/structs.go index a15f7a0..637245f 100644 --- a/structs.go +++ b/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)