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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With