【问题标题】:Why the closure passed to map() does not take a reference while the one passed to filter() takes a reference?为什么传递给 map() 的闭包不带引用,而传递给 filter() 的闭包带引用?
【发布时间】:2021-04-22 07:10:24
【问题描述】:

传递给map() 的闭包不带引用,而传递给filter() 的闭包在Rust 中带引用。大多数迭代器适配器都带有引用。 map() 在 Rust 中没有引用有什么原因吗?

let a = (0..3).map(|x| x*2);
for i in a {
    println!("map i = {}", i);
}

let a = (0..3).filter(|&x| x % 2 == 0);
for i in a {
    println!("filter i = {}", i);
}

【问题讨论】:

    标签: rust reference iterator closures ownership


    【解决方案1】:

    .map(<closure>).filter(<closure>) 有不同的用途。

    .map(<closure>) 将迭代器元素的所有权授予闭包,以便它们可以转换为新元素,然后由闭包返回。

    但是,.filter(<closure>) 在闭包谓词的计算结果为真时返回原始元素。因此,它不能将元素的所有权交给闭包,所以它必须通过引用传递元素。

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      相关资源
      最近更新 更多