Add StructSetValue func
This commit is contained in:
22
struct.go
22
struct.go
@@ -9,6 +9,28 @@ import (
|
|||||||
"go.mongodb.org/mongo-driver/v2/bson"
|
"go.mongodb.org/mongo-driver/v2/bson"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// StructSetValue will update the value of the given field of struct o.
|
||||||
|
func StructSetValue(o any, field string, value any) {
|
||||||
|
ref := reflect.ValueOf(o).Elem()
|
||||||
|
|
||||||
|
if ref.Kind() == reflect.Ptr {
|
||||||
|
ref = reflect.Indirect(ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ref.Kind() == reflect.Interface {
|
||||||
|
ref = ref.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if ref.Kind() == reflect.Struct {
|
||||||
|
f := ref.FieldByName(field)
|
||||||
|
|
||||||
|
if f.IsValid() && f.CanSet() {
|
||||||
|
f.Set(reflect.ValueOf(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
func StructToStruct(source any, target any) {
|
func StructToStruct(source any, target any) {
|
||||||
mapstructure.Decode(source, &target)
|
mapstructure.Decode(source, &target)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,26 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func TestStructSetValue(t *testing.T) {
|
||||||
|
type O struct {
|
||||||
|
Name string
|
||||||
|
Age int
|
||||||
|
Active bool
|
||||||
|
}
|
||||||
|
|
||||||
|
o := &O{
|
||||||
|
Name: "Nick",
|
||||||
|
Age: 15,
|
||||||
|
Active: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
StructSetValue(o, "Name", "George")
|
||||||
|
|
||||||
|
if o.Name != "George" {
|
||||||
|
t.Fatalf("Name should have been George not %s", o.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestStructToStruct(t *testing.T) {
|
func TestStructToStruct(t *testing.T) {
|
||||||
type O struct {
|
type O struct {
|
||||||
Name string
|
Name string
|
||||||
|
|||||||
Reference in New Issue
Block a user