From 3a02eebb90e49de90fffde7d648c0b4e553143cb Mon Sep 17 00:00:00 2001 From: mzg <5487654@qq.com> Date: Sun, 21 Aug 2022 10:38:44 +0800 Subject: [PATCH] add control_flow --- .../control_flow.md" | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git "a/data/1.rust\345\210\235\351\230\266/2.rust\345\237\272\346\234\254\346\246\202\345\277\265/10.\346\216\247\345\210\266\346\265\201/control_flow.md" "b/data/1.rust\345\210\235\351\230\266/2.rust\345\237\272\346\234\254\346\246\202\345\277\265/10.\346\216\247\345\210\266\346\265\201/control_flow.md" index 7b96e95..09398ae 100644 --- "a/data/1.rust\345\210\235\351\230\266/2.rust\345\237\272\346\234\254\346\246\202\345\277\265/10.\346\216\247\345\210\266\346\265\201/control_flow.md" +++ "b/data/1.rust\345\210\235\351\230\266/2.rust\345\237\272\346\234\254\346\246\202\345\277\265/10.\346\216\247\345\210\266\346\265\201/control_flow.md" @@ -1,2 +1,135 @@ # 控制流 +Rust 语言的逻辑控制流有: +- if/else 条件分支 +- loop 循环 +- while 循环 +- for in range 循环 +- match 表达式 +- if let +- while let + +代码表示分别为: + +```rust + +if condition_a {} +else if condition_b {} +else {} + +loop {} + +'outer: loop { + 'innter: loop { + ... + break; + // or + break 'outer; + } +} + +loop { + ... + break counter * 2; +} + +while condition_a {} + +for n in 1..=100 {} + +for name in names.iter() {} + +match val { + tuple_a => statement_a ; + tuple_b => statement_b ; + (x, y) if x = y => statement_c ; + (x, y) => statement_d ; + (Enum::A, Enum::B) => statement_e ; + (n @ 1..=50, m @ 51..=100) => statement_f ; + (Some(n), Some(m)) => statement_g ; +} + +if let Some(i) = number {} +while let Some(i) = number {} + +``` + +下列代码能正常运行的是: + +## 答案 + +```rust + +fn main() { + let mut count = 0; + 'outer: loop { + 'inner: loop { + if count >= 20 { + break 'outer; + } + count += 2; + } + } + + println!("Complete!"); +} + +``` + + +## 选项 + +### + +```rust + +fn main() { + let mut count = 0; + 'outer: loop { + 'inner: loop { + if count <= 20 { + count += 2; + goto: 'inner; + } + } + } + + println!("Complete!"); +} + +``` + + +### + +```rust + +fn main() { + for i in 0..=10 { + if i == 10 { + panic!("This never gonna happy"); + } + } +} + +``` + +### + +```rust + +fn main() { + let guess = 51; + let secret_number = 42; + let result = if guess < secret_number { + "Too small" + } else if guess > secret_number { + "Too big" + } else { + 42 + }; + + println!("{}", result); +} + +``` \ No newline at end of file -- GitLab