Add StructHasStringValue, StructHasProperty

This commit is contained in:
George Suntres
2026-04-01 21:01:00 -04:00
parent e732870865
commit 7e8cf14bb0
2 changed files with 48 additions and 0 deletions

View File

@@ -10,6 +10,38 @@ import (
"go.mongodb.org/mongo-driver/v2/bson" "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. // StructMustTomap given any struct return the equivalent map[string]any or nil.
// Will never throw. // Will never throw.
func StructMustToMap(data any) map[string]any { func StructMustToMap(data any) map[string]any {

View File

@@ -4,6 +4,22 @@ import (
"testing" "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) { func TestStructSetValue(t *testing.T) {
type O struct { type O struct {
Name string Name string