My aim is to retrieve an iterator over all elements in a matrix alongside the row number associated with each element.
The following is a simplified version of the lifetime issue i'm running into.
fn main() {
let mat = [ [1i32, 2, 3],
[4, 5, 6],
[7, 8, 9] ];
// Create an iterator that produces each element alongside its row number.
let all_elems = mat.iter().enumerate().flat_map(|(row, arr)| {
arr.iter().map(|elem| (row, elem)) // Error occurs here.
});
for (row, elem) in all_elems {
println!("Row: {}, Elem: {}", row, elem);
}
}
Here's the error I'm getting:
<anon>:10:9: 10:43 error: cannot infer an appropriate lifetime for lifetime parameter 'r in function call due to conflicting requirements
<anon>:10 arr.iter().map(|elem| (row, elem))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:10:24: 10:42 note: first, the lifetime cannot outlive the expression at 10:23...
<anon>:10 arr.iter().map(|elem| (row, elem))
^~~~~~~~~~~~~~~~~~
<anon>:10:24: 10:42 note: ...so type `|&i32| -> (uint, &i32)` of expression is valid during the expression
<anon>:10 arr.iter().map(|elem| (row, elem))
^~~~~~~~~~~~~~~~~~
<anon>:10:9: 10:43 note: but, the lifetime must be valid for the method call at 10:8...
<anon>:10 arr.iter().map(|elem| (row, elem))
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:10:24: 10:42 note: ...so that argument is valid for the call
<anon>:10 arr.iter().map(|elem| (row, elem))
^~~~~~~~~~~~~~~~~~
Here's the playpen link.
The issue seems to stem from an inability to infer the lifetime in the map method's closure argument, though I'm unsure why.
- Can someone explain the issue here a little more clearly?
- Is it possible to produce the desired iterator another way?