Skip to content

Instantly share code, notes, and snippets.

@devyn
Created September 16, 2019 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devyn/a74cecda29ccac2060c66e7051edbea6 to your computer and use it in GitHub Desktop.
Save devyn/a74cecda29ccac2060c66e7051edbea6 to your computer and use it in GitHub Desktop.
use std::cmp::Ordering;
trait Keyed<'a> {
type Key: 'a + Eq + Ord;
fn key(&'a self) -> Self::Key;
}
#[derive(Debug, Clone)]
struct TypeA {
key: (i32, i32),
value: String
}
impl<'a> Keyed<'a> for TypeA {
type Key = (&'a i32, &'a i32);
fn key(&'a self) -> (&'a i32, &'a i32) {
(&self.key.0, &self.key.1)
}
}
#[derive(Debug, Clone)]
struct TypeB {
key_a: i32,
key_b: i32,
value: u64
}
impl<'a> Keyed<'a> for TypeB {
type Key = (&'a i32, &'a i32);
fn key(&'a self) -> (&'a i32, &'a i32) {
(&self.key_a, &self.key_b)
}
}
fn compare<A, B>(a: &A, b: &B) -> Ordering
where for<'a> A: Keyed<'a>,
for<'a> B: Keyed<'a>,
for<'a> <A as Keyed<'a>>::Key: Ord,
for<'a> <B as Keyed<'a>>::Key: Ord,
for<'a> <A as Keyed<'a>>::Key: PartialOrd<<B as Keyed<'a>>::Key> {
a.key().partial_cmp(&b.key()).unwrap()
}
fn main() {
let a = TypeA {
key: (3, 4),
value: "Hello!".into()
};
let b = TypeB {
key_a: 3,
key_b: 5,
value: 9292
};
let order = compare(&a, &b);
println!("{:?}.key() = {:?}", a, a.key());
println!("{:?}.key() = {:?}", b, b.key());
println!("compare({:?}, {:?}) = {:?}", a, b, order);
assert_eq!(order, Ordering::Less);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment