Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 1, 2020 12:38
Show Gist options
  • Save rust-play/1beb3c22ed1c741f94834cf5e6770fa2 to your computer and use it in GitHub Desktop.
Save rust-play/1beb3c22ed1c741f94834cf5e6770fa2 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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