This article is part of the Introduction to Go Generics series. Go here to see more.
Let’s look at the example. The
reduce() function takes as parameters:
- A slice of
- An initial value of
Mwhich 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