如何从嵌套迭代器中收集?

时间:2018-04-22 13:27:38

标签: rust

我正在尝试从嵌套迭代器中收集并且我得到一个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>`

我可以尝试impl FromIterator,但它必须来自的类型似乎太内心无法处理。我想我没有打电话给collect或者map,但是我看不到我错过了什么

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

1 个答案:

答案 0 :(得分: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() {}