How to Write a Generic Map/Filter/Reduce in Go

Write generic Map, Filter, and Reduce functions in Go using type parameters and function arguments to process slices of any type.

You write generic Map, Filter, and Reduce functions using Go generics by defining a function with a type parameter T and a function parameter for the transformation logic.

func Map[T, U any](slice []T, fn func(T) U) []U {
	result := make([]U, len(slice))
	for i, v := range slice {
		result[i] = fn(v)
	}
	return result
}

func Filter[T any](slice []T, fn func(T) bool) []T {
	var result []T
	for _, v := range slice {
		if fn(v) {
			result = append(result, v)
		}
	}
	return result
}

func Reduce[T any](slice []T, fn func(T, T) T) T {
	if len(slice) == 0 {
		var zero T
		panic("Reduce of empty slice")
	}
	acc := slice[0]
	for i := 1; i < len(slice); i++ {
		acc = fn(acc, slice[i])
	}
	return acc
}

Use them like this:

nums := []int{1, 2, 3, 4, 5}
doubled := Map(nums, func(x int) int { return x * 2 })
evens := Filter(nums, func(x int) bool { return x%2 == 0 })
sum := Reduce(nums, func(a, b int) int { return a + b })