diff --git a/field.go b/field.go index cd751ca..952eeb8 100644 --- a/field.go +++ b/field.go @@ -15,7 +15,8 @@ func (f *Field) Tag(key string) string { return f.field.Tag.Get(key) } -// Value returns the underlying value of of the field. +// Value returns the underlying value of of the field. It panics if the field +// is not exported. func (f *Field) Value() interface{} { return f.value.Interface() } @@ -24,3 +25,8 @@ func (f *Field) Value() interface{} { func (f *Field) IsEmbedded() bool { return f.field.Anonymous } + +// IsExported returns true if the given field is exported. +func (f *Field) IsExported() bool { + return f.field.PkgPath == "" +} diff --git a/field_test.go b/field_test.go new file mode 100644 index 0000000..8c24760 --- /dev/null +++ b/field_test.go @@ -0,0 +1,49 @@ +package structure + +import "testing" + +// A test struct that defines all cases +type Foo struct { + A string + B int `structure:"y"` + C bool `json:"c"` + d string // not exported + *Bar // embedded +} + +type Bar struct { + E string + F int + g []string +} + +func newStruct() *Struct { + b := &Bar{ + E: "example", + F: 2, + g: []string{"zeynep", "fatih"}, + } + + f := &Foo{ + A: "gopher", + B: 1, + C: true, + d: "small", + } + f.Bar = b + + return New(f) +} + +func TestField(t *testing.T) { + s := newStruct() + + defer func() { + err := recover() + if err == nil { + t.Error("Retrieveing a non existing field from the struct should panic") + } + }() + + _ = s.Field("no-field") +}