语法
if ... else if ... else
示例
fn main() {
let x: i32 = 5;
if x > 5{
print!("{}","Hello World!");
}else if x == 5 {
print!("{}","Hello!");
}else{
print!("{}", "Goodbye!");
}
}
fn main() {
let mut x: i32 = 5;
let res: i32 = loop {
x += 1;
if x == 10 {
break x * 2;
}
};
println!("{}", res);
}
fn main() {
let mut x: i32 = 5;
while x < 20 {
x+=1;
print!("{} ", x)
}
}
使用 for 遍历集合是一个安全快速的选择 :
fn main() {
let arr = [1, 2, 3, 4, 5];
for val in arr {
print!("{}", val);
}
}
指定一个开始数字和一个结束数字,Range可以生成它们之间的数字(不含结束),rev 方法可以反转 Range。
fn main() {
for num in (1..6).rev() {
print!("{}", num)
}
}