Stumbled on a problem while working through The Book. In the third exercise in Chapter 8 I want to display all employees with their departments (not grouped, just flat list). It's easy to achieve it with for loops, but doing it with iterators gives me this error: closure may outlive the current function, but it borrows
dep, which is owned by the current function
let mut deps: HashMap<String, Vec<String>> = HashMap::new();
//....
deps.iter()
.flat_map(|(dep, emps)| emps.iter().map(|emp| (emp, dep)))
.sorted()
.for_each(|(emp, dep)| println!("{emp} ({dep})"));
Passing the dep
value through the inner iterator seems to solve the problem (and in this trivial case, the inner closure becomes redundant):
.flat_map(|(dep, emps)| emps.iter().zip(repeat(dep)).map(|(emp, dep)| (emp, dep)))
but is there a way to make the first version work and reference dep
directly from the inner closure?