【问题标题】:How do I collect from a nested iterator?如何从嵌套迭代器中收集?
【发布时间】:2018-04-22 13:27:38
【问题描述】:

我正在尝试从嵌套迭代器中收集数据,但收到 FromIterator 未实现错误。这是一个例子:

#[derive(PartialEq)]
enum DayStatus {
    Normal,
    Abnormal,
}

struct Week {
    days: Vec<Day>,
}

struct Day {
    status: DayStatus,
}

struct Month {
    weeks: Vec<Week>,
}

fn get_abnormal_days(month: Month) -> Vec<Day> {
    // assume we have a month: Month which is filled
    month
        .weeks
        .iter()
        .map(|w| w.days.iter().filter(|d| d.status == DayStatus::Abnormal))
        .collect()
}

fn main() {}

给我:

 error[E0277]: the trait bound `std::vec::Vec<Day>: std::iter::FromIterator<std::iter::Filter<std::slice::Iter<'_, Day>, [closure@src/main.rs:24:39: 24:74]>>` is not satisfied
  --> src/main.rs:25:10
   |
25 |         .collect()
   |          ^^^^^^^ a collection of type `std::vec::Vec<Day>` cannot be built from an iterator over elements of type `std::iter::Filter<std::slice::Iter<'_, Day>, [closure@src/main.rs:24:39: 24:74]>`
   |
   = help: the trait `std::iter::FromIterator<std::iter::Filter<std::slice::Iter<'_, Day>, [closure@src/main.rs:24:39: 24:74]>>` is not implemented for `std::vec::Vec<Day>`

我可以尝试implFromIterator,但它必须来自的类型似乎太内向而无法处理。我想我没有打电话给正确的collect 或者map,但我看不出我错过了什么

我第一次尝试返回 &amp;[Day],但也失败了。

【问题讨论】:

    标签: rust


    【解决方案1】:

    要取消嵌套迭代器,请使用flat_map 而不是map

    此外,您需要使用 Copy 类型或使用 into_iter 来迭代拥有的值而不仅仅是引用。

    工作示例:

    #[derive(PartialEq)]
    enum DayStatus {
        Normal,
        Abnormal,
    }
    
    struct Week {
        days: Vec<Day>,
    }
    
    struct Day {
        status: DayStatus,
    }
    
    struct Month {
        weeks: Vec<Week>,
    }
    
    fn get_abnormal_days(month: Month) -> Vec<Day> {
        // assume we have a month: Month which is filled
        month
            .weeks
            .into_iter()
            .flat_map(|w| {
                w.days
                    .into_iter()
                    .filter(|d| d.status == DayStatus::Abnormal)
            })
            .collect()
    }
    
    fn main() {}
    

    【讨论】:

    • 感谢您的洞察,我的示例有一个错误:Weekdays[Day; 7] 而不是Vec&lt;Day&gt;。它有什么不同吗?我之所以问,是因为我仍然面临一个错误:无法从 &amp;timedata::flexday::FlexDay 类型的元素上的迭代器构建 std::vec::Vec&lt;timedata::flexday::FlexDay&gt; 类型的集合 | = 帮助:std::iter::FromIterator&lt;&amp;timedata::flexday::FlexDay&gt; 的特征没有为 std::vec::Vec&lt;timedata::flexday::FlexDay&gt; 实现
    • 它确实有所作为,但我不明白为什么。在into_iter() 之前添加to_vec() 可以解决问题,但我不明白这里发生了什么:-/
    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多