未能从 Rust 中的结果向量中过滤 OK 值

问题描述 投票:0回答:1

我浏览过许多博客/SOF 帖子,甚至是这本书。不幸的是,我一定遗漏了一些非常基本的东西。

代码如下:

let data_set: Vec<PerRequestData> =
            vec![
                PerRequestData::new(0, Ok(120)),
                PerRequestData::new(0, Err(FailedRequestError { time_taken_till_failure: 20, exact_reason_for_failure: AppErrorReason::TimeOut })),
                PerRequestData::new(0, Ok(120)),
                PerRequestData::new(0, Err(FailedRequestError { time_taken_till_failure: 20, exact_reason_for_failure: AppErrorReason::ResponseUnavailable })),
                PerRequestData::new(0, Ok(120)),

            ];

        let p = data_set.iter().filter_map(Result::ok).collect();

我打算仅从该 Vector 中过滤出

ok
值,而忽略
Err
s.

但是编译器不赞成对

p
的最后一个赋值。

error[E0631]: type mismatch in function arguments
   --> src/lib.rs:360:44
    |
360 |         let p = data_set.iter().filter_map(Result::ok).collect();
    |                                 ---------- ^^^^^^^^^^
    |                                 |          |
    |                                 |          expected due to this
    |                                 |          found signature defined here
    |                                 required by a bound introduced by this call
    |
    = note: expected function signature `fn(&PerRequestData) -> _`
               found function signature `fn(Result<_, _>) -> _`
note: required by a bound in `std::iter::Iterator::filter_map`
   --> /home/nirmalya/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:944:12
    |
944 |         F: FnMut(Self::Item) -> Option<B>,
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `std::iter::Iterator::filter_map`

编译器试图帮助我解决它不被批准的主要原因是什么,但不知何故,我无法理解为什么它正在寻找一个函数签名

fn(Result<_,_>) -> _
因为所有类型都可用,决定,不是吗

这让我很困扰,因为我以为我已经了解了 Result 的概念及其惯用处理,好吧,很明显,我没有。

请把我推向正确的方向

rust
1个回答
-1
投票

iter()
为您提供了一个迭代器 over references(因为它从对集合的引用中获取),但是
Result::ok()
需要一个拥有的
Result
。您可以使用
Result::as_ref()
,或
into_iter()

let p = data_set.iter().map(Result::and_then).filter_map(Result::ok).collect();
// Or
let p = data_set.into_iter().filter_map(Result::ok).collect();
© www.soinside.com 2019 - 2024. All rights reserved.