I am having trouble understanding why adding an early collect()
call is necessary to prevent the error "closure may outlive the current function" error in nested closure" in my code.
Relevant snippet of the function (full version on the playground):
input.iter().enumerate().flat_map(|(row_idx, row)| {
let row_max = row.iter().max();
row.iter().enumerate().filter_map(|(col_idx, &val)| {
let col_min = col_mins[col_idx];
// Side question: Why is Some(&val) required on the left and Some(val)
// on the right in the conditional below?
if Some(&val) == row_max && Some(val) == col_min {
Some((row_idx, col_idx))
} else {
None
}
}).collect::<Vec<(usize, usize)>>() // <-- Why is this necessary?
// Without the collect ^, the compiler complains about the filter_map closure:
// "closure may outlive the current function, but it borrows `row_max`, which is owned by the current function"
// If I add the `move` keyword to that closure, the compiler error changes to:
// "cannot move out of captured variable in an `FnMut` closure"
}).collect::<Vec<(usize, usize)>>()