【发布时间】:2023-03-28 00:21:01
【问题描述】:
我正在尝试从创建每个元素的仿函数创建一个二维矩阵,并将其存储为平面 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
如何在嵌套映射中使用闭包?我解决了这个问题by using a single map on 0..n*m,但我仍然对答案感兴趣。
【问题讨论】:
-
我希望由于 y:usize 是可复制的,它可以被内部闭包按值获取,从而避免任何借用...
-
我同意,而且我有点惊讶这里有一个错误——我觉得这与
FnMut有关。也可能存在一个真正的错误,因为在所有变量上喷洒.clone()并不能像我想的那样解决问题。