diff --git a/README.md b/README.md index 598c961..dfe07d6 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,9 @@ value := name.Value().(string) // Set the field's value name.Set("another gopher") +// Get the field's kind, kind => "string" +name.Kind() + // Check if the field is exported or not if name.IsExported() { fmt.Println("Name field is exported") diff --git a/field.go b/field.go index c557fb8..c394f65 100644 --- a/field.go +++ b/field.go @@ -54,6 +54,11 @@ func (f *Field) Name() string { return f.field.Name } +// Kind returns the fields kind, such as "string", "map", "bool", etc .. +func (f *Field) Kind() reflect.Kind { + return f.value.Kind() +} + // Set sets the field to given value v. It retuns an error if the field is not // settable (not addresable or not exported) or if the given value's type // doesn't match the fields type. diff --git a/field_test.go b/field_test.go index 96afa57..ec728f9 100644 --- a/field_test.go +++ b/field_test.go @@ -1,6 +1,9 @@ package structs -import "testing" +import ( + "reflect" + "testing" +) // A test struct that defines all cases type Foo struct { @@ -109,6 +112,26 @@ func TestField(t *testing.T) { _ = s.Field("no-field") } +func TestField_Kind(t *testing.T) { + s := newStruct() + + f := s.Field("A") + if f.Kind() != reflect.String { + t.Errorf("Field A has wrong kind: %s want: %s", f.Kind(), reflect.String) + } + + f = s.Field("B") + if f.Kind() != reflect.Int { + t.Errorf("Field B has wrong kind: %s want: %s", f.Kind(), reflect.Int) + } + + // unexported + f = s.Field("d") + if f.Kind() != reflect.String { + t.Errorf("Field d has wrong kind: %s want: %s", f.Kind(), reflect.String) + } +} + func TestField_Tag(t *testing.T) { s := newStruct()