gpt4 book ai didi

rust - 当谓词返回 Result 时如何过滤迭代器?

转载 作者:行者123 更新时间:2023-11-29 08:00:03 25 4
gpt4 key购买 nike

我希望迭代器被过滤,但是我的谓词有失败的可能性。当谓词失败时,我想让整个函数失败。在此示例中,我希望 work 返回由 maybe 生成的 Result:

fn maybe(v: u32) -> Result<bool, u8> {
match v % 3 {
0 => Ok(true),
1 => Ok(false),
2 => Err(42),
}
}

fn work() -> Result<Vec<u32>, u8> {
[1, 2, 3, 4, 5].iter().filter(|&&x| maybe(x)).collect()
}

fn main() {
println!("{:?}", work())
}
error[E0308]: mismatched types
--> src/main.rs:10:45
|
10 | [1, 2, 3, 4, 5].iter().filter(|&&x| maybe(x)).collect()
| ^^^^^^^^ expected bool, found enum `std::result::Result`
|
= note: expected type `bool`
found type `std::result::Result<bool, u8>`

error[E0277]: the trait bound `std::result::Result<std::vec::Vec<u32>, u8>: std::iter::FromIterator<&u32>` is not satisfied
--> src/main.rs:10:55
|
10 | [1, 2, 3, 4, 5].iter().filter(|&&x| maybe(x)).collect()
| ^^^^^^^ a collection of type `std::result::Result<std::vec::Vec<u32>, u8>` cannot be built from an iterator over elements of type `&u32`
|
= help: the trait `std::iter::FromIterator<&u32>` is not implemented for `std::result::Result<std::vec::Vec<u32>, u8>`

最佳答案

您可以打开 Result<bool, u8>进入 Option<Result<u32, u8>> , 即拉出 boolOption并将值放入其中,并使用 filter_map :

fn maybe(v: u32) -> Result<bool, u8> {
match v % 3 {
0 => Ok(true),
1 => Ok(false),
_ => Err(42),
}
}

fn work() -> Result<Vec<u32>, u8> {
[1, 2, 3, 4, 5]
.iter()
.filter_map(|&x| match maybe(x) {
Ok(true) => Some(Ok(x)),
Ok(false) => None,
Err(e) => Some(Err(e)),
})
.collect()
}

fn main() {
println!("{:?}", work())
}

playground

关于rust - 当谓词返回 Result<bool, _> 时如何过滤迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036173/

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