Created
January 30, 2016 10:45
-
-
Save zdenal/bd2409b371d12b91849c to your computer and use it in GitHub Desktop.
This file contains 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
macro_rules! with_key { | |
($($t:ty),+) => ($( | |
impl WithKey for $t { | |
fn key(&self) -> &str { | |
&self.key | |
} | |
} | |
)+); | |
} | |
#[derive(Debug)] | |
struct A { | |
key: String, | |
min: u8 | |
} | |
// T because there can be another structure eg. B with 'key' | |
#[derive(Debug)] | |
struct Aggregation<T> { | |
collection: Vec<T> | |
} | |
trait WithKey { | |
fn key(&self) -> &str; | |
fn has_key(&self, value: &str) -> bool { | |
self.key() == value | |
} | |
} | |
with_key! { A } | |
impl<T:WithKey> Aggregation<T> { | |
fn find_by_key(&self, value: String) -> &T { | |
self.collection.iter().find(|t| t.has_key(&value)).unwrap() | |
} | |
} | |
fn main() { | |
let a = A{ key: "key1".to_string(), min: 1 }; | |
let b = A{ key: "key2".to_string(), min: 2 }; | |
let collection = vec!(a,b); | |
let aggr = Aggregation { collection: collection }; | |
let res = aggr.find_by_key("key2".to_string()); | |
println!("{:?}", res); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment