I have a newtype and I want to implement Ord
:
use std::cmp::{Ord, Ordering};
struct MyType(isize);
impl Ord for MyType {
fn cmp(&self, &other: Self) -> Ordering {
let MyType(ref lhs) = *self;
let MyType(ref rhs) = *other;
lhs.cmp(rhs)
}
}
When I try to compare two variables of my types, I get errors:
error[E0277]: the trait bound `MyType: std::cmp::PartialOrd` is not satisfied
--> src/main.rs:5:6
|
5 | impl Ord for MyType {
| ^^^ can't compare `MyType` with `MyType`
|
= help: the trait `std::cmp::PartialOrd` is not implemented for `MyType`
error[E0277]: the trait bound `MyType: std::cmp::Eq` is not satisfied
--> src/main.rs:5:6
|
5 | impl Ord for MyType {
| ^^^ the trait `std::cmp::Eq` is not implemented for `MyType`
When I implement PartialEq
, Eq
and PartialOrd
(gt()
, lt()
, eq()
, ge()
, le()
, etc.), everything works fine, but if I provided cmp
, we can infer functions like lt()
and eq()
! This is redundant! I don't like this!
When looking in the docs, I see this in the definition of Ord
:
pub trait Ord: Eq + PartialOrd<Self>
This looks like the trait inherits from Eq
and PartialOrd
. Why can't the trait provide default implementations for the required methods from the inherited traits using the cmp
function? I don't know how inheritance of traits works and searching turned up nothing useful, but I think this is something that should be possible.
How is this done in Rust? I hope not this way...
See Question&Answers more detail:os