gpt4 book ai didi

rust - 在对迭代器进行分区时,未为Vec实现特征Extend

转载 作者:行者123 更新时间:2023-12-03 11:47:56 24 4
gpt4 key购买 nike

在向量迭代器上调用.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

最佳答案

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

the trait Extend<&Result<HashSet<String>, Box<dyn Error>>> is not implemented for Vec<Result<HashSet<&String>, Box<dyn Error>>>


您不能使用 Vec<T>类型的元素来扩展 &T,因为 它们与类型不同。
相反,您可以执行以下操作之一:
  • 将目标集合的类型更改为Vec<&Result<HashSet<String>>>(或仅将Vec<_>更改为第二种目标类型,以允许编译器推断内部类型)。
  • 可以通过cloneto_owned将引用转换为拥有的值。
  • 不要使用into_iterdrain遍历开头的引用。

  • 但是,当前的类型很难实现,也很难实现,因为您声明要拥有拥有的 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>>)
    }
    也可以看看:
  • What is the difference between iter and into_iter?
  • 关于rust - 在对迭代器进行分区时,未为Vec实现特征Extend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63565121/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com