5 ms·
Finally. Better late than never. I have to write a lot of Go code at $BIGCORP and keep reaching for generic helper functions like Keys or Map or Filter or Conta
by adamch 6y ago
Finally. Better late than never. I have to write a lot of Go code at $BIGCORP and keep reaching for generic helper functions like Keys or Map or Filter or Contains. This is going to make my code much more readable.
- nemo1618 6y agoWill it really? Old: sum := 0 for _, x := range xs { sum += xs } New: slices.Reduce(xs, 0, func(i, j int) int { return i + j })
- dilap 6y agoYeah no real gain for that case, but for something like filter, definitely a win.
- hombre_fatal 6y agoThat's the most compelling example you could come up with as someone who presumably writes Go? 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-functions https://gobyexample.com/collection-functions
- adamch 6y agoYep, this is exactly the use case I was talking about.
- TheCoelacanth 6y agoNew: slices.Sum()
- reissbaker 6y agoThis is an argument I've seen played out in other language communities. In the JS/TypeScript world, the current evolving consensus is "most of the functional programming methods improve readability, except reduce, which is usually worse than a for loop." I 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.