Map, filter, and reduce

suggest change

Map, filter and reduce are the three basic operations on collections:

Go has no built-in map, filter or reduce functions, and the standard library doesn't provide them either. The idiomatic way is a for loop. With generics (Go 1.18) and iterators (Go 1.23) you can write them yourself in a few lines, and the slices, maps and strings packages provide many specialized versions.

Plain loops

Every map, filter and reduce is a simple loop:

package main

import (
	"fmt"
	"strings"
)

func main() {
	words := []string{"go", "", "map", "filter", "", "reduce"}

	// map: transform each element
	upper := make([]string, 0, len(words))
	for _, w := range words {
		upper = append(upper, strings.ToUpper(w))
	}

	// filter: keep elements that match a condition
	var nonEmpty []string
	for _, w := range upper {
		if w != "" {
			nonEmpty = append(nonEmpty, w)
		}
	}

	// reduce: combine all elements into one value
	total := 0
	for _, w := range nonEmpty {
		total += len(w)
	}

	fmt.Printf("%q\n", upper)
	fmt.Printf("%q\n", nonEmpty)
	fmt.Println("total letters:", total)
}
["GO" "" "MAP" "FILTER" "" "REDUCE"]
["GO" "MAP" "FILTER" "REDUCE"]
total letters: 17

For map, the result has the same length as the input, so allocate it up front with make (see Optimize by pre-allocating slice). For filter, the result size isn't known in advance. Starting with a nil slice and calling append is fine. Filter a slice shows how to filter in place without allocating.

Loops are often the best choice in Go: they are explicit, fast, and you can do all three steps in one pass. But when the same pattern repeats, generic helpers make the code shorter.

Generic Map, Filter and Reduce

Generic functions work with slices of any type:

package main

import (
	"fmt"
	"strconv"
)

// Map returns a new slice with f applied to every element of s.
func Map[T, R any](s []T, f func(T) R) []R {
	res := make([]R, len(s))
	for i, v := range s {
		res[i] = f(v)
	}
	return res
}

// Filter returns a new slice with elements of s for which keep returns true.
func Filter[T any](s []T, keep func(T) bool) []T {
	var res []T
	for _, v := range s {
		if keep(v) {
			res = append(res, v)
		}
	}
	return res
}

// Reduce combines elements of s into a single value, starting with init.
func Reduce[T, A any](s []T, init A, f func(A, T) A) A {
	acc := init
	for _, v := range s {
		acc = f(acc, v)
	}
	return acc
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

	squares := Map(nums, func(n int) int { return n * n })
	fmt.Println("squares:", squares)

	labels := Map(nums[:3], strconv.Itoa)
	fmt.Printf("labels: %q\n", labels)

	evens := Filter(nums, func(n int) bool { return n%2 == 0 })
	fmt.Println("evens:", evens)

	sum := Reduce(nums, 0, func(acc, n int) int { return acc + n })
	fmt.Println("sum:", sum)

	// the accumulator can have a different type than the elements
	csv := Reduce(nums[:4], "", func(acc string, n int) string {
		if acc != "" {
			acc += ","
		}
		return acc + strconv.Itoa(n)
	})
	fmt.Printf("csv: %q\n", csv)

	// combine: sum of squares of odd numbers
	odd := func(n int) bool { return n%2 == 1 }
	square := func(n int) int { return n * n }
	add := func(a, b int) int { return a + b }
	fmt.Println("sum of odd squares:", Reduce(Map(Filter(nums, odd), square), 0, add))

	empty := Filter(nums, func(n int) bool { return n > 100 })
	fmt.Println(empty == nil, len(empty))
}
squares: [1 4 9 16 25 36 49 64 81 100]
labels: ["1" "2" "3"]
evens: [2 4 6 8 10]
sum: 55
csv: "1,2,3,4"
sum of odd squares: 165
true 0

Things to notice:

Working with structs

The helpers are most useful with slices of structs, where you pick out fields, select records and compute totals:

package main

import (
	"fmt"
	"maps"
	"slices"
)

type Order struct {
	ID       int
	Customer string
	Amount   float64
	Paid     bool
}

func Map[T, R any](s []T, f func(T) R) []R {
	res := make([]R, len(s))
	for i, v := range s {
		res[i] = f(v)
	}
	return res
}

func Filter[T any](s []T, keep func(T) bool) []T {
	var res []T
	for _, v := range s {
		if keep(v) {
			res = append(res, v)
		}
	}
	return res
}

func Reduce[T, A any](s []T, init A, f func(A, T) A) A {
	acc := init
	for _, v := range s {
		acc = f(acc, v)
	}
	return acc
}

// GroupBy puts elements into buckets keyed by key(v).
func GroupBy[T any, K comparable](s []T, key func(T) K) map[K][]T {
	res := make(map[K][]T)
	for _, v := range s {
		k := key(v)
		res[k] = append(res[k], v)
	}
	return res
}

func main() {
	orders := []Order{
		{1, "alice", 25.50, true},
		{2, "bob", 99.99, false},
		{3, "alice", 10.00, true},
		{4, "carol", 42.00, true},
		{5, "bob", 5.25, true},
	}

	paid := Filter(orders, func(o Order) bool { return o.Paid })
	ids := Map(paid, func(o Order) int { return o.ID })
	fmt.Println("paid order ids:", ids)

	revenue := Reduce(paid, 0.0, func(acc float64, o Order) float64 {
		return acc + o.Amount
	})
	fmt.Printf("revenue: %.2f\n", revenue)

	// reduce into a map: total per customer
	perCustomer := Reduce(paid, map[string]float64{},
		func(acc map[string]float64, o Order) map[string]float64 {
			acc[o.Customer] += o.Amount
			return acc
		})
	for _, name := range slices.Sorted(maps.Keys(perCustomer)) {
		fmt.Printf("  %-6s %6.2f\n", name, perCustomer[name])
	}

	byCustomer := GroupBy(orders, func(o Order) string { return o.Customer })
	fmt.Println("bob's orders:", Map(byCustomer["bob"], func(o Order) int { return o.ID }))

	// biggest order: reduce with the first element as the initial value
	biggest := Reduce(orders[1:], orders[0], func(best, o Order) Order {
		if o.Amount > best.Amount {
			return o
		}
		return best
	})
	fmt.Printf("biggest: %+v\n", biggest)
}
paid order ids: [1 3 4 5]
revenue: 82.75
  alice   35.50
  bob      5.25
  carol   42.00
bob's orders: [2 5]
biggest: {ID:2 Customer:bob Amount:99.99 Paid:false}

Reduce can build any value, including a map. Because a map is a reference type, the function modifies the map in place and returns the same map. This works, but a plain loop says the same thing more clearly. GroupBy is a dedicated helper for this common case.

Finding the biggest element uses the first element as the initial value and reduces the rest. This requires a non-empty slice: orders[0] panics on an empty one. For this particular case the standard library has slices.MaxFunc, shown next.

Helpers in the standard library

The standard library has no general Map, Filter or Reduce, but it has many specialized functions that cover common cases:

package main

import (
	"cmp"
	"fmt"
	"maps"
	"slices"
	"strings"
	"unicode"
)

type Product struct {
	Name  string
	Price int
}

func main() {
	nums := []int{3, 8, 1, 6, 9, 2}

	// filter in place: DeleteFunc removes elements for which f returns true
	odds := slices.DeleteFunc(slices.Clone(nums), func(n int) bool { return n%2 == 0 })
	fmt.Println("odds:", odds, "original:", nums)

	// "any" and "find" are filters that stop at the first match
	fmt.Println("has > 7:", slices.ContainsFunc(nums, func(n int) bool { return n > 7 }))
	i := slices.IndexFunc(nums, func(n int) bool { return n > 7 })
	fmt.Println("first > 7 at index", i, "value", nums[i])

	// common reductions are built in
	fmt.Println("min:", slices.Min(nums), "max:", slices.Max(nums))

	products := []Product{{"pen", 3}, {"book", 25}, {"lamp", 40}, {"mug", 8}}
	priciest := slices.MaxFunc(products, func(a, b Product) int {
		return cmp.Compare(a.Price, b.Price)
	})
	fmt.Println("priciest:", priciest.Name)

	// map over the runes of a string; returning -1 drops the rune
	s := strings.Map(func(r rune) rune {
		if unicode.IsDigit(r) {
			return -1
		}
		return unicode.ToUpper(r)
	}, "a1b2c3 go")
	fmt.Printf("strings.Map: %q\n", s)

	// map keys and values are iterators; collect them into slices
	stock := map[string]int{"pen": 120, "book": 0, "lamp": 7}
	fmt.Println("keys:", slices.Sorted(maps.Keys(stock)))
	fmt.Println("values:", slices.Sorted(maps.Values(stock)))

	// filter a map in place
	maps.DeleteFunc(stock, func(name string, qty int) bool { return qty == 0 })
	fmt.Println("in stock:", stock)
}
odds: [3 1 9] original: [3 8 1 6 9 2]
has > 7: true
first > 7 at index 1 value 8
min: 1 max: 9
priciest: lamp
strings.Map: "ABC GO"
keys: [book lamp pen]
values: [0 7 120]
in stock: map[lamp:7 pen:120]
Task Function
filter a slice in place slices.DeleteFunc (note: removes elements where f is true)
filter a map in place maps.DeleteFunc
is there an element matching? slices.ContainsFunc
index of first matching element slices.IndexFunc
smallest / largest element slices.Min, slices.Max, slices.MinFunc, slices.MaxFunc
map over the runes of a string strings.Map, bytes.Map
remove consecutive duplicates slices.Compact, slices.CompactFunc
keys or values of a map maps.Keys, maps.Values (iterators)
iterator to slice / map slices.Collect, slices.Sorted, maps.Collect

slices.Min, slices.Max, slices.MinFunc and slices.MaxFunc panic on an empty slice. slices.DeleteFunc reuses the input's backing array, which is why the example filters a slices.Clone. Without the clone the original slice is overwritten:

package main

import (
	"fmt"
	"slices"
)

func main() {
	nums := []int{1, 2, 3, 4, 5, 6}
	odds := slices.DeleteFunc(nums, func(n int) bool { return n%2 == 0 })
	fmt.Println("odds:", odds)
	fmt.Println("nums:", nums)
}
odds: [1 3 5]
nums: [1 3 5 0 0 0]

DeleteFunc moves the kept elements to the front and zeroes the tail, so after the call the original nums holds garbage. Only use it when you don't need the original anymore, and always use the returned slice.

Lazy Map and Filter with iterators

The slice versions above build a new slice at every step. Map(Filter(nums, odd), square) allocates one slice for the filter result and another for the map result, and processes all elements even if you only need the first few.

Since Go 1.23, functions of type iter.Seq[T] can be used with for ... range. Map and filter written over iter.Seq are lazy: they compute nothing until someone ranges over the result, and they process one element at a time:

package main

import (
	"fmt"
	"iter"
	"slices"
)

// Map returns a sequence of f(v) for every v in seq.
func Map[T, R any](seq iter.Seq[T], f func(T) R) iter.Seq[R] {
	return func(yield func(R) bool) {
		for v := range seq {
			if !yield(f(v)) {
				return
			}
		}
	}
}

// Filter returns a sequence of elements of seq for which keep returns true.
func Filter[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
	return func(yield func(T) bool) {
		for v := range seq {
			if keep(v) && !yield(v) {
				return
			}
		}
	}
}

// Reduce consumes seq and combines its elements into a single value.
func Reduce[T, A any](seq iter.Seq[T], init A, f func(A, T) A) A {
	acc := init
	for v := range seq {
		acc = f(acc, v)
	}
	return acc
}

// Take returns a sequence of at most the first n elements of seq.
func Take[T any](seq iter.Seq[T], n int) iter.Seq[T] {
	return func(yield func(T) bool) {
		if n <= 0 {
			return
		}
		i := 0
		for v := range seq {
			if !yield(v) {
				return
			}
			i++
			if i == n {
				return
			}
		}
	}
}

// Naturals is an infinite sequence 1, 2, 3, ...
func Naturals() iter.Seq[int] {
	return func(yield func(int) bool) {
		for i := 1; ; i++ {
			if !yield(i) {
				return
			}
		}
	}
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 6}

	squares := Map(slices.Values(nums), func(n int) int {
		fmt.Println("  squaring", n)
		return n * n
	})
	fmt.Println("nothing computed yet")

	big := Filter(squares, func(n int) bool { return n > 10 })
	for v := range big {
		fmt.Println("got", v)
		if v > 20 {
			break
		}
	}

	sum := Reduce(Filter(slices.Values(nums), func(n int) bool { return n%2 == 0 }),
		0, func(a, b int) int { return a + b })
	fmt.Println("sum of evens:", sum)

	// works on infinite sequences because only what's needed is computed
	isPrime := func(n int) bool {
		if n < 2 {
			return false
		}
		for d := 2; d*d <= n; d++ {
			if n%d == 0 {
				return false
			}
		}
		return true
	}
	primes := slices.Collect(Take(Filter(Naturals(), isPrime), 10))
	fmt.Println("first 10 primes:", primes)
}
nothing computed yet
  squaring 1
  squaring 2
  squaring 3
  squaring 4
got 16
  squaring 5
got 25
sum of evens: 12
first 10 primes: [2 3 5 7 11 13 17 19 23 29]

How it works:

Note that a lazy sequence re-runs the whole chain every time you range over it. If an expensive pipeline is used more than once, collect it into a slice with slices.Collect.

Key-value pairs: iter.Seq2

iter.Seq2[K, V] yields pairs. maps.All yields key/value pairs of a map and slices.All yields index/value pairs of a slice. The same pattern works for pairs:

package main

import (
	"fmt"
	"iter"
	"maps"
	"slices"
)

// Filter2 returns a sequence of pairs from seq for which keep returns true.
func Filter2[K, V any](seq iter.Seq2[K, V], keep func(K, V) bool) iter.Seq2[K, V] {
	return func(yield func(K, V) bool) {
		for k, v := range seq {
			if keep(k, v) && !yield(k, v) {
				return
			}
		}
	}
}

// MapValues returns a sequence of pairs with f applied to every value.
func MapValues[K, V, R any](seq iter.Seq2[K, V], f func(V) R) iter.Seq2[K, R] {
	return func(yield func(K, R) bool) {
		for k, v := range seq {
			if !yield(k, f(v)) {
				return
			}
		}
	}
}

func main() {
	prices := map[string]float64{"pen": 1.5, "book": 12, "lamp": 30, "mug": 6}

	// keep items over 5, apply a 10% discount, collect into a new map
	expensive := Filter2(maps.All(prices), func(_ string, p float64) bool { return p > 5 })
	discounted := maps.Collect(MapValues(expensive, func(p float64) float64 { return p * 0.9 }))
	for _, k := range slices.Sorted(maps.Keys(discounted)) {
		fmt.Printf("%s=%.2f ", k, discounted[k])
	}
	fmt.Println()
	fmt.Println("original unchanged:", len(prices))

	// slices.All gives index/value pairs: keep elements at even indexes
	words := []string{"a", "b", "c", "d", "e"}
	for i, w := range Filter2(slices.All(words), func(i int, _ string) bool { return i%2 == 0 }) {
		fmt.Print(i, ":", w, " ")
	}
	fmt.Println()
}
book=10.80 lamp=27.00 mug=5.40
original unchanged: 4
0:a 2:c 4:e

maps.Collect turns an iter.Seq2 back into a map. Unlike maps.DeleteFunc, this builds a new map and leaves the original alone. Map iteration order is random, so sort the keys before printing (see Sorting).

Map with errors

Real transformations often fail: parsing, validation, lookups. A function that returns (R, error) doesn't fit Map, so write a variant that stops at the first error:

package main

import (
	"fmt"
	"strconv"
)

// MapErr applies f to every element and stops at the first error.
func MapErr[T, R any](s []T, f func(T) (R, error)) ([]R, error) {
	res := make([]R, 0, len(s))
	for i, v := range s {
		r, err := f(v)
		if err != nil {
			return nil, fmt.Errorf("element %d: %w", i, err)
		}
		res = append(res, r)
	}
	return res, nil
}

func main() {
	nums, err := MapErr([]string{"10", "20", "30"}, strconv.Atoi)
	fmt.Println(nums, err)

	nums, err = MapErr([]string{"10", "x", "30"}, strconv.Atoi)
	fmt.Println(nums, err)
}
[10 20 30] <nil>
[] element 1: strconv.Atoi: parsing "x": invalid syntax

The error includes the index of the failing element and wraps the original error with %w, so callers can still inspect it with errors.Is and errors.As (see Error handling). If you want all errors instead of the first one, collect them and return errors.Join(errs...).

Performance

Helpers aren't free. Here is the same computation (sum of squares of even numbers among 10,000 integers) as a loop, as a chain of slice helpers and as a chain of iterator helpers:

package main

import (
	"fmt"
	"iter"
	"slices"
	"testing"
)

func Map[T, R any](s []T, f func(T) R) []R {
	res := make([]R, len(s))
	for i, v := range s {
		res[i] = f(v)
	}
	return res
}

func Filter[T any](s []T, keep func(T) bool) []T {
	var res []T
	for _, v := range s {
		if keep(v) {
			res = append(res, v)
		}
	}
	return res
}

func Reduce[T, A any](s []T, init A, f func(A, T) A) A {
	acc := init
	for _, v := range s {
		acc = f(acc, v)
	}
	return acc
}

func MapSeq[T, R any](seq iter.Seq[T], f func(T) R) iter.Seq[R] {
	return func(yield func(R) bool) {
		for v := range seq {
			if !yield(f(v)) {
				return
			}
		}
	}
}

func FilterSeq[T any](seq iter.Seq[T], keep func(T) bool) iter.Seq[T] {
	return func(yield func(T) bool) {
		for v := range seq {
			if keep(v) && !yield(v) {
				return
			}
		}
	}
}

func ReduceSeq[T, A any](seq iter.Seq[T], init A, f func(A, T) A) A {
	acc := init
	for v := range seq {
		acc = f(acc, v)
	}
	return acc
}

var (
	isEven = func(n int) bool { return n%2 == 0 }
	square = func(n int) int { return n * n }
	add    = func(a, b int) int { return a + b }
)

func loop(nums []int) int {
	sum := 0
	for _, n := range nums {
		if n%2 == 0 {
			sum += n * n
		}
	}
	return sum
}

func withSlices(nums []int) int {
	return Reduce(Map(Filter(nums, isEven), square), 0, add)
}

func withSeq(nums []int) int {
	return ReduceSeq(MapSeq(FilterSeq(slices.Values(nums), isEven), square), 0, add)
}

func main() {
	nums := make([]int, 10_000)
	for i := range nums {
		nums[i] = i
	}
	fmt.Println(loop(nums) == withSlices(nums), loop(nums) == withSeq(nums))

	for _, b := range []struct {
		name string
		f    func([]int) int
	}{{"loop", loop}, {"slices", withSlices}, {"iter.Seq", withSeq}} {
		r := testing.Benchmark(func(tb *testing.B) {
			for tb.Loop() {
				b.f(nums)
			}
		})
		fmt.Printf("%-9s %8d ns/op %7d B/op %3d allocs/op\n",
			b.name, r.NsPerOp(), r.AllocedBytesPerOp(), r.AllocsPerOp())
	}
}
true true
loop          7406 ns/op       0 B/op   0 allocs/op
slices       66623 ns/op  169154 B/op  14 allocs/op
iter.Seq     22529 ns/op       0 B/op   0 allocs/op

(Numbers from one run on an x86-64 machine with Go 1.27; yours will differ, but the ratios are typical.)

For most code the difference doesn't matter: 60 microseconds for 10,000 elements is fast. In hot loops, write the loop.

When to use what

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents