1. if语句
下面看一个示例:
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}
(1) 需要注意的是,RUST与cpp不同,不可以将整型识别为bool,所以下面的语句会报错:
fn main() {
let number =3;
if number{
println!("condition is true");
}else{
println!("condition is false");
}
}
(2)另一个需要注意的点是,if多个分支返回的值要是同类型
fn main() {
let condition = true;
let number = if condition { 5 } else { "six" };
println!("The value of number is: {number}");
}
因为RUST需要在编译的时候确定number的类型,如果类型无法确定后续对代码的保证会降低
2. 循环
2.1 loop
一个简单的例子:
fn main() {
loop {
println!("again!");
}
}
比较特别的一个点是,允许循环标签来在内循环中断外部循环
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
2.2 while
while
的用法和其他语言类似,同样需要注意表达式的返回值必须为布尔值
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
遍历数组示例:
fn main() {
test1();
}
fn test1(){
let a=[1,2,3,4,5];
let mut index=0;
while index<5{
println!("the value of a[{index}] is {} ",a[index]);
index+=1;
}
}
2.3 for
for的遍历array的写法很类似于cpp中的for(auto ele:array)
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}
一个倒计时的例子
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}
//输出结果 3 2 1
标签:count,控制流,number,while,let,fn,println,main,loop
From: https://www.cnblogs.com/SaltyCheese/p/17302549.html