I have the following minimized code that produces a lifetime compiler error. It fails only when iter()
is involved.
use std::collections::HashMap;
struct Person<'a> {
name: &'a str,
}
struct PersonInfo<'a> {
info: &'a str,
}
struct Model<'a> {
persons: Vec<Person<'a>>,
person_info_map: HashMap<String, PersonInfo<'a>>,
}
impl<'a> Model<'a> {
fn build(&'a mut self) -> Vec<&'a PersonInfo<'a>> {
let person_info_map = &mut self.person_info_map;
self.persons.iter().map(|person| {
update_info(person, person_info_map)
}).collect()
}
}
fn update_info<'a>(
person: &'a Person,
info_map: &'a mut HashMap<String, PersonInfo<'a>>,
) -> &'a PersonInfo<'a> {
let name = person.name.to_string();
let entry = info_map.entry(name);
entry.or_insert_with(|| { PersonInfo { info: person.name }})
}
The error seems to be centered around:
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 22:33...
--> src/lib.rs:22:33
|
22 | self.persons.iter().map(|person| {
| ^^^^^^^^
But I think the references returned by iter()
should be able to live for the same lifetime as the collection being iterated over (which has the lifetime of 'a
). Why does person have '_
lifetime and not 'a
.
If I add person: Person<'a>,
to the Model
struct, then update_info(&self.person, person_info_map)
(added to build
) compiles just fine.
Any tips on fixing this?