走进 Rust:流程控制
Rust About 1,838 wordsif
if
的条件必须是bool
类型。
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
if number != 0 {
println!("number was something other than zero");
}
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");
}
}
let
表达式中使用if
,if
和else
表达式内的值类型必须一致。
fn main() {
let condition = false;
let number = if condition {
5
} else {
6
};
println!("The value of number is: {}", number);
}
loop
loop
循环的一个作用是当你知道会失败时重试操作,例如检查一个线程是否完成他的任务。loop
中可使用break
关键字跳出循环,还可以返回想要的值以便后面的程序中使用该值。
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
while
while
循环有判断条件,当条件为true
时循环继续执行,当为false
时,循环终止。
fn main() {
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
println!("LIFTOFF!!!");
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the value is: {}", a[index]);
index += 1;
}
}
for
for
循环遍历数组。注意:遍历的是数组的迭代器iter
,不是数组本身。
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is: {}", element);
}
}
使用..
,生成Range
类型。for
循环遍历Range
类型
fn main() {
for number in 1..4 {
println!("asc number={}", number);
}
}
倒叙遍历Range
,使用rev()
函数逆转Range
。
fn main() {
for number in (1..4).rev() {
println!("desc number={}", number);
}
}
Views: 2,876 · Posted: 2020-07-03
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...