【问题标题】:Why does the closure for `take_while` take its argument by reference?为什么 `take_while` 的闭包通过引用来获取它的参数?
【发布时间】:2016-03-25 14:02:03
【问题描述】:

这是来自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 的闭包通过引用获取它的参数,而所有其他的都通过值获取?

【问题讨论】:

  • take_while 和 filter 都收到一个引用。在本例中,在 take_while 中,引用被 |&n| 解构,而在 filter 中,引用被 *n 解引用。

标签: closures rust higher-order-functions


【解决方案1】:

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 适配器返回的值!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2013-12-21
    • 1970-01-01
    • 2015-12-27
    • 2015-10-08
    • 2012-05-03
    • 2016-10-21
    相关资源
    最近更新 更多