Created
July 26, 2021 19:00
-
-
Save rtorrero/ae6852ab4fcc2db75ce3965d1db4d12f to your computer and use it in GitHub Desktop.
Reflection to avoid duplicating very similar methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (sm SAPSystemsMap) GetSIDsString() string { | |
return getSIDsString(reflect.ValueOf(sm)) | |
} | |
func (sl SAPSystemsList) GetSIDsString() string { | |
return getSIDsString(reflect.ValueOf(sl)) | |
} | |
func getSIDsString(v reflect.Value) string { | |
var s []string | |
for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface { | |
v = v.Elem() | |
} | |
switch v.Kind() { | |
case reflect.Array, reflect.Slice: | |
for i := 0; i < v.Len(); i++ { | |
s = append(s, getSIDsString(v.Index(i))) | |
} | |
case reflect.Map: | |
for _, k := range v.MapKeys() { | |
s = append(s, getSIDsString(v.MapIndex(k))) | |
} | |
default: | |
return v.Interface().(SAPSystem).SID | |
} | |
return strings.Join(s, ",") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment