Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Created September 13, 2023 00:20
Show Gist options
  • Save maxjustus/121ee0c841542d17e1c11c8de8fc2d09 to your computer and use it in GitHub Desktop.
Save maxjustus/121ee0c841542d17e1c11c8de8fc2d09 to your computer and use it in GitHub Desktop.
golang parallelMap
func parallelMap[T any, V any](input []T, f func(T) (V, error)) ([]V, error) {
outChan := make(chan V, len(input))
errChan := make(chan error, len(input))
for i, val := range input {
go func(i int, val T) {
out, err := f(val)
if err != nil {
errChan <- err
} else {
outChan <- out
}
}(i, val)
}
output := make([]V, len(input))
for i := 0; i < len(input); i++ {
select {
case out := <-outChan:
output[i] = out
case err := <-errChan:
return []V{}, err
}
}
return output, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment