Cookies management by TermsFeed Cookie Consent

🔉 Reduce function using Generics in Go

introduction generics generics-intro

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:

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.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🫘 Count the occurrences of an element in a slice in Go

Learn how to count elements in a slice that meet certain conditions
introduction generics generics-intro

🗑️ Remove duplicates from any slice using Generics in Go

Learn how to create a slice with unique values using Generics
introduction slice generics generics-intro

🦾 Create a slice 'map' function using Generics in Go

Learn how to apply a function to all slice elements using Generics
introduction generics generics-intro