[generics] What are the cases when type spec is absolutely needed during invocation?

57 views
Skip to first unread message

Andrey Tcherepanov

unread,
Jun 22, 2020, 8:32:30 PM6/22/20
to golang-nuts

TL;DR
Question to people who played with new generics pipeline extensively:

How often do we actually need to specify types during invocation? Can they always be deduced? If not, maybe just parameters need to be type casted appropriately?


Long story (just thoughts of how I got there)

So, after going through draft, and seeing this Attack Of The Braces - both in the draft and outside - I was thinking about maybe a slightly better way to declare functions

1. Using decorator like $ or @, so type keyword could be dropped. Something like func Min(a,b $T) $T {...} , or `func Some(a $T1, b $T2) ($T3, error)` will automatically use generic because of the decorator $. But then invocation and contracting becomes a bit funny. `result := Min$int(1,3)` and `result, err := Some$(int, string)(1, "no")`
Still, might be better for just readability (IMHO, YMMV)

2. Then I thought what if decorator on existing interface would make it treated as generic contract,
    type Comparable interface {
        type int, float...
    }
   
    func Min(a, b $Comparable) $Comparable {
      // ...
    }
, but then - Why do we even need generic on a function if we can just specify contract/interface as type of the parameters?... Like  func Min(a, b Comparable) Comparable { /* ... */ } does not need to do anything "special"    

3. Shift declaration before func or before name... (I think someone said something about not liking traincars in front of the steamer, but I actually like it)

    (type T Comparable) func Min(a, b T) T {...}
or
    func(type T Comparable) Min(a,b T) T {...}

and invocation becomes kind of calling something on a type

    result := int.Min(1, 2)
or
    result, err := (int, error).Some(2, "yes")

But then I thought... Why bother? How often it cannot be deduced at the invocation site what types this was called with? And even if the do, can these places be casted just like a normal cast to some type? So it becomes

    result, err := Some(int('A'), string(make([]byte,0)))
 
when needed.

Thanks,
   Andrey

PS.

3 - Another thought is to allow to use a block after type keyword, but I think it might conflict heavily with existing code

  type (
    type T Something
    type T2 OtherType
  ) {
   func SomeFunc(a,b T) T2 {
     // ...
   }
  }

Reply all
Reply to author
Forward
0 new messages