我正在尝试编写一个涉及对数组进行过滤和折叠的程序。我一直在使用The Rust Programming Language第一版作为参考,但我不理解当我在数组上形成迭代器时会发生什么。这里是一个例子:
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
,但我不明白为什么数组的第二个示例表现不同。(在第一函数中,我注意到范围上的迭代器不会拥有所有权,因此我必须在filter
的lambda中使用&x
,但我不明白为什么数组的第二个示例表现不同。)