Rust-05-控制流

Rust提供了多种控制流语句来控制程序的执行流程。

if-else

用于根据条件执行不同的代码块。

rust 复制代码
// if else
let x = 5;
if x > 0 {
    println!("x is positive");
} else {
    println!("x is not positive");
}
// if else if 
if x > 0 {
	x+1; 
} else if x > 10 {
	x-1;
} else {
	x;
}
// 三目运算,运算值的数据类型应该相同
let number = if true { 5 } else { 6 };

match

类似于java的switch

rust 复制代码
let x = 3;
match x {
    1 => println!("x is 1"),
    2 => println!("x is 2"),
    3 => println!("x is 3"),
    _ => println!("x is something else"), // 默认
}

while

用于重复执行一段代码,直到条件不满足为止。

rust 复制代码
    let mut i = 0;
    let array = [1,2,3,4,5,6,7];
    while i < array.len() {
        println!("{}",array[i]);
        i += 1;
    }

for

用于遍历集合或范围,并执行一段代码。

rust 复制代码
for x in 0..5 {
    println!("x is {}", x);
}

loop

用于无限循环,直到显式地跳出循环。

rust 复制代码
loop {
    println!("This is an infinite loop");
    break; // 显式地跳出循环
}

continue

用于跳过当前迭代,进入下一次迭代。

rust 复制代码
for x in 0..5 {
    if x == 2 {
        continue; // 跳过 x = 2 的情况
    }
    println!("x is {}", x);
}

break

用于跳出当前循环或 switch 语句

rust 复制代码
for x in 0..5 {
    if x == 3 {
        break; // 跳出循环,不再执行后续迭代
    }
    println!("x is {}", x);
}
相关推荐
iCxhust1 分钟前
c# U盘映像生成工具
开发语言·单片机·c#
yangzhi_emo40 分钟前
ES6笔记2
开发语言·前端·javascript
emplace_back2 小时前
C# 集合表达式和展开运算符 (..) 详解
开发语言·windows·c#
jz_ddk2 小时前
[学习] C语言数学库函数背后的故事:`double erf(double x)`
c语言·开发语言·学习
萧曵 丶2 小时前
Rust 所有权系统:深入浅出指南
开发语言·后端·rust
xiaolang_8616_wjl2 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
收破烂的小熊猫~2 小时前
《Java修仙传:从凡胎到码帝》第四章:设计模式破万法
java·开发语言·设计模式
nananaij3 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
阿蒙Amon3 小时前
为什么 12 版仍封神?《C# 高级编程》:从.NET 5 到实战架构,进阶者绕不开的必修课
开发语言·c#