Created
January 1, 2020 12:38
-
-
Save rust-play/1beb3c22ed1c741f94834cf5e6770fa2 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
use std::collections::HashMap; | |
#[derive(Debug)] | |
struct Item { | |
name: String, | |
value: i64, | |
} | |
impl Item { | |
fn new(n: &str, v: i64) -> Self { | |
Self { | |
name: n.to_owned(), | |
value: v, | |
} | |
} | |
} | |
#[derive(Debug)] | |
struct Container<'a> { | |
index: HashMap<&'a str, &'a Item>, | |
} | |
impl<'a> Container<'a> { | |
fn new(items: &'a [Item]) -> Self { | |
Self { | |
index: Self::index_items(items), | |
} | |
} | |
fn index_items(items: &[Item]) -> HashMap<&str, &Item> { | |
let mut result = HashMap::<&str, &Item>::new(); | |
for item in items { | |
result.insert(&item.name, &item); | |
} | |
result | |
} | |
} | |
fn main() { | |
let items = vec![Item::new("foo", 1), Item::new("bar", 2)]; | |
dbg!(&items); | |
let index = Container::index_items(&items); | |
dbg!(&index); | |
let container = Container::new(&items); | |
dbg!(&container); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment