Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use pattern matching guards in a `while let`?

I have a while let loop which goes over an iterator of Result and uses pattern matching; it goes over the iterator until it either hits an Err or the Ok's value is an empty string:

while let Some(Ok(a)) = some_iterator.next() {
    if a == "" {
        break;
    }
    // ...
}

This code works fine. However, I think the if statement looks ugly and is probably not idiomatic Rust. In match statements, guards can be used in pattern matching, like so:

match foo {
    Some(Ok(a)) if a != "" => bar(a)
    // ...
}

This would be ideal for my while let loop, although the pattern matching employed there doesn't seem to support it, causing a syntax error:

while let Some(Ok(a)) = some_iterator.next() if a != "" { // <-- Syntax error
    // ...
}

Is there any way of using guards like this in the condition of a while let? If not, is there a better way of breaking out of the loop if an empty string is found?

like image 685
Aaron Christiansen Avatar asked Oct 26 '16 18:10

Aaron Christiansen


People also ask

Does Rust have pattern matching?

Patterns are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with match expressions and other constructs gives you more control over a program's control flow.

How does Rust Match work?

Rust has an extremely powerful control-flow operator called match that allows us to compare a value against a series of patterns and then execute code based on which pattern matches.

How does pattern matching work in OCaml?

Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.

How do you match types in Rust?

Instead of matching on an element, call the method in the trait on it. TLDR: in Rust, to match over type, we create a trait, implement a function for each type and call it on the element to match. Surround it with backticks to mark it as code. Single backticks for inline code, triple backticks for code blocks.


1 Answers

No, while let and if let patterns cannot have guards. There has been some discussion about changing that (e.g. here), but nothing has been decided yet.

Regarding alternatives, I think your version is pretty clear and I can't think of any ways to really improve on that.

like image 103
fjh Avatar answered Oct 13 '22 11:10

fjh