Skip to content

Commit

Permalink
add extensions mothed for get string value form object
Browse files Browse the repository at this point in the history
  • Loading branch information
futugyou authored Jul 25, 2024
1 parent c3f85e3 commit 51c56e8
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions extensions/reflect.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 51c56e8

Please sign in to comment.