【发布时间】:2015-08-08 15:09:01
【问题描述】:
我正在尝试编写一个涉及过滤和折叠数组的程序。我一直使用The Rust Programming Language, first edition 作为参考,但我不明白当我在数组上形成迭代器时会发生什么。这是一个例子:
fn compiles() {
let range = (1..6);
let range_iter = range.into_iter();
range_iter.filter(|&x| x == 2);
}
fn does_not_compile() {
let array = [1, 4, 3, 2, 2];
let array_iter = array.into_iter();
//13:34 error: the trait `core::cmp::PartialEq<_>` is not implemented for the type `&_` [E0277]
array_iter.filter(|&x| x == 2);
}
fn janky_workaround() {
let array = [1, 4, 3, 2, 2];
let array_iter = array.into_iter();
// Note the dereference in the lambda body
array_iter.filter(|&x| *x == 2);
}
在第一个函数中,我遵循该范围内的迭代器没有所有权,所以我必须在filter 的 lambda 中取一个&x,但我不明白为什么第二个示例带有数组行为不同。
【问题讨论】:
标签: rust