On Fri, Aug 2, 2019 at 1:12 PM Bruno Albuquerque <b...@gmail.com> wrote:
>
> I was thinking about a way to  "extend" usual operations (say, equality 
> checks) to types that can not be compared the usual way (they are not 
> "comparable" in the contract sense) and came up with something like this:
>
> // Just to use for type assertion later.
> type Equaler interface {
>   Equal(Equaler) bool
> }
>
> contract Comparable(T) {
>   T comparable(T), Equal(T) bool
> }
>
> func Compare(type T Comparable)(a, b T) bool {
>   if eq, ok := a.(Equaler); ok {
>     return eq.Equal(b)
>   }
>
>   return a == b  // Does this work at all?
> }
>
> Would this work? More specifically it looks to me that that if the specific 
> type is not comparable (But has the Equal method), the compiler might see the 
> "==" comparison in the function and give an error.
>
> One way around this would possibly be to use something similar to type 
> assertion (in this case, a and b would have to be asserted to "comparable" 
> which I guess is not possible as it is a contract). Or, the compiler could be 
> smart enough to know that if we reached that check, then the type must be 
> comparable (so it would also not give an error).

In the current design draft, that would not work.  The == operator is
not supported by all possible types, so it is not permitted.

We definitely don't want to rely on the compiler being smart enough.
Any such approach would require writing down the exact inference rules
that the compiler is permitted to use.  Otherwise different compilers
would behave differently.

One possibility we've toyed with is

    switch T.(type) { // Note: switch on type parameter itself, not a
value of that type.
    case Equaler:
        ...
    case comparable:
        // Permit using == operator here on values of type T in this case only.
    }

We'll see whether some such facility seems useful.  This is something
we can add later, if the current design draft seems workable.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcW%2BR%3D6FPQFLTexuP_FBTT6ibGo0aoDo_Xcjgf7i0zC9UQ%40mail.gmail.com.

Reply via email to