A program I'm writing reads in some data and creates a Vec of data objects, each containing a name (String,RegistryData).
I then want to index it with a HashMap, so I can quickly access a named item. I want to keep the Vec also, rather than just placing each item into a HashMap from the beginning.
I've tried the following where my HashMap<String,&RegistryData> would store a reference to an item in the Vec, but I think this fails because I'm not specifying lifetimes. I've tried adding the suggested changes from the compiler, but still can't get to a working version.
Can somebody point me in the right direction?
Is it possible to modify this example so that I can store references to the Vec's contents in the HashMap?
use std::collections::HashMap;
// In real program, this would be a struct
type RegistryData = i32;
#[derive(Debug)]
struct Registry {
data: Vec<(String,RegistryData)>, // names and data in Vec format
map: HashMap<String,&RegistryData>, // map of name -> data
}
impl Registry {
pub fn new() -> Self {
// create some data
let data = [(String::from("foo"), 7), (String::from("bar"), 42)].to_vec();
// create empty hashmap
let mut map:HashMap<String,&RegistryData> = HashMap::new();
// walk through data, adding reference to each to hashmap
for item in &data {
map.insert(item.0.clone(), &item.1);
}
Self {
data: data,
map: map
}
}
}
fn main() {
let registry = Registry::new();
println!("{:#?}", registry);
}