Created
November 22, 2019 07:43
-
-
Save Sherlock-Holo/7fa7c4073ce2980ab2778c5d5a05d57a to your computer and use it in GitHub Desktop.
functional helper
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
// Map is a functional map, like Kotlin or Rust map. | |
// wantType must be a pointer, If you want return a []*string, | |
// wantType should be **string | |
func Map(slice interface{}, wantType interface{}, f func(v interface{}) interface{}) interface{} { | |
if reflect.TypeOf(slice).Kind() != reflect.Slice { | |
panic("slice type must be slice") | |
} | |
value := reflect.ValueOf(slice) | |
newType := reflect.ValueOf(wantType) | |
if newType.Kind() != reflect.Ptr { | |
panic("wantType must be a pointer") | |
} | |
newType = reflect.Indirect(newType) | |
newSlice := reflect.MakeSlice(reflect.SliceOf(newType.Type()), value.Len(), value.Cap()) | |
for index := 0; index < value.Len(); index++ { | |
v := value.Index(index) | |
newSlice.Index(index).Set(reflect.ValueOf(f(v.Interface()))) | |
} | |
return newSlice.Interface() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment