以下是Rust by Example的示例:
fn is_odd(n: u32) -> bool {
n % 2 == 1
}
fn main() {
println!("Find the sum of all the squared odd numbers under 1000");
let upper = 1000;
// Functional approach
let sum_of_squared_odd_numbers: u32 =
(0..).map(|n| n * n) // All natural numbers squared
.take_while(|&n| n < upper) // Below upper limit
.filter(|n| is_odd(*n)) // That are odd
.fold(0, |sum, i| sum + i); // Sum them
println!("functional style: {}", sum_of_squared_odd_numbers);
}
为什么take_while
的闭包是通过引用来获取它的参数,而所有其他的都是以值为基础?
答案 0 :(得分:2)
Iterator::take_while
的实施非常有启发性:
fn next(&mut self) -> Option<I::Item> {
if self.flag {
None
} else {
self.iter.next().and_then(|x| {
if (self.predicate)(&x) {
Some(x)
} else {
self.flag = true;
None
}
})
}
}
如果从底层迭代器返回的值直接传递给谓词,那么该值的所有权也将被传输。调用谓词后,如果谓词为真,则不再有TakeWhile
适配器返回的值!