跳到主要内容
Rust 控制流详解:条件、循环与模式匹配 | 极客日志
Rust 算法
Rust 控制流详解:条件、循环与模式匹配 Rust 控制流机制涵盖条件表达式 if/else 的返回值特性、三种循环结构 loop/while/for 的适用场景及性能考量、强大的 match 模式匹配语法以及 if let/while let 的简洁用法。同时提供代码可读性优化策略和错误处理最佳实践,帮助开发者编写安全高效的 Rust 程序。
1951018925 发布于 2026/3/16 更新于 2026/4/27 3 浏览Rust 控制流详解
4.1 条件表达式 if/else
在 Rust 中,条件表达式是程序决策的基础。与其他语言不同,Rust 的 if 表达式总是返回一个值,这使得它们更加灵活和强大。
4.1.1 基础条件表达式
fn basic_conditionals () {
println! ("=== 基础条件表达式 ===" );
let number = 7 ;
if number < 5 {
println! ("条件为真" );
} else {
println! ("条件为假" );
}
let score = 85 ;
if score >= 90 {
println! ("优秀" );
} else if score >= 80 {
println! ("良好" );
} else if score >= 70 {
println! ("中等" );
} else if score >= 60 {
println! ("及格" );
} else {
println! ("不及格" );
}
let condition = true ;
= condition { } { };
( , result);
= ;
= number % == { } { };
( , number, is_even);
= ;
= ;
= x > y { }
x < y { }
{ };
( , comparison);
= ;
flag {
( );
}
!flag {
( );
}
}
let
result
if
"真分支的值"
else
"假分支的值"
println!
"if 表达式结果:{}"
let
number
6
let
is_even
if
2
0
"偶数"
else
"奇数"
println!
"{} 是 {}"
let
x
10
let
y
20
let
comparison
if
"x 大于 y"
else
if
"x 小于 y"
else
"x 等于 y"
println!
"比较结果:{}"
let
flag
true
if
println!
"标志为真"
if
println!
"标志为假"
fn conditional_operators () {
println! ("\n=== 条件运算符 ===" );
let a = 10 ;
let b = 20 ;
println! ("比较运算:" );
println! (" {} == {}: {}" , a, b, a == b);
println! (" {} != {}: {}" , a, b, a != b);
println! (" {} < {}: {}" , a, b, a < b);
println! (" {} > {}: {}" , a, b, a > b);
println! (" {} <= {}: {}" , a, b, a <= b);
println! (" {} >= {}: {}" , a, b, a >= b);
let has_permission = true ;
let has_credits = false ;
println! ("逻辑运算:" );
println! (" 与运算:{}" , has_permission && has_credits);
println! (" 或运算:{}" , has_permission || has_credits);
println! (" 非运算:{}" , !has_permission);
let age = 25 ;
let has_license = true ;
if age >= 18 && has_license {
println! ("可以驾驶" );
} else {
println! ("不能驾驶" );
}
println! ("\n短路求值演示:" );
fn expensive_check () -> bool {
println! ("执行昂贵检查..." );
true
}
let condition1 = false ;
let condition2 = true ;
if condition1 && expensive_check () {
println! ("条件 1 为真" );
}
if condition2 || expensive_check () {
println! ("条件 2 为真" );
}
let temperature = 25 ;
let is_sunny = true ;
let is_weekend = false ;
let should_go_out = if temperature > 20 && temperature < 30 && is_sunny {
if is_weekend { "绝对要出门!" }
else { "天气很好,但得上班" }
} else { "还是呆在家里吧" };
println! ("出门建议:{}" , should_go_out);
}
fn conditional_with_blocks () {
println! ("\n=== 带代码块的条件表达式 ===" );
let value = 42 ;
let description = if value > 50 {
let temp = value * 2 ;
format! ("大的数:{}" , temp)
} else {
let temp = value / 2 ;
format! ("小的数:{}" , temp)
};
println! ("描述:{}" , description);
let user_role = "admin" ;
let is_authenticated = true ;
let access_level = if is_authenticated {
match user_role {
"admin" => {
println! ("记录管理员访问" );
"full_access"
},
"user" => {
println! ("记录用户访问" );
"limited_access"
},
"guest" => {
println! ("记录访客访问" );
"read_only"
},
_ => "no_access"
}
} else {
"unauthorized"
};
println! ("访问级别:{}" , access_level);
let config_value = Some (100 );
let processed_value = if let Some (value) = config_value {
let result = value * 2 ;
format! ("处理后的值:{}" , result)
} else {
"没有配置值" .to_string ()
};
println! ("处理结果:{}" , processed_value);
}
4.1.2 高级条件表达式模式 fn advanced_conditional_patterns () {
println! ("=== 高级条件表达式模式 ===" );
fn process_user (age: Option <u32 >, has_consent: bool ) -> String {
if age.is_none () {
return "年龄信息缺失" .to_string ();
}
let age = age.unwrap ();
if !has_consent {
return "需要用户同意" .to_string ();
}
if age < 18 {
return "用户未成年" .to_string ();
}
"处理成功" .to_string ()
}
println! ("守卫条件示例:{}" , process_user (Some (20 ), true ));
let mut counter = 0 ;
let max_attempts = 3 ;
while let true = {
counter += 1 ;
counter <= max_attempts
} {
println! ("尝试 {} of {}" , counter, max_attempts);
}
let is_weekday = true ;
let is_holiday = false ;
let has_meeting = true ;
let workload = 75 ;
let should_work_from_home = (is_weekday && !is_holiday) && (has_meeting || workload > 80 );
println! ("应该在家办公:{}" , should_work_from_home);
let config = Some ("production" );
if let Some (env) = config {
println! ("运行在 {} 环境" , env);
}
let point = (5 , 10 );
if let (x, y) = point {
if x > 0 && y > 0 {
println! ("点 ({}, {}) 在第一象限" , x, y);
}
}
fn parse_number (s: &str ) -> Result <i32 , String > {
if s.is_empty () {
return Err ("字符串为空" .to_string ());
}
if !s.chars ().all (|c| c.is_ascii_digit ()) {
return Err ("包含非数字字符" .to_string ());
}
Ok (s.parse ().unwrap ())
}
match parse_number ("123" ) {
Ok (num) => println! ("解析成功:{}" , num),
Err (e) => println! ("解析失败:{}" , e),
}
#[cfg(debug_assertions)]
{
println! ("这是调试构建" );
}
#[cfg(not(debug_assertions))]
{
println! ("这是发布构建" );
}
#[cfg(feature = "logging" )]
{
println! ("日志特性已启用" );
}
}
fn conditional_performance () {
println! ("\n=== 条件表达式性能考虑 ===" );
use std::time::Instant;
fn check_conditions_optimized (value: i32 ) -> bool {
if value < 0 {
return false ;
}
if value > 1000 {
return false ;
}
is_prime (value)
}
fn check_conditions_unoptimized (value: i32 ) -> bool {
if is_prime (value) {
if value < 0 {
return false ;
}
if value > 1000 {
return false ;
}
true
} else {
false
}
}
fn is_prime (n: i32 ) -> bool {
if n <= 1 { return false ; }
if n <= 3 { return true ; }
if n % 2 == 0 || n % 3 == 0 { return false ; }
let mut i = 5 ;
while i * i <= n {
if n % i == 0 || n % (i + 2 ) == 0 { return false ; }
i += 6 ;
}
true
}
let test_value = 97 ;
let start = Instant::now ();
let result1 = check_conditions_optimized (test_value);
let duration1 = start.elapsed ();
let start = Instant::now ();
let result2 = check_conditions_unoptimized (test_value);
let duration2 = start.elapsed ();
println! ("优化版本:{} (耗时:{:?})" , result1, duration1);
println! ("未优化版本:{} (耗时:{:?})" , result2, duration2);
fn validate_input (input: &str ) -> bool {
!input.is_empty () && input.len () <= 100 && input.chars ().all (|c| c.is_ascii_alphanumeric ())
}
println! ("输入验证:'hello' -> {}" , validate_input ("hello" ));
println! ("输入验证:'' -> {}" , validate_input ("" ));
}
4.2 循环:loop、while、for
4.2.1 loop 循环深度解析 loop 循环是 Rust 中最基本的循环结构,它会无限循环直到显式中断。
fn loop_deep_dive () {
println! ("=== loop 循环深度解析 ===" );
let mut counter = 0 ;
loop {
counter += 1 ;
println! ("循环次数:{}" , counter);
if counter >= 5 {
break ;
}
}
let result = loop {
counter += 1 ;
if counter >= 10 {
break counter * 2 ;
}
};
println! ("loop 返回值:{}" , result);
'outer : loop {
println! ("进入外部循环" );
let mut inner_counter = 0 ;
'inner : loop {
inner_counter += 1 ;
println! (" 内部循环:{}" , inner_counter);
if inner_counter >= 3 {
break 'inner ;
}
}
counter += 1 ;
if counter >= 2 {
break 'outer ;
}
}
let mut values = vec! [1 , 2 , 3 , 4 , 5 ].into_iter ();
loop {
match values.next () {
Some (value) => {
println! ("处理值:{}" , value);
if value == 3 {
println! ("找到目标值,继续处理..." );
continue ;
}
},
None => {
println! ("没有更多值" );
break ;
}
}
}
let mut number = 0 ;
loop {
number += 1 ;
if number % 2 == 0 {
continue ;
}
println! ("奇数:{}" , number);
if number >= 9 {
break ;
}
}
complex_loop_control ();
}
fn complex_loop_control () {
println! ("\n=== 复杂循环控制 ===" );
let mut attempts = 0 ;
const MAX_ATTEMPTS: u32 = 3 ;
let result = loop {
attempts += 1 ;
println! ("尝试 {}..." , attempts);
let success = attempts >= 2 ;
if success {
break Ok ("操作成功" );
} else if attempts >= MAX_ATTEMPTS {
break Err ("达到最大尝试次数" );
}
std::thread::sleep (std::time::Duration::from_millis (100 ));
};
match result {
Ok (msg) => println! ("结果:{}" , msg),
Err (err) => println! ("错误:{}" , err),
}
let mut state = LoopState::new ();
loop {
state.iteration += 1 ;
match state.process () {
ProcessResult::Continue => {
println! ("继续迭代 {}" , state.iteration);
},
ProcessResult::Break (reason) => {
println! ("循环结束:{}" , reason);
break ;
},
ProcessResult::Restart => {
println! ("重启循环" );
state = LoopState::new ();
continue ;
}
}
if state.iteration >= 5 {
break ;
}
}
event_based_loop ();
}
#[derive(Debug)]
struct LoopState {
iteration: u32 ,
data: Vec <i32 >,
}
impl LoopState {
fn new () -> Self {
Self {
iteration: 0 ,
data: vec! [1 , 2 , 3 ],
}
}
fn process (&mut self ) -> ProcessResult {
println! ("处理状态:{:?}" , self );
if self .iteration == 2 {
ProcessResult::Restart
} else if self .iteration >= 4 {
ProcessResult::Break ("完成处理" .to_string ())
} else {
ProcessResult::Continue
}
}
}
#[derive(Debug)]
enum ProcessResult {
Continue,
Break (String ),
Restart,
}
fn event_based_loop () {
println! ("\n=== 基于事件的循环 ===" );
use std::collections::VecDeque;
let mut event_queue = VecDeque::from ([
Event::Message ("事件 1" .to_string ()),
Event::Message ("事件 2" .to_string ()),
Event::Error ("错误事件" .to_string ()),
Event::Message ("事件 3" .to_string ()),
Event::Shutdown,
]);
let mut running = true ;
while running && !event_queue.is_empty () {
if let Some (event) = event_queue.pop_front () {
match event {
Event::Message (msg) => {
println! ("处理消息:{}" , msg);
},
Event::Error (err) => {
println! ("处理错误:{}" , err);
},
Event::Shutdown => {
println! ("收到关机信号" );
running = false ;
}
}
}
std::thread::sleep (std::time::Duration::from_millis (50 ));
}
println! ("事件循环结束" );
}
#[derive(Debug)]
enum Event {
Message (String ),
Error (String ),
Shutdown,
}
4.2.2 while 循环深度解析 fn while_loop_deep_dive () {
println! ("=== while 循环深度解析 ===" );
let mut counter = 0 ;
while counter < 5 {
println! ("计数器:{}" , counter);
counter += 1 ;
}
let mut stack = Vec ::new ();
stack.push (1 );
stack.push (2 );
stack.push (3 );
println! ("栈内容:" );
while let Some (top) = stack.pop () {
println! ("弹出:{}" , top);
}
let mut x = 100 ;
while x > 0 {
x /= 2 ;
if x == 0 {
break ;
}
println! ("x = {}" , x);
}
process_user_input_simulation ();
let numbers = [1 , 2 , 3 , 4 , 5 ];
let mut iter = numbers.iter ();
while let Some (&number) = iter.next () {
if number == 3 {
println! ("找到 3,跳过剩余" );
break ;
}
println! ("处理数字:{}" , number);
}
let mut remaining_time = 10 ;
while remaining_time > 0 {
println! ("倒计时:{}秒" , remaining_time);
remaining_time -= 1 ;
std::thread::sleep (std::time::Duration::from_millis (100 ));
}
println! ("时间到!" );
}
fn process_user_input_simulation () {
println! ("\n=== 用户输入处理模拟 ===" );
use std::collections::VecDeque;
let mut input_queue = VecDeque::from ([
"help" .to_string (),
"exit" .to_string (),
"invalid" .to_string (),
"status" .to_string (),
]);
let mut running = true ;
while running && !input_queue.is_empty () {
let input = input_queue.pop_front ().unwrap ();
match input.as_str () {
"help" => {
println! ("显示帮助信息" );
},
"exit" => {
println! ("退出程序" );
running = false ;
},
"status" => {
println! ("显示状态信息" );
},
_ => {
println! ("未知命令:{}" , input);
}
}
}
println! ("输入处理结束" );
}
fn while_with_complex_conditions () {
println! ("\n=== 复杂条件的 while 循环 ===" );
let mut temperature = 20 ;
let mut pressure = 100 ;
let mut iterations = 0 ;
while temperature < 100 && pressure < 200 && iterations < 50 {
temperature += 5 ;
pressure += 10 ;
iterations += 1 ;
println! ("迭代 {}: 温度={}, 压力={}" , iterations, temperature, pressure);
}
let mut state = ProcessingState::Initializing;
let mut data = 0 ;
while !state.is_terminal () {
state = state.next (data);
data += 10 ;
println! ("状态:{:?}, 数据:{}" , state, data);
if data > 100 {
break ;
}
}
let mut number = 0 ;
while number < 20 {
number += 1 ;
if number % 3 == 0 {
continue ;
}
if number == 16 {
println! ("在 16 时提前退出" );
break ;
}
println! ("处理数字:{}" , number);
}
}
#[derive(Debug, PartialEq)]
enum ProcessingState {
Initializing,
Processing,
Finalizing,
Completed,
Error,
}
impl ProcessingState {
fn next (self , data: i32 ) -> Self {
match self {
ProcessingState::Initializing => {
if data >= 10 {
ProcessingState::Processing
} else {
ProcessingState::Initializing
}
},
ProcessingState::Processing => {
if data >= 50 {
ProcessingState::Finalizing
} else if data < 0 {
ProcessingState::Error
} else {
ProcessingState::Processing
}
},
ProcessingState::Finalizing => {
if data >= 80 {
ProcessingState::Completed
} else {
ProcessingState::Finalizing
}
},
ProcessingState::Completed => ProcessingState::Completed,
ProcessingState::Error => ProcessingState::Error,
}
}
fn is_terminal (&self ) -> bool {
matches!(self , ProcessingState::Completed | ProcessingState::Error)
}
}
4.2.3 for 循环深度解析 for 循环是 Rust 中最常用的循环结构,主要用于迭代集合。
fn for_loop_deep_dive () {
println! ("=== for 循环深度解析 ===" );
println! ("范围迭代:" );
for i in 0 ..5 {
println! ("i = {}" , i);
}
println! ("包含范围:" );
for i in 0 ..=5 {
println! ("i = {}" , i);
}
let numbers = [10 , 20 , 30 , 40 , 50 ];
println! ("数组迭代:" );
for number in numbers {
println! ("数字:{}" , number);
}
let names = vec! ["Alice" , "Bob" , "Charlie" ];
println! ("向量迭代:" );
for name in &names {
println! ("名字:{}" , name);
}
println! ("带索引迭代:" );
for (index, name) in names.iter ().enumerate () {
println! ("索引 {}: {}" , index, name);
}
let text = "Hello, 世界!" ;
println! ("字符迭代:" );
for (i, ch) in text.chars ().enumerate () {
println! ("位置 {}: '{}' (U+{:04X})" , i, ch, ch as u32 );
}
println! ("字节迭代:" );
for byte in text.bytes () {
println! ("字节:0x{:02X}" , byte);
}
use std::collections::HashMap;
let mut scores = HashMap::new ();
scores.insert ("Alice" , 100 );
scores.insert ("Bob" , 85 );
scores.insert ("Charlie" , 92 );
println! ("哈希映射迭代:" );
for (name, score) in &scores {
println! ("{}: {}" , name, score);
}
println! ("反向迭代:" );
for i in (0 ..5 ).rev () {
println! ("i = {}" , i);
}
println! ("步长迭代:" );
for i in (0 ..20 ).step_by (3 ) {
println! ("i = {}" , i);
}
println! ("嵌套循环:" );
for i in 0 ..3 {
for j in 0 ..3 {
println! ("({}, {})" , i, j);
}
}
advanced_for_patterns ();
}
fn advanced_for_patterns () {
println! ("\n=== 高级 for 循环模式 ===" );
let numbers = 1 ..=10 ;
println! ("过滤偶数:" );
for even in numbers.filter (|&x| x % 2 == 0 ) {
println! ("偶数:{}" , even);
}
let numbers = 1 ..=5 ;
println! ("数字平方:" );
for square in numbers.map (|x| x * x) {
println! ("平方:{}" , square);
}
let result : Vec <i32 > = (1 ..=10 )
.filter (|&x| x % 2 == 0 )
.map (|x| x * 2 )
.collect ();
println! ("链式操作结果:{:?}" , result);
let pairs = vec! [(1 , "one" ), (2 , "two" ), (3 , "three" )];
println! ("元组解构:" );
for (number, word) in pairs {
println! ("{}: {}" , number, word);
}
#[derive(Debug)]
struct Point {
x: i32 ,
y: i32 ,
}
let points = vec! [
Point { x: 0 , y: 0 },
Point { x: 1 , y: 2 },
Point { x: 3 , y: 4 },
];
println! ("结构体迭代:" );
for point in points {
println! ("点:({}, {})" , point.x, point.y);
}
let numbers = 1 ..=10 ;
println! ("跳过前 3 个:" );
for num in numbers.skip (3 ) {
println! ("数字:{}" , num);
}
let numbers = 1 ..=100 ;
println! ("前 5 个元素:" );
for num in numbers.take (5 ) {
println! ("数字:{}" , num);
}
println! ("循环控制:" );
for i in 1 ..=10 {
if i == 3 {
continue ;
}
if i == 8 {
break ;
}
println! ("i = {}" , i);
}
'outer : for i in 1 ..=3 {
'inner : for j in 1 ..=3 {
if i * j > 4 {
println! ("跳过外部循环的剩余部分" );
continue 'outer ;
}
println! ("({}, {})" , i, j);
}
}
let large_vec : Vec <i32 > = (0 ..1000 ).collect ();
let mut sum1 = 0 ;
for &num in &large_vec {
sum1 += num;
}
let mut sum2 = 0 ;
for i in 0 ..large_vec.len () {
sum2 += large_vec[i];
}
println! ("求和结果:{} = {}" , sum1, sum2);
}
fn for_loop_with_custom_iterators () {
println! ("\n=== 自定义迭代器的 for 循环 ===" );
struct StepRange {
start: i32 ,
end: i32 ,
step: i32 ,
}
impl Iterator for StepRange {
type Item = i32 ;
fn next (&mut self ) -> Option <Self ::Item> {
if self .start < self .end {
let current = self .start;
self .start += self .step;
Some (current)
} else {
None
}
}
}
println! ("自定义步长迭代器:" );
for i in StepRange { start: 0 , end: 10 , step: 2 } {
println! ("i = {}" , i);
}
struct Fibonacci {
current: u64 ,
next: u64 ,
}
impl Fibonacci {
fn new () -> Self {
Fibonacci { current: 0 , next: 1 }
}
}
impl Iterator for Fibonacci {
type Item = u64 ;
fn next (&mut self ) -> Option <Self ::Item> {
let new_next = self .current.checked_add (self .next)?;
let result = self .current;
self .current = self .next;
self .next = new_next;
Some (result)
}
}
println! ("斐波那契数列:" );
for (i, fib) in Fibonacci::new ().enumerate ().take (10 ) {
println! ("F({}) = {}" , i, fib);
}
file_line_iteration_simulation ();
}
fn file_line_iteration_simulation () {
println! ("\n=== 文件行迭代模拟 ===" );
let file_content = "第一行\n第二行\n第三行\n第四行" ;
let lines = file_content.lines ();
println! ("文件内容:" );
for (line_num, line) in lines.enumerate () {
println! ("行 {}: {}" , line_num + 1 , line);
}
let log_content = "INFO: 系统启动\nERROR: 磁盘空间不足\nINFO: 用户登录\nWARN: 内存使用率高" ;
println! ("错误日志:" );
for line in log_content.lines ().filter (|l| l.contains ("ERROR" )) {
println! ("错误:{}" , line);
}
}
4.3 模式匹配与 match 表达式
4.3.1 match 表达式基础 match 是 Rust 中最强大的控制流工具之一,提供全面的模式匹配能力。
fn match_expression_basics () {
println! ("=== match 表达式基础 ===" );
let number = 13 ;
match number {
1 => println! ("一" ),
2 | 3 | 5 | 7 | 11 => println! ("质数" ),
13 ..=19 => println! ("青少年数字" ),
_ => println! ("其他数字" ),
}
let number = 5 ;
let description = match number {
1 => "一" ,
2 => "二" ,
3 => "三" ,
_ => "很多" ,
};
println! ("数字 {} 是 {}" , number, description);
let flag = true ;
match flag {
true => println! ("真" ),
false => println! ("假" ),
}
let grade = 'A' ;
match grade {
'A' | 'B' | 'C' => println! ("及格" ),
'D' => println! ("勉强及格" ),
'F' => println! ("不及格" ),
_ => println! ("无效成绩" ),
}
let language = "Rust" ;
match language {
"Rust" => println! ("系统编程语言" ),
"Python" => println! ("脚本语言" ),
"Java" => println! ("企业级语言" ),
_ => println! ("其他语言" ),
}
let boolean = true ;
match boolean {
true => println! ("真" ),
false => println! ("假" ),
}
let value = 42 ;
match value {
1 => println! ("一" ),
2 => println! ("二" ),
_ => (),
}
let age = 25 ;
match age {
0 ..=12 => println! ("儿童" ),
13 ..=19 => println! ("青少年" ),
20 ..=64 => println! ("成人" ),
_ => println! ("长者" ),
}
}
fn match_with_patterns () {
println! ("\n=== 模式匹配 ===" );
let point = (0 , 5 );
match point {
(0 , 0 ) => println! ("在原点" ),
(0 , y) => println! ("在 Y 轴上,y = {}" , y),
(x, 0 ) => println! ("在 X 轴上,x = {}" , x),
(x, y) => println! ("在点 ({}, {})" , x, y),
}
struct Point {
x: i32 ,
y: i32 ,
}
let point = Point { x: 10 , y: 20 };
match point {
Point { x: 0 , y: 0 } => println! ("在原点" ),
Point { x, y: 0 } => println! ("在 X 轴上,x = {}" , x),
Point { x: 0 , y } => println! ("在 Y 轴上,y = {}" , y),
Point { x, y } => println! ("在点 ({}, {})" , x, y),
}
enum Message {
Quit,
Move { x: i32 , y: i32 },
Write (String ),
ChangeColor (i32 , i32 , i32 ),
}
let msg = Message::Move { x: 10 , y: 20 };
match msg {
Message::Quit => println! ("退出" ),
Message::Move { x, y } => println! ("移动到 ({}, {})" , x, y),
Message::Write (text) => println! ("文本消息:{}" , text),
Message::ChangeColor (r, g, b) => println! ("颜色改变为 ({}, {}, {})" , r, g, b),
}
let reference = &4 ;
match reference {
&val => println! ("解引用得到:{}" , val),
}
let arr = [1 , 2 , 3 ];
match arr {
[1 , _, _] => println! ("以 1 开头" ),
[a, b, c] => println! ("数组:{}, {}, {}" , a, b, c),
}
let pair = (2 , -2 );
match pair {
(x, y) if x == y => println! ("相等" ),
(x, y) if x + y == 0 => println! ("相加为零" ),
(x, _) if x % 2 == 0 => println! ("第一个是偶数" ),
_ => println! ("不匹配" ),
}
let number = 5 ;
match number {
n @ 1 ..=10 => println! ("数字 {} 在 1-10 之间" , n),
n @ 11 ..=20 => println! ("数字 {} 在 11-20 之间" , n),
n => println! ("数字 {} 不在范围内" , n),
}
}
fn advanced_match_patterns () {
println! ("\n=== 高级模式匹配 ===" );
enum Color {
Rgb (u8 , u8 , u8 ),
Hsv (u8 , u8 , u8 ),
}
enum Message {
ChangeColor (Color),
}
let msg = Message::ChangeColor (Color::Rgb (255 , 0 , 0 ));
match msg {
Message::ChangeColor (Color::Rgb (r, g, b)) => {
println! ("改变 RGB 颜色为 ({}, {}, {})" , r, g, b);
},
Message::ChangeColor (Color::Hsv (h, s, v)) => {
println! ("改变 HSV 颜色为 ({}, {}, {})" , h, s, v);
},
}
let some_value = Some (5 );
let none_value : Option <i32 > = None ;
match some_value {
Some (x) => println! ("有值:{}" , x),
None => println! ("无值" ),
}
match none_value {
Some (x) => println! ("有值:{}" , x),
None => println! ("无值" ),
}
fn divide (a: f64 , b: f64 ) -> Result <f64 , String > {
if b == 0.0 {
Err ("除数不能为零" .to_string ())
} else {
Ok (a / b)
}
}
match divide (10.0 , 2.0 ) {
Ok (result) => println! ("结果:{}" , result),
Err (error) => println! ("错误:{}" , error),
}
fn complex_operation () -> Result <i32 , Box <dyn std::error::Error>> {
Ok (42 )
}
match complex_operation () {
Ok (value) => println! ("操作成功:{}" , value),
Err (e) => {
if let Some (io_error) = e.downcast_ref::<std::io::Error>() {
println! ("IO 错误:{}" , io_error);
} else if let Some (parse_error) = e.downcast_ref::<std::num::ParseIntError>() {
println! ("解析错误:{}" , parse_error);
} else {
println! ("未知错误:{}" , e);
}
}
}
let name = String ::from ("Alice" );
match name {
ref ref_name => println! ("名字是:{}" , ref_name),
}
println! ("名字仍然可用:{}" , name);
let person = Person { name: String ::from ("Bob" ), age: 30 };
match person {
Person { name, age } => {
println! ("{} 今年 {} 岁" , name, age);
}
}
let triple = (1 , 2 , 3 );
match triple {
(1 , _, third) => println! ("第一个是 1,第三个是 {}" , third),
_ => println! ("其他情况" ),
}
}
#[derive(Debug)]
struct Person {
name: String ,
age: u32 ,
}
4.3.2 if let 和 while let if let 和 while let 提供了模式匹配的简洁语法。
fn if_let_while_let_patterns () {
println! ("=== if let 和 while let 模式 ===" );
let some_value = Some (5 );
match some_value {
Some (x) => println! ("值为:{}" , x),
None => (),
}
if let Some (x) = some_value {
println! ("值为:{}" , x);
}
let none_value : Option <i32 > = None ;
if let Some (x) = none_value {
println! ("有值:{}" , x);
} else {
println! ("没有值" );
}
let some_number = Some (10 );
if let Some (x) = some_number {
if x > 5 {
println! ("值 {} 大于 5" , x);
}
}
if let Some (x) = some_number && x > 5 {
println! ("值 {} 大于 5" , x);
}
enum Event {
Click { x: i32 , y: i32 },
KeyPress (char ),
}
let event = Event::Click { x: 100 , y: 200 };
if let Event ::Click { x, y } = event {
println! ("点击位置:({}, {})" , x, y);
}
let mut stack = Vec ::new ();
stack.push (1 );
stack.push (2 );
stack.push (3 );
println! ("使用 while let 弹出栈:" );
while let Some (top) = stack.pop () {
println! ("弹出:{}" , top);
}
let numbers = vec! [1 , 2 , 3 , 4 , 5 ];
let mut iter = numbers.iter ();
println! ("使用 while let 迭代:" );
while let Some (&number) = iter.next () {
println! ("数字:{}" , number);
}
let mut optional = Some (0 );
while let Some (i) = optional {
if i > 9 {
println! ("大于 9,退出" );
optional = None ;
} else {
println! ("`i` 是 `{:?}`,继续" , i);
optional = Some (i + 1 );
}
}
let config_max = Some (3u8 );
let max_value = if let Some (max) = config_max { max } else { 0u8 };
println! ("最大值:{}" , max_value);
let result : Result <i32 , &str > = Ok (42 );
if let Ok (value) = result {
println! ("成功:{}" , value);
}
if let Err (error) = result {
println! ("错误:{}" , error);
}
practical_if_let_examples ();
}
fn practical_if_let_examples () {
println! ("\n=== if let 实际应用示例 ===" );
struct Config {
timeout: Option <u32 >,
retries: Option <u32 >,
}
let config = Config { timeout: Some (30 ), retries: None };
if let Some (timeout) = config.timeout {
println! ("超时设置:{}秒" , timeout);
} else {
println! ("使用默认超时" );
}
let user_input = "42" ;
if let Ok (number) = user_input.parse::<i32 >() {
println! ("解析的数字:{}" , number);
} else {
println! ("无效的数字" );
}
let mut values = vec! [Some (1 ), None , Some (3 )];
while let Some (Some (value)) = values.pop () {
println! ("处理值:{}" , value);
}
let nested_option = Some (Some (42 ));
if let Some (Some (value)) = nested_option {
println! ("嵌套值:{}" , value);
}
let numbers = vec! [1 , 3 , 5 , 8 , 10 ];
for number in numbers {
if let n @ 1 ..=5 = number && n % 2 == 1 {
println! ("{} 是 1-5 之间的奇数" , n);
}
}
}
fn match_vs_if_let () {
println! ("\n=== match 与 if let 的比较 ===" );
let option_value = Some (42 );
println! ("使用 match:" );
match option_value {
Some (x) => println! ("值为:{}" , x),
None => println! ("没有值" ),
}
println! ("使用 if let:" );
if let Some (x) = option_value {
println! ("值为:{}" , x);
} else {
println! ("没有值" );
}
let result : Result <i32 , &str > = Ok (100 );
if let Ok (value) = result {
println! ("成功:{}" , value);
}
match result {
Ok (value) => println! ("成功:{}" , value),
Err (_) => {},
}
enum ComplexEnum {
A (i32 ),
B (String ),
C { x: i32 , y: i32 },
}
let value = ComplexEnum::C { x: 10 , y: 20 };
match value {
ComplexEnum::A (n) => println! ("A: {}" , n),
ComplexEnum::B (s) => println! ("B: {}" , s),
ComplexEnum::C { x, y } => println! ("C: ({}, {})" , x, y),
}
if let ComplexEnum ::C { x, y } = value {
println! ("只关心 C: ({}, {})" , x, y);
}
performance_considerations ();
}
fn performance_considerations () {
println! ("\n=== 性能考虑 ===" );
let value = Some (42 );
match value {
Some (x) => println! ("有值:{}" , x),
None => println! ("无值" ),
}
if let Some (x) = value {
println! ("有值:{}" , x);
}
let complex_value = (Some (1 ), Some ("hello" ));
match complex_value {
(Some (a), Some (b)) => println! ("都有值:{}, {}" , a, b),
_ => println! ("其他情况" ),
}
if let (Some (a), Some (b)) = complex_value {
println! ("都有值:{}, {}" , a, b);
}
println! ("选择建议:" );
println! (" - 需要处理所有情况:使用 match" );
println! (" - 只关心一种情况:使用 if let" );
println! (" - 循环中的模式匹配:使用 while let" );
println! (" - 需要守卫条件:match 更灵活" );
}
4.4 控制流最佳实践
4.4.1 代码可读性与维护性 fn readability_best_practices () {
println! ("=== 代码可读性最佳实践 ===" );
let user_age = 25 ;
let has_driving_license = true ;
if user_age >= 18 && has_driving_license {
println! ("可以驾驶" );
}
let a = 25 ;
let b = true ;
if a >= 18 && b {
println! ("可以驾驶" );
}
complex_nested_logic ();
refactored_complex_logic ();
fn process_user_data (name: Option <&str >, age: Option <u32 >) -> Result <String , String > {
let name = name.ok_or ("姓名缺失" )?;
let age = age.ok_or ("年龄缺失" )?;
if name.is_empty () {
return Err ("姓名为空" .to_string ());
}
if age < 18 {
return Err ("用户未成年" .to_string ());
}
Ok (format! ("用户 {} 年龄 {}" , name, age))
}
let temperature = 25 ;
let is_weekend = true ;
let has_plans = false ;
if temperature > 20 && temperature < 30 && is_weekend && !has_plans {
println! ("好天气,没安排,出门吧!" );
}
let good_weather = temperature > 20 && temperature < 30 ;
let free_time = is_weekend && !has_plans;
if good_weather && free_time {
println! ("好天气,没安排,出门吧!" );
}
enum TrafficLight {
Red,
Yellow,
Green,
}
let light = TrafficLight::Red;
match light {
TrafficLight::Red => println! ("停止" ),
TrafficLight::Yellow => println! ("准备" ),
TrafficLight::Green => println! ("通行" ),
}
let score = 85 ;
let grade = match score {
90 ..=100 => "优秀" ,
80 ..=89 => "良好" ,
70 ..=79 => "中等" ,
60 ..=69 => "及格" ,
_ => "不及格" ,
};
println! ("成绩等级:{}" , grade);
}
fn complex_nested_logic () {
println! ("\n=== 复杂嵌套逻辑(反面教材) ===" );
let user_role = "admin" ;
let is_authenticated = true ;
let has_permission = true ;
let resource_available = true ;
if is_authenticated {
if user_role == "admin" {
if has_permission {
if resource_available {
println! ("操作成功" );
} else {
println! ("资源不可用" );
}
} else {
println! ("权限不足" );
}
} else {
println! ("角色不符" );
}
} else {
println! ("未认证" );
}
}
fn refactored_complex_logic () {
println! ("\n=== 重构后的逻辑 ===" );
let user_role = "admin" ;
let is_authenticated = true ;
let has_permission = true ;
let resource_available = true ;
if !is_authenticated {
println! ("未认证" );
return ;
}
if user_role != "admin" {
println! ("角色不符" );
return ;
}
if !has_permission {
println! ("权限不足" );
return ;
}
if !resource_available {
println! ("资源不可用" );
return ;
}
println! ("操作成功" );
}
4.4.2 错误处理模式 fn error_handling_patterns () {
println! ("=== 错误处理模式 ===" );
fn parse_number (s: &str ) -> Result <i32 , String > {
s.parse ().map_err (|_| "解析失败" .to_string ())
}
let input = "42" ;
match parse_number (input) {
Ok (number) => println! ("解析成功:{}" , number),
Err (error) => println! ("解析失败:{}" , error),
}
fn process_data (data: &str ) -> Result <i32 , String > {
let num1 = parse_number (data)?;
let num2 = parse_number ("100" )?;
Ok (num1 + num2)
}
fn comprehensive_data_processing (input: &str ) -> Result <String , String > {
let number = input.parse::<i32 >().map_err (|_| "数字解析失败" .to_string ())?;
if number < 0 {
return Err ("数字不能为负" .to_string ());
}
if number > 1000 {
return Err ("数字太大" .to_string ());
}
Ok (format! ("处理后的数字:{}" , number * 2 ))
}
let result = comprehensive_data_processing ("5000" );
if let Err (error) = &result {
if error == "数字太大" {
println! ("数字超出范围,但可以继续处理" );
}
}
fn convert_errors () -> Result <(), String > {
let input = "not_a_number" ;
let _number : i32 = input.parse ().map_err (|e| format! ("解析错误:{}" , e))?;
Ok (())
}
fn find_user (name: &str ) -> Option <&str > {
if name == "admin" {
Some ("管理员用户" )
} else {
None
}
}
let user = find_user ("admin" );
match user {
Some (user_info) => println! ("找到用户:{}" , user_info),
None => println! ("用户不存在" ),
}
let user = find_user ("guest" ).unwrap_or ("默认用户" );
println! ("用户:{}" , user);
fn complex_operation () -> Result <i32 , String > {
Ok (42 )
}
let final_result = complex_operation ()
.and_then (|x| Ok (x * 2 ))
.and_then (|x| if x > 50 { Ok (x) } else { Err ("值太小" .to_string ()) });
match final_result {
Ok (value) => println! ("最终结果:{}" , value),
Err (error) => println! ("处理失败:{}" , error),
}
}
fn performance_optimization () {
println! ("\n=== 性能优化 ===" );
let large_vector : Vec <i32 > = (0 ..1_000_000 ).collect ();
let sum : i32 = large_vector.iter ().sum ();
println! ("迭代器求和:{}" , sum);
let sum = large_vector.iter ().fold (0 , |acc, &x| acc + x);
println! ("fold 求和:{}" , sum);
let mut results = Vec ::with_capacity (1000 );
for i in 0 ..1000 {
results.push (i * 2 );
}
let fixed_data = [1 , 2 , 3 , 4 , 5 ];
let value = Some (42 );
match value {
Some (x) => println! ("有值:{}" , x),
None => println! ("无值" ),
}
let number = 5 ;
match number {
1 => println! ("一" ),
2 => println! ("二" ),
3 => println! ("三" ),
4 => println! ("四" ),
5 => println! ("五" ),
_ => println! ("其他" ),
}
let name = String ::from ("Alice" );
process_name (&name);
println! ("名字仍然可用:{}" , name);
}
fn process_name (name: &str ) {
println! ("处理名字:{}" , name);
}
fn idiomatic_rust_patterns () {
println! ("\n=== Rust 惯用模式 ===" );
let numbers = vec! [1 , 2 , 3 , 4 , 5 ];
let doubled : Vec <i32 > = numbers.iter ().map (|&x| x * 2 ).collect ();
println! ("加倍后:{:?}" , doubled);
let maybe_value = Some (42 );
if let Some (value) = maybe_value {
println! ("有值:{}" , value);
}
fn read_file () -> Result <String , std::io::Error> {
Ok ("文件内容" .to_string ())
}
fn process_file () -> Result <(), Box <dyn std::error::Error>> {
let content = read_file ()?;
println! ("文件内容:{}" , content);
Ok (())
}
enum ConnectionState {
Disconnected,
Connecting,
Connected,
Error (String ),
}
let state = ConnectionState::Connected;
match state {
ConnectionState::Disconnected => println! ("断开连接" ),
ConnectionState::Connecting => println! ("连接中" ),
ConnectionState::Connected => println! ("已连接" ),
ConnectionState::Error (msg) => println! ("连接错误:{}" , msg),
}
struct Config {
host: String ,
port: u16 ,
timeout: u32 ,
}
let base_config = Config {
host: "localhost" .to_string (),
port: 8080 ,
timeout: 30 ,
};
let new_config = Config {
host: "127.0.0.1" .to_string (),
..base_config
};
trait Drawable {
fn draw (&self );
}
struct Circle ;
struct Square ;
impl Drawable for Circle {
fn draw (&self ) {
println! ("绘制圆形" );
}
}
impl Drawable for Square {
fn draw (&self ) {
println! ("绘制方形" );
}
}
let shapes : Vec <Box <dyn Drawable>> = vec! [Box ::new (Circle), Box ::new (Square)];
for shape in shapes {
shape.draw ();
}
}
fn control_flow_in_real_world () {
println! ("\n=== 实际项目中的控制流 ===" );
web_request_handling_simulation ();
data_processing_pipeline ();
state_machine_implementation ();
}
fn web_request_handling_simulation () {
println! ("\n=== Web 请求处理模拟 ===" );
enum HttpMethod {
GET,
POST,
PUT,
DELETE,
}
struct HttpRequest {
method: HttpMethod,
path: String ,
headers: Vec <(String , String )>,
body: Option <String >,
}
fn handle_request (request: HttpRequest) -> Result <String , String > {
if request.path.is_empty () {
return Err ("路径不能为空" .to_string ());
}
match (request.method, request.path.as_str ()) {
(HttpMethod::GET, "/api/users" ) => {
Ok ("用户列表" .to_string ())
},
(HttpMethod::POST, "/api/users" ) => {
if let Some (body) = request.body {
Ok (format! ("创建用户:{}" , body))
} else {
Err ("请求体为空" .to_string ())
}
},
(HttpMethod::GET, path) if path.starts_with ("/api/users/" ) => {
let user_id = &path["/api/users/" .len ()..];
Ok (format! ("用户详情:{}" , user_id))
},
_ => {
Err ("未找到路由" .to_string ())
}
}
}
let request = HttpRequest {
method: HttpMethod::GET,
path: "/api/users" .to_string (),
headers: vec! [],
body: None ,
};
match handle_request (request) {
Ok (response) => println! ("响应:{}" , response),
Err (error) => println! ("错误:{}" , error),
}
}
fn data_processing_pipeline () {
println! ("\n=== 数据处理管道 ===" );
#[derive(Debug)]
struct DataPoint {
value: f64 ,
timestamp: u64 ,
quality: Quality,
}
#[derive(Debug)]
enum Quality {
Good,
Bad,
Unknown,
}
fn process_data_stream (data: Vec <DataPoint>) -> Vec <DataPoint> {
data.into_iter ()
.filter (|point| matches!(point.quality, Quality::Good))
.filter (|point| point.value >= 0.0 && point.value <= 100.0 )
.map (|mut point| {
point.value = (point.value * 100.0 ).round () / 100.0 ;
point
})
.collect ()
}
let raw_data = vec! [
DataPoint { value: 23.456 , timestamp: 1000 , quality: Quality::Good },
DataPoint { value: -5.0 , timestamp: 1001 , quality: Quality::Good },
DataPoint { value: 150.0 , timestamp: 1002 , quality: Quality::Good },
DataPoint { value: 45.678 , timestamp: 1003 , quality: Quality::Bad },
];
let processed_data = process_data_stream (raw_data);
println! ("处理后的数据:{:?}" , processed_data);
}
fn state_machine_implementation () {
println! ("\n=== 状态机实现 ===" );
#[derive(Debug, Clone, Copy)]
enum VendingMachineState {
WaitingForPayment,
SelectingProduct,
DispensingProduct,
OutOfOrder,
}
struct VendingMachine {
state: VendingMachineState,
balance: u32 ,
selected_product: Option <u32 >,
}
impl VendingMachine {
fn new () -> Self {
Self {
state: VendingMachineState::WaitingForPayment,
balance: 0 ,
selected_product: None ,
}
}
fn insert_coin (&mut self , amount: u32 ) -> Result <(), String > {
match self .state {
VendingMachineState::WaitingForPayment => {
self .balance += amount;
if self .balance >= 100 {
self .state = VendingMachineState::SelectingProduct;
}
Ok (())
},
_ => Err ("无法投币,机器状态不正确" .to_string ()),
}
}
fn select_product (&mut self , product_id: u32 ) -> Result <(), String > {
match self .state {
VendingMachineState::SelectingProduct => {
self .selected_product = Some (product_id);
self .state = VendingMachineState::DispensingProduct;
Ok (())
},
_ => Err ("无法选择商品,机器状态不正确" .to_string ()),
}
}
fn dispense (&mut self ) -> Result <String , String > {
match self .state {
VendingMachineState::DispensingProduct => {
if let Some (product_id) = self .selected_product {
self .balance = 0 ;
self .selected_product = None ;
self .state = VendingMachineState::WaitingForPayment;
Ok (format! ("分发商品 {}" , product_id))
} else {
Err ("没有选中的商品" .to_string ())
}
},
_ => Err ("无法分发商品,机器状态不正确" .to_string ()),
}
}
}
let mut machine = VendingMachine::new ();
println! ("正常购买流程:" );
if let Err (e) = machine.insert_coin (50 ) {
println! ("错误:{}" , e);
}
if let Err (e) = machine.insert_coin (50 ) {
println! ("错误:{}" , e);
}
if let Err (e) = machine.select_product (1 ) {
println! ("错误:{}" , e);
}
match machine.dispense () {
Ok (msg) => println! ("成功:{}" , msg),
Err (e) => println! ("错误:{}" , e),
}
println! ("\n错误流程:" );
match machine.select_product (2 ) {
Ok (_) => println! ("选择成功" ),
Err (e) => println! ("错误:{}" , e),
}
}
通过本章的全面学习,你已经深入掌握了 Rust 的控制流系统。从基础的条件表达式到复杂的模式匹配,从简单的循环到高级的迭代器模式,你现在应该能够编写出既安全又高效的 Rust 控制流代码。
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
Gemini 图片去水印 基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
Markdown转HTML 将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
HTML转Markdown 将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online