鍍金池/ 教程/ Java/ 控制流(control flow)
標(biāo)準(zhǔn)輸入與輸出
消息傳遞
循環(huán)
注釋
Rust for Mac OS
幾種智能指針
Cell, RefCell
trait對(duì)象 (trait object)
rust web 開發(fā)
Unsafe、原始指針
Macro
迭代器
函數(shù)
Borrow, BorrowMut, ToOwned
快速上手
二叉樹
編輯器
測(cè)試與評(píng)測(cè)
Deref
安裝Rust
哈希表 HashMap
原生類型
17.錯(cuò)誤處理
VS Code 安裝配置
動(dòng)態(tài)數(shù)組Vec
模式匹配
操作符和格式化字符串
Rust for Linux
函數(shù)參數(shù)
Visual Studio
vim/GVim安裝配置
閉包作為參數(shù)和返回值
安全(Safety)
Cow
生命周期( Lifetime )
閉包的實(shí)現(xiàn)
所有權(quán)(Ownership)
Atom
將Rust編譯成庫
類型、運(yùn)算符和字符串
類型系統(tǒng)中的幾個(gè)常見 trait
特性
屬性和編譯器參數(shù)
Spacemacs
集合類型
Rust json處理
Heap & Stack
并行
標(biāo)準(zhǔn)庫示例
基本程序結(jié)構(gòu)
鏈表
trait 和 trait對(duì)象
前期準(zhǔn)備
代碼風(fēng)格
編譯器參數(shù)
基于語義化版本的項(xiàng)目版本聲明與管理
Rust 版本管理工具: rustup
引用&借用(References&Borrowing)
注釋與文檔
10.1 trait關(guān)鍵字
模式
調(diào)用ffi函數(shù)
unsafe
并發(fā),并行,多線程編程
AsRef 和 AsMut
Rust旅程
Rust for Windows
結(jié)構(gòu)體與枚舉
條件分支
附錄I-術(shù)語表
變量綁定與原生類型
Mutex 與 RwLock
泛型
裸指針
常用數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn)
系統(tǒng)命令:調(diào)用grep
Into/From 及其在 String 和 &str 互轉(zhuǎn)上的應(yīng)用
共享內(nèi)存
Sublime
網(wǎng)絡(luò)模塊:W貓的回音
函數(shù)返回值
包和模塊
高階函數(shù)
函數(shù)與方法
match關(guān)鍵字
隊(duì)列
目錄操作:簡(jiǎn)單grep
語句和表達(dá)式
并發(fā)編程
閉包
測(cè)試
閉包的語法
同步
迭代器
String
Send 和 Sync
Rc 和 Arc
屬性
Emacs
優(yōu)先隊(duì)列
Prelude
cargo簡(jiǎn)介
控制流(control flow)
數(shù)組、動(dòng)態(tài)數(shù)組和字符串
FFI
模塊和包系統(tǒng)、Prelude
實(shí)戰(zhàn)篇
Rust 是一門系統(tǒng)級(jí)編程語言,被設(shè)計(jì)為保證內(nèi)存和線程安全,并防止段錯(cuò)誤。作為系統(tǒng)級(jí)編程語言,它的基本理念是 “零開銷抽象”。理
運(yùn)算符重載
Any和反射
rust數(shù)據(jù)庫操作
輸入輸出流
復(fù)合類型
性能測(cè)試

控制流(control flow)

If

If是分支 (branch) 的一種特殊形式,也可以使用elseelse if。 與C語言不同的是,邏輯條件不需要用小括號(hào)括起來,但是條件后面必須跟一個(gè)代碼塊。 Rust中的if是一個(gè)表達(dá)式 (expression),可以賦給一個(gè)變量:

let x = 5;

let y = if x == 5 { 10 } else { 15 };

Rust是基于表達(dá)式的編程語言,有且僅有兩種語句 (statement):

  1. 聲明語句 (declaration statement),比如進(jìn)行變量綁定的let語句。
  2. 表達(dá)式語句 (expression statement),它通過在末尾加上分號(hào);來將表達(dá)式變成語句, 丟棄該表達(dá)式的值,一律返回unit()

表達(dá)式如果返回,總是返回一個(gè)值,但是語句不返回值或者返回(),所以以下代碼會(huì)報(bào)錯(cuò):

let y = (let x = 5);

let z: i32 = if x == 5 { 10; } else { 15; };

值得注意的是,在Rust中賦值 (如x = 5) 也是一個(gè)表達(dá)式,返回unit的值()

For

Rust中的for循環(huán)與C語言的風(fēng)格非常不同,抽象結(jié)構(gòu)如下:

for var in expression {
    code
}

其中expression是一個(gè)迭代器 (iterator),具體的例子為0..10 (不包含最后一個(gè)值), 或者[0, 1, 2].iter()

While

Rust中的while循環(huán)與C語言中的類似。對(duì)于無限循環(huán),Rust有一個(gè)專用的關(guān)鍵字loop。 如果需要提前退出循環(huán),可以使用關(guān)鍵字break或者continue, 還允許在循環(huán)的開頭設(shè)定標(biāo)簽 (同樣適用于for循環(huán)):

'outer: loop {
   println!("Entered the outer loop");

   'inner: loop {
       println!("Entered the inner loop");
       break 'outer;
   }

   println!("This point will never be reached");
}

println!("Exited the outer loop");

Match

Rust中的match表達(dá)式非常強(qiáng)大,首先看一個(gè)例子:

let day = 5;

match day {
  0 | 6 => println!("weekend"),
  1 ... 5 => println!("weekday"),
  _ => println!("invalid"),
}

其中|用于匹配多個(gè)值,...匹配一個(gè)范圍 (包含最后一個(gè)值),并且_在這里是必須的, 因?yàn)?code>match強(qiáng)制進(jìn)行窮盡性檢查 (exhaustiveness checking),必須覆蓋所有的可能值。 如果需要得到|或者...匹配到的值,可以使用@綁定變量:

let x = 1;

match x {
    e @ 1 ... 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}

使用ref關(guān)鍵字來得到一個(gè)引用:

let x = 5;
let mut y = 5;

match x {
    // the `r` inside the match has the type `&i32`
    ref r => println!("Got a reference to {}", r),
}

match y {
    // the `mr` inside the match has the type `&i32` and is mutable
    ref mut mr => println!("Got a mutable reference to {}", mr),
}

再看一個(gè)使用match表達(dá)式來解構(gòu)元組的例子:

let pair = (0, -2);

match pair {
    (0, y) => println!("x is `0` and `y` is `{:?}`", y),
    (x, 0) => println!("`x` is `{:?}` and y is `0`", x),
    _ => println!("It doesn't matter what they are"),
}

match的這種解構(gòu)同樣適用于結(jié)構(gòu)體或者枚舉。如果有必要,還可以使用..來忽略域或者數(shù)據(jù):

struct Point {
    x: i32,
    y: i32,
}

let origin = Point { x: 0, y: 0 };

match origin {
    Point { x, .. } => println!("x is {}", x),
}

enum OptionalInt {
    Value(i32),
    Missing,
}

let x = OptionalInt::Value(5);

match x {
    // 這里是 match 的 if guard 表達(dá)式,我們將在以后的章節(jié)進(jìn)行詳細(xì)介紹
    OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
    OptionalInt::Value(..) => println!("Got an int!"),
    OptionalInt::Missing => println!("No such luck."),
}

此外,Rust還引入了if letwhile let進(jìn)行模式匹配:

let number = Some(7);
let mut optional = Some(0);

// If `let` destructures `number` into `Some(i)`, evaluate the block.
if let Some(i) = number {
    println!("Matched {:?}!", i);
} else {
    println!("Didn't match a number!");
}

// While `let` destructures `optional` into `Some(i)`, evaluate the block.
while let Some(i) = optional {
    if i > 9 {
        println!("Greater than 9, quit!");
        optional = None;
    } else {
        println!("`i` is `{:?}`. Try again.", i);
        optional = Some(i + 1);
    }
}