1

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?

5
  • 2
    map produces another iterator. If you want to abandon the mapping and run code then map might not be the method to go for, maybe your situation can be better handled via try_for_each? Commented Aug 7 at 13:51
  • 3
    the workaround depends on what you're doing, right now your code does nothing since iterators are lazy. If you're just doing something for each item then a for loop would be better suited. If this is a transformation that will be put in a different collection then collecting into a Result will short-circuit on the first failure. Commented Aug 7 at 14:13
  • 6
    Use filter_map and make your closure to wrap the return value in Some(..) on the Ok case and return None on error. If I understand correctly what you are trying to do. Commented Aug 7 at 14:14
  • 1
    While map and filter (or just filter_map) can do what you want, sometimes a for loop is just easier. Commented Aug 7 at 17:06
  • I found the solution, thanks @kmdreko and @BallpointBen! For loops did indeed help, so I just constructed the lists from scratch. Commented Aug 8 at 4:58

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.