diff --git a/struct.go b/struct.go index 3d41206..2e46ffc 100644 --- a/struct.go +++ b/struct.go @@ -10,6 +10,38 @@ import ( "go.mongodb.org/mongo-driver/v2/bson" ) +// StructHasStringValue given any struct will check if the requested property has +// a non-blank value. +func StructHasStringValue(o any, field string) bool { + v := reflect.ValueOf(o).Elem().FieldByName(field) + + return v.String() != "" +} + +// StructHasNotStringValue given any struct will check if the requested property has +// a blank value. +func StructHasNotStringValue(o any, field string) bool { + return !StructHasStringValue(o, field) +} + +// StructHasProperty cheks if a struct has the requested property. +func StructHasProperty(value interface{}, name string) bool { + vo := reflect.ValueOf(value).Elem() + + typeOfValue := vo.Type() + + has := false + + for i:= 0; i < vo.NumField(); i++ { + if typeOfValue.Field(i).Name == name { + has = true + break + } + } + + return has +} + // StructMustTomap given any struct return the equivalent map[string]any or nil. // Will never throw. func StructMustToMap(data any) map[string]any { diff --git a/struct_test.go b/struct_test.go index e05530d..152fbc0 100644 --- a/struct_test.go +++ b/struct_test.go @@ -4,6 +4,22 @@ import ( "testing" ) +func TestStructHasProperty(t *testing.T) { + type O struct { + Name string + Age int + } + + o := &O{ + Name: "Nick", + Age: 15, + } + + if !StructHasProperty(o, "Name") { + t.Fatal("Should have property name") + } +} + func TestStructSetValue(t *testing.T) { type O struct { Name string