Loop breakage optimization

Hi!

I often find myself writing this code of loop:

for item in items {
    let mut skip_item = false;

    for predicate in exclusion_predicates {
        if predicate(item) {
            skip_item = true;
            break;
        }
    }
    
    if skip_item {
        continue;
    }
    
    // do some stuff
}

What I'd love to write is something like:

for item in items {
    for predicate in exclusion_predicates {
        if predicate(item) {
            continue $parent;
        }
    }

    // do some stuff
}

Is there such a syntax, or an equivalent mechanism in Rust to avoid writing the large snippet I wrote first?

Note that the // do some stuff is a large portion of code which I'd like to not put behind an if !skip_item {.

Thanks in advance for your help :slight_smile:

You can use something like 'outer: for item in items { for predicate in ... { if predicate(item) { continue 'outer; } } }.

1 Like

Very nice, thanks for your help :smiley:

You could also shorten this to:

for item in items {
    if exclusion_predicates.iter().any(|pred| pred(item))) {
        break
    }
    // do some stuff
}
1 Like

I thought about it, but given the actual predicate I use in my code is very long, I doubt this would be very readable (triple condtion with function calls), and I forgot to specify but my predicate may also return an Err(), so it's more like if predicate(item)? {

But thanks for the idea :slight_smile: