I am trying to create a struct which contains a Vec v
and a HashMap m
with references to v
elements as keys. Something like
use std::collections::HashMap;
struct VecMap<'a> {
v: Vec<String>,
m: HashMap<&'a String, u32>
}
fn func() -> VecMap {
let keys = vec!["a".to_string(), "b".to_string()];
let mut vm = VecMap{v:keys, m:HashMap::new()};
for k in &vm.v {
vm.m.insert(&k,0);
}
vm
}
fn main() {
let vm = func();
}
I am getting the following error
error[E0106]: missing lifetime specifier
--> src/main.rs:8:15
|
8 | fn func() -> VecMap {
| ^^^^^^ help: consider giving it a 'static lifetime: `VecMap + 'static`
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
I guess the problem is that VecMap's HashMap contains references borrowed from the Vec, but the compiler has no way of making sure that these references will remain valid during the HashMap's lifetime, since its lifetime isn't bound to that of the Vec. The VecMap is supposed to be immutable after its creation. The code compiles if the func function does not return a value, I guess because, in this case, the compiler knows tha both of them will die at the end of func.
Is that indeed the problem? How to get round this?