【问题标题】:How can I return a filtering iterator that captures an argument?如何返回捕获参数的过滤迭代器?
【发布时间】:2020-06-03 21:55:23
【问题描述】:

我正在尝试创建一个基于参数过滤切片的迭代器。

fn dates_from_iterator_ref<'a>(
    from: &'a NaiveDate,
    dates: &'a [NaiveDate],
) -> impl Iterator<Item = &'a NaiveDate> {
    dates.iter().filter(|&date| date >= from)
}

fn dates_from_iterator_val<'a>(
    from: NaiveDate,
    dates: &'a [NaiveDate],
) -> impl Iterator<Item = &'a NaiveDate> {
    dates.iter().filter(|&&date| date >= from)
}

无论我将参数作为引用还是值传递,我都会得到相同的错误:

   |
89 | fn dates_from_iterator_ref<'a>(
   |                            -- lifetime `'a` defined here
...
92 | ) -> impl Iterator<Item = &'a NaiveDate> {
   |      ----------------------------------- opaque type requires that `from` is borrowed for `'a`
93 |     dates.iter().filter(|&date| date >= from)
   |                         -------         ^^^^ borrowed value does not live long enough
   |                         |
   |                         value captured here
94 | }
   | - `from` dropped here while still borrowed

我怎样才能让它工作?

【问题讨论】:

    标签: rust iterator closures


    【解决方案1】:

    对于值版本,您只需要通过添加 move 关键字来确保闭包通过将值移动到捕获中而不是借用它来捕获date 的值。

    另外,正如@LukasKalbertodt 所指出的,你should change|&amp;&amp;date| date &gt;= from|&amp;date| date &gt;= &amp;from 的闭包。

    pub fn dates_from_iterator_val<'a>(
        from: NaiveDate,
        dates: &'a [NaiveDate],
    ) -> impl Iterator<Item = &'a NaiveDate> {
        dates.iter().filter(move |&date| date >= &from)
    }
    

    对于 ref 版本,同样适用,但移动的是引用而不是值:

    pub fn dates_from_iterator_ref<'a>(
        from: &'a NaiveDate,
        dates: &'a [NaiveDate],
    ) -> impl Iterator<Item = &'a NaiveDate> {
        dates.iter().filter(move |&date| date >= from)
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 2020-03-14
      • 2019-09-06
      • 1970-01-01
      • 2021-05-09
      相关资源
      最近更新 更多