Rust 流程控制
2025/6/6大约 2 分钟
流程控制
if
if用于判断一个或多个条件是否为真,并执行if块内的操作。
在Rust中,if后的条件必须为bool类型,因为Rust不像Ruby或Javascript语言一样,会自动将bool以外的类型隐式转换为bool类型。
if condition {
// expression
}
else if condition {
// expression
}
else {
// expression
}fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was true在Rust中,if是一个表达式,这也就意味着它可以在let语句中进行使用,if表达式的结果可以赋值给声明的变量。需要注意的是,if表达式的结果必须拥有相同的类型,否则无法通过编译。
fn main() {
let condition = true;
let number = if condition { 1 } else { 2 };
println!("The value of number is {}", number);
}$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/branches`
The value of number is 1loop
loop关键字用于创建一个无条件循环,它会不断被执行,直到你使用break语句跳出该循环。
fn main() {
loop {
println!("again!");
}
}$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!loop的返回值
在break后添加你想要返回的值,即可将loop内的变量作为返回值返回。
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}The result is 20while 循环
bool 条件循环
当conditon为真时进入循环,当condition为假时退出循环。
while condition {
// expression
}while let 模式匹配循环
只要模式匹配就一直运行while循环。
let mut stack = vec![];
stack.push(1);
stack.push(2);
while let Some(value) = stack.pop() {
println!("{}", value);
}for 循环
Rust的for循环与其他编程语言有所不同。在Rust中,for循环使用迭代器对一个集合中的元素进行遍历。
for element in collection {
// expression
}在实际使用中,我们通常使用集合的引用形式。因为在不使用引用的情况下,集合的所有权会被转移到for循环内,后续就无法再使用该集合了。此外,如果我们需要在循环中修改该元素,需要在引用后添加mut关键字。
| 使用方法 | 等价使用方式 | 所有权 |
|---|---|---|
for item in collection | for item in IntoIterator::into_iter(collection) | 转移所有权 |
for item in &collection | for item in collection.iter() | 不可变借用 |
for item in &mut collection | for item in collection.iter_mut() | 可变借用 |
如果我们需要在一段数据范围内进行遍历(类似C语言的for循环),可以使用以下形式。
for i in 1..100 {} // i = 1, 2, 3, ..., 99
for i in 1..=100 {} // i = 1, 2, 3, ..., 100常用的iterater操作
-
rev:将迭代器反向 -
step:指定迭代器步长
