分区迭代器时,Vec未实现特征Extend

问题描述

在向量迭代器上调用.partition()时遇到错误

error[E0277]: the trait bound `std::vec::Vec<std::result::Result<std::collections::HashSet<&std::string::String>,std::Boxed::Box<dyn std::error::Error>>>: std::iter::Extend<&std::result::Result<std::collections::HashSet<std::string::String>,std::Boxed::Box<dyn std::error::Error>>>` is not satisfied
 --> src/main.rs:9:24
  |
9 |         results.iter().partition(|r| r.is_ok());
  |                        ^^^^^^^^^ the trait `std::iter::Extend<&std::result::Result<std::collections::HashSet<std::string::String>,std::Boxed::Box<dyn std::error::Error>>>` is not implemented for `std::vec::Vec<std::result::Result<std::collections::HashSet<&std::string::String>,std::Boxed::Box<dyn std::error::Error>>>`
  |
  = help: the following implementations were found:
            <std::vec::Vec<T> as std::iter::Extend<&'a T>>
            <std::vec::Vec<T> as std::iter::Extend<T>>

运行以下代码时:

use std::collections::HashSet;

type Result<T> = std::result::Result<T,Box<dyn std::error::Error>>;

fn main() {
    let mut results: Vec<Result<HashSet<String>>> = Default::default();

    let (okays,errors): (Vec<Result<HashSet<&String>>>,Vec<_>) =
        results.iter().partition(|r| r.is_ok());
}

例如,请参见playground

解决方法

错误消息指出(删除了命名空间):

Extend<&Result<HashSet<String>,Box<dyn Error>>>未实现特征Vec<Result<HashSet<&String>,Box<dyn Error>>>

您不能使用类型为Vec<T>的元素来扩展&T,因为它们不是同一类型

相反,您可以执行以下操作之一:

  1. 将目标集合的类型更改为Vec<&Result<HashSet<String>>>(或仅将Vec<_>更改为第二个目标类型,以允许编译器推断内部类型)。

  2. 可以通过cloneto_owned将引用转换为拥有的值。

  3. 不要使用into_iterdrain来迭代引用开头。

但是,由于要声明拥有Result且拥有HashMap但拥有 reference { {1}}。

我认为最好的方法是使用Itertools::partition_mapString

into_iter

另请参阅: