Created
September 16, 2019 01:14
-
-
Save devyn/a74cecda29ccac2060c66e7051edbea6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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