[英]The trait Extend is not implemented for Vec when partitioning an iterator
在向量迭代器上调用.partition()
时.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());
}
以游乐场为例。
正如错误消息所述(删除了命名空间):
特征
Extend<&Result<HashSet<String>, Box<dyn Error>>>
没有为Vec<Result<HashSet<&String>, Box<dyn Error>>>
您不能使用&T
类型的元素扩展Vec<T>
,因为它们不是相同的 type 。
相反,您可以执行以下操作之一:
将目标集合的类型更改为Vec<&Result<HashSet<String>>>
(或者只是Vec<_>
,就像您的第二个目标类型一样,以允许编译器推断内部类型)。
可能通过clone
或to_owned
将引用转换为拥有的值。
不要在开始时迭代引用,而是使用into_iter
或drain
。
但是,您当前的类型将很难实现或成本很高,因为您声明您想要一个拥有Result
和一个拥有的HashMap
但引用String
。
我认为最好的方法是使用Itertools::partition_map
和into_iter
:
use itertools::Itertools; // 0.9.0
use std::collections::HashSet;
type Error = Box<dyn std::error::Error>;
type Result<T, E = Error> = std::result::Result<T, E>;
fn main() {
let mut results: Vec<Result<HashSet<String>>> = Default::default();
let (errors, okays): (Vec<_>, Vec<_>) = results.into_iter().partition_map(Into::into);
// let (errors, okays): (Vec<Error>, Vec<HashSet<String>>)
}
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.