I'm trying to store a reference of an object which is hold in a HashMap
in a Vec
in order to access it in its order of insertion:
Reference from a HashMap in a Vec
use std::collections::HashMap;
use std::vec::Vec;
#[derive(Debug)]
struct Data {
id: u32,
name: String,
}
struct DataFactory<'fct> {
vdatas: Vec<&'fct Data>,
lstdatas: HashMap<u32, Data>,
}
impl<'fct> DataFactory<'fct> {
fn add_data(&'fct mut self, inputdata: Data) -> Option<&mut Data> {
let idtaid = inputdata.id;
self.lstdatas.insert(inputdata.id, inputdata);
let odta = self.lstdatas.get_mut(&idtaid);
match &odta {
Some(dta) => self.vdatas.push(dta),
None => {
eprintln!("data set (id: '{}'): add Data failed!", &idtaid);
}
}
odta
}
}
fn main() {
let mut dfact = DataFactory {
vdatas: Vec::new(),
lstdatas: HashMap::new(),
};
let dset = Data {
id: 11,
name: "dataset 11".to_string(),
};
let odset = dfact.add_data(dset);
println!("added set: '{:?}'", odset);
}
but I'm getting constant compiler errors
Compiling playground v0.0.1 (/playground)
error[E0597]: `odta` does not live long enough
--> src/main.rs:23:15
|
15 | impl<'fct> DataFactory<'fct> {
| ---- lifetime `'fct` defined here
...
23 | match &odta {
| ^^^^^ borrowed value does not live long enough
24 | Some(dta) => self.vdatas.push(dta),
| --- assignment requires that `odta` is borrowed for `'fct`
...
31 | }
| - `odta` dropped here while still borrowed
error[E0505]: cannot move out of `odta` because it is borrowed
--> src/main.rs:30:9
|
15 | impl<'fct> DataFactory<'fct> {
| ---- lifetime `'fct` defined here
...
23 | match &odta {
| ----- borrow of `odta` occurs here
24 | Some(dta) => self.vdatas.push(dta),
| --- assignment requires that `odta` is borrowed for `'fct`
...
30 | odta
| ^^^^ move out of `odta` occurs here
Some errors have detailed explanations: E0505, E0597.
For more information about an error, try `rustc --explain E0505`.
error: could not compile `playground` due to 2 previous errors
and I'm running in cycles with it.
I read lots of documentation about it but all examples and explanations are just too simple or too specific as to be reusable or applicable for this use case.
So, please if anyone knew how to write this correctly or about any documentation that comes close to it it would help me a lot.