Skip to main content
  1. Tutorials/

🔉 Reduce function using Generics in Go

·2 mins

The reduce() function is a functional programming concept popularized by other programming languages such as JavaScript and Python. It works by reducing an array to a single value by applying a function generating a partial result to each element of the array. The result after the last item is the cumulative value from the entire list. So far in Go, it has not been easy to create this type of function that would work for different types. However, with the Go 1.18 release, which introduces Generics, this is no longer a problem.

This article is part of the Introduction to Go Generics series. Go here to see more.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
    "fmt"
)

func reduce[T, M any](s []T, f func(M, T) M, initValue M) M {
    acc := initValue
    for _, v := range s {
        acc = f(acc, v)
    }
    return acc
}

func main() {
    numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    sum := reduce(numbers, func(acc, current int) int {
        return acc + current
    }, 0)
    fmt.Println(sum)
	
    divided := reduce(numbers, func(acc float64, current int) float64 {
        return acc + float64(current)/10.0
	}, 0)
    fmt.Println(divided)
}

Output:

55
5.5

Let’s look at the example. The reduce() function takes as parameters:

  • A slice of any type T
  • An initial value of any type M which is a start value of our accumulator - the value that accumulates partial results of reducer function calls. Note that the accumulator type need not be the same as the slice type.
  • A reducer function that takes the accumulator and current value of the slice and returns the new accumulator.

As a result, we created a function that works similarly to the reduce() known from other languages. In the first example of the main(), it is used to sum a slice of numbers, and in the second, to sum the same slice, where each value is divided by 10 and the result is float64 rather than int.