Add StructHasStringValue, StructHasProperty
This commit is contained in:
32
struct.go
32
struct.go
@@ -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 {
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user