迴圈
最後更新
Rust 有三種迴圈:無限重複的
loop、依條件重複的 while、走訪集合與範圍的 for,再搭配 break、continue 與迴圈標籤控制流程。loop:重複到你喊停
loop 會一直重複執行,直到遇到 break。適合「不知道要跑幾次,但知道何時該停」的情境,例如重試、讀取輸入直到結束、事件迴圈。用 break 離開
break 立刻跳出最內層的迴圈,接著執行迴圈之後的程式碼。範例:
- fn main() {
- let mut tries = 0;
- loop {
- tries += 1;
- println!("第 {tries} 次嘗試");
- if tries == 3 {
- break;
- }
- }
- println!("結束");
- }
輸出:
- 第 1 次嘗試
- 第 2 次嘗試
- 第 3 次嘗試
- 結束
break 帶回一個值
loop 是表達式:break 值 會讓整個 loop 的結果變成那個值,可以直接用 let 接住。下例找出第一個超過 1000 的 3 的次方。只有 loop 能這樣用,while 與 for 的值固定是 (),因為它們可能一次都沒執行就結束,沒有值可給。範例:
- fn main() {
- let mut n = 1u32;
- let first_big_power = loop {
- n *= 3;
- if n > 1000 {
- break n;
- }
- };
- println!("{first_big_power}");
- }
輸出:
- 2187
注意
loop { ... }; 結尾的分號屬於 let 陳述式。表達式的觀念見 函式與表達式。while:條件成立就繼續
while 與 while let
while 條件 { ... } 每輪開始前檢查條件,為 false 就停止。條件和 if 一樣必須是 bool。while let 則是「只要值符合模式就繼續」,常搭配 Vec::pop:還有元素就回傳 Some,空了回傳 None,迴圈自然結束。範例:
- fn main() {
- let mut balance = 1000;
- let mut months = 0;
- while balance < 2000 {
- balance += balance / 10;
- months += 1;
- }
- println!("{months} 個月後餘額 {balance}");
- let mut stack = vec![1, 2, 3];
- while let Some(top) = stack.pop() {
- println!("取出 {top}");
- }
- }
輸出:
- 8 個月後餘額 2142
- 取出 3
- 取出 2
- 取出 1
balance / 10 是整數除法,小數會被捨去。while let 等模式語法的更多用法見 模式語法。for:走訪集合與範圍
for 變數 in 可迭代的東西 { ... } 是 Rust 最常用的迴圈。它背後用的是 迭代器,不必自己管索引,也就不會有索引越界的問題。Rust 沒有 C 風格的 for (i = 0; i < n; i++)。走訪陣列與 Vec
三種寫法決定你拿到的是什麼:
| 寫法 | 拿到的元素 | 迴圈後原集合 |
|---|---|---|
for x in v | 值本身(取得所有權) | Vec 被移走,不能再用 |
for x in &v | 唯讀參考 &T | 還能用 |
for x in &mut v | 可變參考 &mut T,用 *x 修改 | 還能用,內容已修改 |
需要索引時用
.iter().enumerate(),會得到 (索引, 元素)。陣列的元素若是 Copy 型別(如下例的 &str),for f in fruits 走訪後陣列仍可使用。所有權與移動的觀念見 所有權。範例:
- fn main() {
- let fruits = ["蘋果", "香蕉", "芭樂"];
- for f in fruits {
- println!("{f}");
- }
- for (i, f) in fruits.iter().enumerate() {
- println!("{i}: {f}");
- }
- let mut scores = vec![60, 75, 90];
- for s in &mut scores {
- *s += 5;
- }
- println!("{:?}", scores);
- }
輸出:
- 蘋果
- 香蕉
- 芭樂
- 0: 蘋果
- 1: 香蕉
- 2: 芭樂
- [65, 80, 95]
範圍 a..b 與 a..=b
要跑固定次數就走訪範圍(range)。
0..3 不含結尾(0、1、2),1..=3 含結尾(1、2、3)。.rev() 反向、.step_by(n) 每次跳 n。範圍本身也是迭代器,可以直接 .sum()。範例:
- fn main() {
- for i in 0..3 {
- print!("{i} ");
- }
- println!();
- for i in 1..=3 {
- print!("{i} ");
- }
- println!();
- for i in (1..=5).rev() {
- print!("{i} ");
- }
- println!();
- for i in (0..20).step_by(5) {
- print!("{i} ");
- }
- println!();
- let total: u32 = (1..=100).sum();
- println!("{total}");
- }
輸出:
- 0 1 2
- 1 2 3
- 5 4 3 2 1
- 0 5 10 15
- 5050
注意:
(5..1) 這種起點大於終點的範圍不會報錯,只是一次都不執行。要倒數請用 (1..5).rev()。step_by(0) 會 panic。走訪時不能修改同一個集合
在
for x in &list 的迴圈裡呼叫 list.push,等於同時持有唯讀借用與可變借用。其他語言可能在執行時拋出「集合在迭代中被修改」的例外,Rust 則在編譯期就擋下。這段無法編譯:- fn main() {
- let mut list = vec![1, 2, 3];
- for x in &list {
- if *x == 2 {
- list.push(4);
- }
- }
- println!("{:?}", list);
- }
輸出:
- error[E0502]: cannot borrow `list` as mutable because it is also borrowed as immutable
- --> main.rs:5:13
- |
- 3 | for x in &list {
- | - -----
- | | |
- | | immutable borrow occurs here
- | _____| immutable borrow later used here
- | |
- 4 | | if *x == 2 {
- 5 | | list.push(4);
- | | ^^^^^^^^^^^^ mutable borrow occurs here
- 6 | | }
- 7 | | }
- | |_____- this for loop borrows `list` immutably, preventing mutation within its body
- |
- = help: consider using an index-based loop instead, or collecting modifications into a separate collection
push 可能讓 Vec 重新配置記憶體,迴圈手上的參考就會指向已釋放的位置,所以編譯器不允許。照 help 的建議,把要新增的東西先收集起來,迴圈結束後再加入。借用規則見 參考與借用。範例:
- fn main() {
- let mut list = vec![1, 2, 3];
- let mut extra = Vec::new();
- for x in &list {
- if *x == 2 {
- extra.push(4);
- }
- }
- list.extend(extra);
- println!("{:?}", list);
- }
輸出:
- [1, 2, 3, 4]
continue 與迴圈標籤
continue 跳過這一輪
continue 結束本輪剩下的程式碼,直接進入下一輪。常用來「不符合條件就跳過」,讓主要邏輯不必縮排在 if 裡。範例:
- fn main() {
- for n in 1..=10 {
- if n % 3 != 0 {
- continue;
- }
- println!("{n} 是 3 的倍數");
- }
- }
輸出:
- 3 是 3 的倍數
- 6 是 3 的倍數
- 9 是 3 的倍數
迴圈標籤:跳出外層迴圈
巢狀迴圈中,
break 和 continue 預設只作用在最內層。在外層迴圈前加上標籤 '名稱:,就能用 break '名稱 或 continue '名稱 指定要作用的迴圈。標籤以單引號開頭,這不是字元字面值。範例:
- fn main() {
- let grid = [[1, 2, 3], [4, -5, 6], [7, 8, 9]];
- let mut found = None;
- 'rows: for (r, row) in grid.iter().enumerate() {
- for (c, &v) in row.iter().enumerate() {
- if v < 0 {
- found = Some((r, c));
- break 'rows;
- }
- }
- }
- println!("{:?}", found);
- 'outer: for i in 1..=3 {
- for j in 1..=3 {
- if j == i {
- continue 'outer;
- }
- print!("({i},{j}) ");
- }
- }
- println!();
- }
輸出:
- Some((1, 1))
- (2,1) (3,1) (3,2)
第一段找到負數就直接結束兩層迴圈;第二段在
j == i 時跳到外層的下一輪,所以每一列只印到對角線之前。帶標籤的區塊
標籤也能加在一般區塊上(Rust 1.65 起),用
break '標籤 值 提早離開區塊並帶出值。它不是迴圈,不會重複,適合「依序檢查幾個條件,符合就提早給出結果」的寫法。區塊內只能用 break,不能用 continue。範例:
- fn classify(text: &str) -> &'static str {
- let kind = 'check: {
- if text.is_empty() {
- break 'check "空白";
- }
- if text.chars().all(|c| c.is_ascii_digit()) {
- break 'check "數字";
- }
- "文字"
- };
- kind
- }
- fn main() {
- println!("{} {} {}", classify(""), classify("2024"), classify("rust"));
- }
輸出:
- 空白 數字 文字
三種迴圈怎麼選
| 情境 | 選擇 |
|---|---|
| 走訪集合、跑固定次數 | for |
| 條件成立就繼續,次數不固定 | while |
| 每次從容器取出直到空 | while let |
| 無限重複、或需要從迴圈帶出值 | loop 搭配 break 值 |
重點整理
loop無限重複,break 值可以讓整個loop產生一個值while每輪前檢查bool條件;while let在值符合模式時持續執行for走訪迭代器:v、&v、&mut v分別取得所有權、唯讀參考、可變參考a..b不含結尾、a..=b含結尾,.rev()反向、.step_by(n)跳著走- 走訪集合時不能修改同一個集合,編譯器以借用規則擋下
- 迴圈標籤
'名稱讓break/continue作用到外層迴圈,也可以標在區塊上提早帶值離開