Warning: yet another generics-related idea ahead. :-)
The motivation for using contracts instead of interfaces as the type
constraints in the Go 2 generics proposal is the fact that interfaces only
allow one type of operation: method calls. And we’d like to be able to use
other operations, such as addition and comparison, in our generic functions. So
maybe we could extend interfaces to support other operations as well.
This would be an interesting and useful feature even without generics, though
probably not worth the cost in complexity by itself. For example, here is a Min
function written with operator interfaces, but not generics:
type Ordered interface {
<
}
func Min(a, b Ordered) Ordered {
if a < b {
return a
}
return b
}
The presence of an operator in an interface definition would mean that to
implement the interface, the type must be usable with that operator. The vtable
for the interface would include an entry for the function that implements that
operator for the concrete type stored in the interface. When the interface is
used with that operator, there would first be a check to ensure that the values
on both sides are the same concrete type; if this fails, there would be a
panic. Then the function is called much like an ordinary interface method call.
(== and != would be exceptions, since they already have a defined meaning for
interfaces. interface { == } would be implemented only by types that can be
compared for equality, but it should not change the meaning of the == operator.)
The syntax for declaring operator interfaces is a bit of a question; the most
obvious syntax, as I used in my example, would not interact very well with
automatic semicolon insertion.
The principle could be extended to other operations beyond the arithmetic and
comparison operators, perhaps something like this:
interface stringish {
len
[int]byte
}
Andy
--
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 [email protected].
For more options, visit https://groups.google.com/d/optout.