我试图从一个创建每个元素的函子中生成一个二维矩阵,并将其存储为一个平面Vec
(每行连接).
我使用嵌套map
(实际上是flat_map
和嵌套map
)来创建每一行并将其连接起来.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);
}
不幸的是,我在编译过程中遇到了一个错误:
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
如何在嵌套映射中使用闭包?我研究了这个问题,但我仍然对答案感兴趣.