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?
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.