Skip to content

Instantly share code, notes, and snippets.

@Sherlock-Holo
Created November 22, 2019 07:43
Show Gist options
  • Save Sherlock-Holo/7fa7c4073ce2980ab2778c5d5a05d57a to your computer and use it in GitHub Desktop.
Save Sherlock-Holo/7fa7c4073ce2980ab2778c5d5a05d57a to your computer and use it in GitHub Desktop.
functional helper
// 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