Skip to content

Instantly share code, notes, and snippets.

@alexcrichton
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexcrichton/10945968 to your computer and use it in GitHub Desktop.
Save alexcrichton/10945968 to your computer and use it in GitHub Desktop.
pub trait Eq {
fn eq(&self, other: &Self) -> bool;
}
// equality operators are wired to this trait
#[lang = "partial_eq"]
pub trait PartialEq {
fn eq(&self, other: &Self) -> bool;
fn ne(&self, other: &Self) -> bool { !self.eq(other) }
}
pub trait Ord {
fn cmp(&self, other: &Self) -> bool;
fn lt(&self, other: &Self) -> bool { self.cmp(other) == Less }
fn le(&self, other: &Self) -> bool { !other.lt(self) }
fn gt(&self, other: &Self) -> bool { other.lt(self) }
fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}
// all comparison operators are wired to this trait
#[lang = "partial_ord"]
pub trait PartialOrd {
fn lt(&self, other: &Self) -> bool;
fn le(&self, other: &Self) -> bool { !other.lt(self) }
fn gt(&self, other: &Self) -> bool { other.lt(self) }
fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}
impl<T: Eq> PartialEq for T {
fn eq(&self, other: &T) -> bool { Eq::eq(self, other) }
fn ne(&self, other: &T) -> bool { !Eq::eq(self, other) }
}
impl<T: Ord> PartialOrd for T {
fn lt(&self, other: &T) -> bool { Ord::lt(self, other) }
fn le(&self, other: &T) -> bool { Ord::le(self, other) }
fn gt(&self, other: &T) -> bool { Ord::gt(self, other) }
fn ge(&self, other: &T) -> bool { Ord::ge(self, other) }
}
// Bar implements Eq/Ord/PartialEq/PartialOrd
//
// The deriving code only derives an Ord and Eq implementaion, *not* PartialEq or PartialOrd
#[deriving(Eq, Ord)]
pub struct Bar(int);
// Foo implements Eq/Ord/PartialEq/PartialOrd
pub struct Foo(int);
impl Eq for Foo {
fn eq(&self, other: &Foo) -> bool { self.a == other.a }
}
impl Ord for Foo {
fn cmp(&self, other: &Foo) -> Ordering { self.a.cmp(&other.a) }
}
// Baz implements PartialEq/PartialOrd
pub struct Baz { x: f64 }
impl PartialEq for Baz {
fn eq(&self, other: &Baz) -> bool { self.x == other.x }
}
impl PartialOrd for Baz {
fn lt(&self, other: &Baz) -> bool { self.x < other.x }
}
// Baz2 implements PartialEq/PartialOrd
#[deriving(PartialEq, PartialOrd)]
pub struct Baz2 { x: f64 }
// Works because Eq implies PartialEq
fn foo1<T: Eq>(t1: &T, t2: &T) {
t1 == t2
}
// Works because == is wired to PartialEq
fn foo2<T: PartialEq>(t1: &T, t2: &T) {
t1 == t2
}
// Works because Ord implies PartialOrd
fn foo3<T: Ord>(t1: &T, t2: &T) {
t1 < t2
}
// Works because < is wired to PartialOrd
fn foo4<T: PartialOrd>(t1: &T, t2: &T) {
t1 < t2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment