My goal is to get an iterator over all the elements in the matrix along with the row number associated with each element.
The following is a simplified version of the lifetime problem in which I run.
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 is the error I get:
<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 is the playpen link.
The problem seems to be related to the inability to infer the lifetime in the argument of closing the map method, although I'm not sure why.
- Can someone explain the problem here a little more clearly?
- Is it possible to create the desired iterator in another way?
source share