当谓词返回 Result<bool, _> 时,如何过滤迭代器?

She*_*ter 5 rust

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

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())
}
Run Code Online (Sandbox Code Playgroud)
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())
}
Run Code Online (Sandbox Code Playgroud)

huo*_*uon 6

可以将 转为Result<bool, u8>an Option<Result<u32, u8>>,即把取出来的值放到boolan里面,然后使用:Optionfilter_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())
}
Run Code Online (Sandbox Code Playgroud)

操场