这一篇博客来写一下基本的分支和循环,ifelse ifloopwhilefor

if else

1
2
3
4
5
6
7
8
let x = 10;
if x > 100 {
println!("x > 100");
} else if x > 50 {
println!("x > 50");
} else {
println!("x <= 50");
}
1
2
3
4
5
6
7
8
9
// 还可以这样写
fn main() {
let condition = false;
let x = if condition {
5
} else {
6
};
}

loop

1
2
3
4
5
fn main() {
loop {
println!("hello");
}
}
1
2
3
4
5
6
7
8
9
10
11
// 这段代码中,break counter * 100; 这一句是将和跳出循环,并把 counter * 100 返回
fn main() {
let mut counter = 0;
let x = loop {
counter += 1;
if counter == 10 {
break counter * 100;
}
};
println!("x: {}", x);
}

while

1
2
3
4
5
6
7
fn main() {
let mut counter = 10;
while counter >= 0 {
println!("counter: {}", counter);
counter -= 1;
}
}

for

1
2
3
4
5
6
// 这段代码将输出,0 到 9
fn main() {
for i in(0..10) {
println!("x: {}", i);
}
}
1
2
3
4
5
6
7
// 使用 for 循环来遍历集合中的元素
fn main() {
let nums = [0, 1, 2, 10, 11, 20];
for num in nums.iter() {
println!("num: {}", num);
}
}