Let এর প্রবাহ নিয়ন্ত্রণ
Rust has a few control flow constructs which differ from other languages. They are used for pattern matching:
if let
expressionswhile let
expressionsmatch
expressions
if let
expressions
The if let
expression lets you execute different code depending on whether a value matches a pattern:
let else
expressions
For the common case of matching a pattern and returning from the function, use let else
. The "else" case must diverge (return
, break
, or panic - anything but falling off the end of the block).
Like with if let
, there is a while let
variant which repeatedly tests a value against a pattern:
Here String::pop
returns Some(c)
until the string is empty, after which it will return None
. The while let
lets us keep iterating through all items.
Speaker Notes
This slide should take about 10 minutes.
if-let
- Unlike
match
,if let
does not have to cover all branches. This can make it more concise thanmatch
. - A common usage is handling
Some
values when working withOption
. - Unlike
match
,if let
does not support guard clauses for pattern matching.
let-else
if-let
s can pile up, as shown. The let-else
construct supports flattening this nested code. Rewrite the awkward version for students, so they can see the transformation.
The rewritten version is:
while-let
- Point out that the
while let
loop will keep going as long as the value matches the pattern. - You could rewrite the
while let
loop as an infinite loop with an if statement that breaks when there is no value to unwrap forname.pop()
. Thewhile let
provides syntactic sugar for the above scenario.