From 51c56e868eebc7666cd657ede08b25b0ea1f4f6a Mon Sep 17 00:00:00 2001 From: futugyousuzu <17871902+futugyou@users.noreply.github.com> Date: Thu, 25 Jul 2024 10:56:47 +0000 Subject: [PATCH] add extensions mothed for get string value form object --- extensions/reflect.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 extensions/reflect.go diff --git a/extensions/reflect.go b/extensions/reflect.go new file mode 100644 index 00000000..a33f539c --- /dev/null +++ b/extensions/reflect.go @@ -0,0 +1,39 @@ +package extensions + +import ( + "fmt" + "reflect" +) + +func GetStringFieldPointer(obj interface{}, fields ...string) *string { + v := reflect.ValueOf(obj) + for _, field := range fields { + if v.Kind() == reflect.Ptr && !v.IsNil() { + v = v.Elem() + } else { + return nil + } + v = v.FieldByName(field) + if !v.IsValid() { + return nil + } + } + if v.Kind() == reflect.Ptr && !v.IsNil() { + val := v.Interface().(*string) + return val + } + if v.Kind() == reflect.String { + val := v.String() + return &val + } + fmt.Println(v.Kind() == reflect.String) + return nil +} + +func GetStringFieldStruct(obj interface{}, fields ...string) string { + v := GetStringFieldPointer(obj, fields...) + if v == nil { + return "" + } + return *v +}