问题描述
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
,因为它们不是同一类型。
相反,您可以执行以下操作之一:
-
将目标集合的类型更改为
Vec<&Result<HashSet<String>>>
(或仅将Vec<_>
更改为第二个目标类型,以允许编译器推断内部类型)。 -
可以通过
clone
或to_owned
将引用转换为拥有的值。 -
不要使用
into_iter
或drain
来迭代引用开头。
但是,由于要声明拥有Result
且拥有HashMap
但拥有 reference { {1}}。
我认为最好的方法是使用Itertools::partition_map
和String
:
into_iter
另请参阅: