我想练习使用Rust的函数式能力。
例如,我想将这个循环转换为函数式:
levels: Vec<Vec<u8>> = //< Built by something
let mut total = 0;
for (x, y) in iproduct!(0..10, 0..10) {
if levels[x][y] > 9 {
total += count_something(levels, x, y);
}
}
// Edit: here's the `count_something` function signature
fn count_something (levels: &mut Vec<Vec<u8>>, x: usize, y: usize) -> usize {
// Count
}
这是我的功能重构的结果:
iproduct!(0..10, 0..10)
.filter(|(x, y)| levels[*x][*y] > 9)
.map(|(x, y)| count_something(levels, x, y))
.sum()
问题是:这段代码无法编译。
错误信息:
error[E0500]: closure requires unique access to *levels but it is already borrowed
。我不理解为什么
filter
会借用levels
二维矩阵。
我的内部模型似乎无法解释这个问题。
count_something
如何声明(如果它需要可变引用,那么你就有了答案)。 - Denys Séguretcount_something
,因为我认为这是不必要的细节。我错了吗? - gberth