Old:
sum := 0
for _, x := range xs {
sum += xs
}
New: slices.Reduce(xs, 0, func(i, j int) int {
return i + j
})Old:
sum := 0
for _, x := range xs {
sum += xs
}
New: slices.Reduce(xs, 0, func(i, j int) int {
return i + j
})Reversing a slice of T. Copy and pasting this:
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
New: reverse(a)
Or generic versions of these: https://gobyexample.com/collection-functionsI think the other replies to your comment point out the improvements that non-reduce-based versions of the code would bring, but I wanted to specifically call out reduce as being a pretty awkward function in other languages as well. So I think it's not a strong argument against generics (and the OP didn't mention wanting it in the first place); by and large functional methods like map, filter, reverse, etc are more readable; reduce is the exception that often isn't.
I wrote a fair bit of production Go code in my past, and missed many functional programming patterns. Didn't really miss reduce though. I'm glad that it seems like the ones I missed will become possible with this generics proposal.
And reduce isn't horribly unreadable, it's just a slight degradation compared to a for loop IMO. And the other functions are a large improvement.
slices.Sum()