Is it possible to use patterns matching security devices in `while let`?

I have a while let that iterates through the Result iterator and uses pattern matching; it iterates over the iterator until it hits the Err or Ok value, this is an empty string:

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

This code is working fine. However, I think the if looks ugly and probably not idiomatic Rust. In match statements, guards can be used when matching with a pattern, for example:

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

This would be ideal for my while let , although the pattern matching used there does not seem to support it, causing a syntax error:

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

Is there any way to use the guards in while let state? If not, is there a better way to exit the loop if an empty string is found?

+5
source share
1 answer

No, while let and if let patterns cannot be protected. There have been several discussions about changing this (for example, here ), but so far nothing has been decided.

As for the alternatives, I think your version is pretty clear, and I can't figure out how to improve it.

+3
source

Source: https://habr.com/ru/post/1258845/


All Articles