控制流程
Rust 的某些控制流程結構與其他程式語言不同。這些結構會用於模式配對:
if let
運算式while let
運算式match
運算式
if let
運算式
if let
運算式可讓您根據值是否符合模式,執行不同的程式碼:
let else
運算式
如果是要配對模式並從函式傳回的常見情況,請使用 let else
。如果是「其他」情況,則必須發散 (return
、break
或恐慌,也就是落在區塊結尾之外的任何情況)。
和 if let
的情況一樣,有一個 while let
變數可針對模式重複測試值:
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
. - 常見用途是在使用
Option
時處理Some
值。 - 與
match
不同,if let
不會為模式比對支援成立條件子句。
let-else
如上所示,if-let
可能會越加越多。let-else
結構支援壓平合併這個巢狀程式碼。請為學生重新編寫這個冗長的版本,讓他們見識改寫的效果。
重新編寫的版本如下:
while-let
- 請指出只要值符合模式,
while let
迴圈就會持續運作。 - 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.