loopsrustiterator

Is there a Rust way to `continue` a loop inside a `map` closure?


I found this question here but that one doesn't really answer my question due to it having an answer centered around unwrap_or_else.

Here is the code I am trying to use, simplified:

let x = loop {
    // stuff
    something.iter().map(|x| match x.fn_that_returns_result() {
        Ok(_) => // snip,
        Err(_) => {
            // handle err;
            continue;
        }
    })
    break value;
}

The problem is that this won't compile, as I can't continue from a map. And I don't know any workarounds, as it's not like unwrap_or_else which is a wrapper around a match.

Is there any way to continue the outer loop from the map method call?


Solution

  • I found the solution with the help of @kmdreko and @BallpointBen!

    Just use a Vec and load all the data into it:

    let x = 'outer: loop {
        // stuff
        let mut y = Vec::new();
        for val in something {
            match val {
                Ok(ans) => {
                    // snip
                    y.push(val);
                },
                Err(_) => { 
                    handle_err();
                    continue 'outer;
                }
            }
        }
        break returnval;
    }