I thought of a way to do something similar to the “implements” proposal without
introducing operator overloading: turn it around. Instead of letting methods
implement operators, we could let operators implement methods.
type Lesser(type T) interface {
Less(b T) bool for(<)
}
This interface would be implemented by any type that has an appropriate Less
method, and by any type that works with the < operator. For example int would
implement Lesser(int).
It would be nice if we could get rid of the type parameter. One way would be to
adopt the Self type from Rust:
type Lesser interface {
Less(b Self) bool for (<)
}
For types implementing the interface, Self would be replaced by the
implementing type:
type vehicle struct {
weight float64
horsepower float64
}
func (v vehicle) Less(b vehicle) bool {
return v.weight < b.weight
}
For code using the interface, Self would be replaced by the interface type; it
would be as though Lesser had been declared as
type Lesser interface {
Less(b Lesser) bool
}
But if a mis-matched type was passed to Less, it would need to panic. So this
option (using the Self type) would somewhat reduce compile-time type safety.
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.