Rust教學
Rust下載和安裝
Rust簡介
Rust Hello World
Rust的特點
Rust註釋
Rust開發環境安裝
Rust文檔
Rust第一個程序
Rust格式化打印
Rust調試
Rust顯示
測試用例:列表
Rust格式化
Rust原語
Rust常量和運算符
Rust元組
Rust數組和切片
Rust自定義類型
Rust結構
Rust可視性
Rust枚舉
Rust常量
Rust變量綁定
Rust變量綁定-可變性
Rust變量綁定-範圍和陰影
Rust變量綁定-聲明
Rust類型轉換
Rust類型轉換 - 字面量
Rust類型轉換-推導
Rust類型轉換 - 別名
Rust表達式
Rust if/else語句
Rust循環
Rust嵌套和標籤
Rust while循環
Rust for和範圍
Rust匹配/match
Rust匹配析構元組
Rust解構枚舉
Rust指針和引用
Rust解構結構
Rust Guards
Rust綁定
Rust if let
Rust while let
Rust函數
Rust方法
Rust閉包
Rust捕捉
Rust作爲輸入參數
Rust匿名類型
Rust輸入函數
Rust作爲輸出參數
Rust if let
if let
對於一些使用情況,匹配很尷尬。例如:
// Make `optional` of type `Option
`
let optional = Some(7);
match optional {
Some(i) => {
println!("This is a really long string and `{:?}`", i);
// ^ Needed 2 indentations just so we could destructure
// `i` from the option.
},
_ => {},
// ^ Required because `match` is exhaustive. Doesn't it seem
// like wasted space?
};
if let 是清潔器用例,另外允許指定的各種失敗選項:
fn main() {
// All have type `Option
`
let number = Some(7);
let letter: Option
= None; let emoticon: Option
= None; // The \`if let\` construct reads: "if \`let\` destructures \`number\` into // \`Some(i)\`, evaluate the block (\`{}\`). Else do nothing. if let Some(i) = number { println!("Matched {:?}!", i); } // If you need to specify a failure, use an else: if let Some(i) = letter { println!("Matched {:?}!", i); } else { // Destructure failed. Change the failure case. println!("Didn't match a number. Let's go with a letter!"); }; // Provide an altered failing condition. let i\_like\_letters = false; if let Some(i) = emoticon { println!("Matched {:?}!", i); // Destructure failed. Evaluated the condition to see if this branch // should be taken. } else if i\_like\_letters { println!("Didn't match a number. Let's go with a letter!"); // The condition evaluated false. This branch is the default. } else { println!("I don't like letters. Let's go with an emoticon :)!"); }; }
也可以參考:
enum
, Option
, 和 RFC