ParallelMap function for arrays/slices in Go

How to write a concurrent functional Map function in golang using generics and goroutines. Leverage all your CPU cores!

ParallelMap applies a function to each element in the input slice in parallel and returns a new slice with the results. The function f takes an element of type A and returns an element of type B.

func ParallelMap[A, B any](input []A, f func(A) B) []B {
	result := make([]B, len(input))
	var wg sync.WaitGroup

	for i, v := range input {
		go func(i int, v A) {
			defer wg.Done()
			result[i] = f(v)
		}(i, v)

	return result

Linked Technologies

What it's made of

illustration of Go

Fast, simple, and efficient. Ideal for solopreneurs, Go's straightforward syntax and powerful performance allow for quick development and deployment.

Linked Categories

Where it's useful

illustration of Data Engineering
Data Engineering

Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.