I am trying to make a 2-dimensional matrix from a functor that creates each element, and store it as a flat Vec
(each row concatenated).
I used nested map
(actually a flat_map
and a nested map
) to create each row and concatenate it. Here is what I tried:
fn make<T, F>(n: usize, m: usize, f: F) -> Vec<T>
where
F: Fn(usize, usize) -> T,
{
(0..m).flat_map(|y| (0..n).map(|x| f(x, y))).collect()
}
fn main() {
let v = make(5, 5, |x, y| x + y);
println!("{:?}", v);
}
Unfortunately, I get an error during compilation:
error[E0597]: `y` does not live long enough
--> src/main.rs:5:45
|
5 | (0..m).flat_map(|y| (0..n).map(|x| f(x, y))).collect()
| --- ^ - - borrowed value needs to live until here
| | | |
| | | borrowed value only lives until here
| | borrowed value does not live long enough
| capture occurs here
How does one use closures in nested maps? I worked around this issue by using a single map on 0..n*m
, but I'm still interested in the answer.