If是分支 (branch) 的一種特殊形式,也可以使用else
和else 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):
let
語句。;
來將表達(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的值()
。
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()
。
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");
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 let
和while 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);
}
}