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.
|
|
Output:
55
5.5
Let’s look at the example. The reduce()
function takes as parameters:
- A slice of
any
typeT
- An initial value of
any
typeM
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
.