From 064b8903efc3a60da6fffc99198362d97ce89db6 Mon Sep 17 00:00:00 2001 From: Mattia Cabrini Date: Sat, 8 Jul 2023 09:31:52 +0200 Subject: [PATCH] Reflect Field --- go.sum | 3 +++ reflect.go | 14 ++++++++++++++ methods_test.go => reflect_test.go | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 go.sum rename methods_test.go => reflect_test.go (91%) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..4bc0337 --- /dev/null +++ b/go.sum @@ -0,0 +1,3 @@ +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/reflect.go b/reflect.go index ed89d80..1589c0c 100644 --- a/reflect.go +++ b/reflect.go @@ -88,6 +88,20 @@ func GetMethod(obj interface{}, name string, suffix string) GenericFunc { return nil } +func GetProperty(obj interface{}, name string, suffix string) interface{} { + to := reflect.TypeOf(obj) + vo := reflect.ValueOf(obj) + + _, b := to.FieldByName(name + suffix) + + if b { + fieldVO := vo.FieldByName(name + suffix) + return fieldVO.Interface() + } + + return nil +} + var typeDefault = map[reflect.Kind]interface{}{ reflect.String: "", reflect.Int64: int64(0), diff --git a/methods_test.go b/reflect_test.go similarity index 91% rename from methods_test.go rename to reflect_test.go index 1b340b2..cc27ac2 100644 --- a/methods_test.go +++ b/reflect_test.go @@ -161,3 +161,23 @@ func TestMethodNameKo(t *testing.T) { t.Fail() } } + +func TestFieldOk(t *testing.T) { + obj := testType{0, 1} + + i := GetProperty(obj, "B", "") + + if i.(int) != 1 { + t.Fail() + } +} + +func TestFieldKo(t *testing.T) { + obj := testType{0, 1} + + i := GetProperty(obj, "c", "") + + if i != nil { + t.Fail() + } +} -- 2.43.0