在Rust Book上有一个迭代器调用filter()
的例子:过滤器(| x |)和过滤器(|&x |)之间有什么区别?
for i in (1..100).filter(|&x| x % 2 == 0) {
println!("{}", i);
}
下面有一个解释,但我有了解它的麻烦:
This will print all of the even numbers between one and a hundred. (Note that because filter doesn't consume the elements that are being iterated over, it is passed a reference to each element, and thus the filter predicate uses the &x pattern to extract the integer itself.)
但这不起作用:
for i in (1..100).filter(|&x| *x % 2 == 0) {
println!("i={}", i);
}
为什么参数封闭引用|&x|
,inst ead的|x|
?那么使用|&x|
和|x|
有什么区别?
据我所知,使用参考|&x|
更高效,但我很困惑,因为我不需要使用*x
取消引用x
指针。
因此'let&x = my_pointer'实际上是'let x = * my_pointer'的替代方法,它也可以在函数参数声明中使用?如果是这样,为什么使用'| x |'不会引发错误?从我与C的经验来看,预计会在这里得到一个指针。或者生锈在这里隐式地分配堆栈中原始'x'的值的副本? – jeremija
哦,我有很多东西要学习:)谢谢 - 现在我对它更清楚了! – jeremija