Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The problem is that with current proposal Go severely lacks type inference, required for generics to look nice and clean.

A lot of the information is already in the definitions, there's no reason to repeat it, but Go chose to do that.

    // Reduce reduces a []T1 to a single value using a reduction function.
    func Reduce(type T1, T2)(s []T1, initializer T2, f func(T2, T1) T2) T2 {

    s := []int{1, 2, 3}
    sum := slices.Reduce(s, 0, func(i, j int) int { return i + j })
and the example from referenced article is even more outrageous

    t1 := hashtable.New(string, int)(8, func(key string, m int) int {
We have function types literally at the same exression, but Go requires to repeat it.


> We have function types literally at the same exression, but Go requires to repeat it.

It does not require it, the author chose to do it.

    t1 := hashtable.New(8, func(key string, m int) int {
is perfectly valid.

https://go2goplay.golang.org/p/SbEXpyVl-V3


In this particular case, the compiler can't infer the type of V if you omit the type parameters at the call sites:

  type checking failed for main
  prog.go2:17:3: cannot infer V (prog.go2:46:27)
  prog.go2:22:3: cannot infer V (prog.go2:46:27)
But generally you are right, yes. It is able to infer K at least.


Thanks for noting, but my bigger concern was with different thing, that I’m also quoting from the doc (https://go2goplay.golang.org/p/LFo23rCKHXZ):

    func Filter(type T)(s []T, f func(T) bool) []T { ... }
 
    s:= []int{1,2m3}
    evens := slices.Filter(s, func(i int) bool { return i%2 == 0 })
The type of predicate is already in generic definition, we don’t need this verbosity. Other languages (I’d even say most of languages, used in dev work today) let us write simply something like slices.Filter(s, i->i%2).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: