Hi,
I'm struggling with lifetimes, moves and borrowings... all the common things for beginners I guess?
What I want to do is basically store a collection of items into 3 different index maps. I don't need the keep the original collection, having the items in the maps is sufficient.
I had a first version where I clone the items for each different maps, and it compiles fine. But I would like to use references instead. Here's my code so far :
use super::files;
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserInfo {
int_idx: i32,
name: String,
prov: String,
prov_u_id: String,
}
pub struct Users<'a> {
by_id: HashMap<i32, UserInfo>,
by_name: HashMap<String, &'a UserInfo>,
by_provid: HashMap<String, &'a UserInfo>,
}
fn provider_key(pname: String, id: String) -> String { format!("{}-{}", pname, id) }
pub fn load_users<'a>() -> Users<'a> {
let content = files::read_file("users/_index.json").expect("Could not open users index file");
let raw_users: Vec<UserInfo> = serde_json::from_str(&content).expect("Could not deserialize index file");
println!("{:?}", raw_users);
let mut by_id: HashMap<i32, UserInfo> = HashMap::new();
let mut by_name: HashMap<String, &'a UserInfo> = HashMap::new();
let mut by_provid: HashMap<String, &'a UserInfo> = HashMap::new();
for user in raw_users {
let prov_key = provider_key(user.prov.to_owned(), user.prov_u_id.to_owned());
if !by_id.contains_key(&user.int_idx) && !by_name.contains_key(&user.name) && !by_provid.contains_key(&prov_key) {
let u1 = user.clone();
let ref_user = &u1;
by_id.insert(u1.int_idx, u1);
by_name.insert(u1.name.to_owned(), ref_user);
by_provid.insert(prov_key, ref_user);
}
}
Users {
by_id: by_id,
by_name: by_name,
by_provid: by_provid,
}
}
My idea is to have the first Map containing the owned objects, and the two others containing references.
But it doesn't compile because " u1
does not live long enough". I would like to make explicit that lifetime of the reference is the same as the owned object itself, but I don't know how. How could I do?
Thanks
Joel