版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BaiHuaXiu123/article/details/88095153
控制结构
1. if语句
let x = 5;
if x == 5 {
println!("相等")
} else {
println!("不相等")
}
错误写法:
if x {
println!("相等")
}
注意:if 后面的条件表达式只能是逻辑表达式或者bool值。
let x = 5;
if x == 5 {
println!("x is five!");
} else if x == 6 {
println!("x is six!");
} else {
println!("x is not five or six :(");
}
这些都是非常标准的情况。然而你也可以这么写:
let x = 5;
let y = if x == 5 {
10
} else {
15
}; // y: i32
注意:这种写法类似其它语言中的?:表达式
你可以(或许也应该)这么写:
let x = 5;
let y = if x == 5 { 10 } else { 15 }; // y: i32
2. 循环
2.1 loop
无限loop是 Rust 提供的最简单的循环。使用loop关键字,Rust 提供了一个直到一些终止语句被执行的循环方法。Rust 的无限loop看起来像这样:
无限循环:
loop {
println!("Loop forever!");
}
当count计数达到100终止循环:
let mut count = 0;
loop {
count += 1;
println!("Loop forever!");
if count == 50 {
break;
}
}
println!("break!");
2.2 while循环
Rust 也有一个while循环。它看起来像:
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
无限循环
while true {
println!("无限循环");
}
2.3 for语句
for用来循环一个特定的次数。然而,Rust的for循环与其它系统语言有些许不同。Rust的for循环看起来并不像这个“C语言样式”的for循环:
for (x = 0; x < 20; x++) {
printf( "%d\n", x );
}
相反,它看起来像这个样子:
for x in 0..20 {
println!("{}", x); // x: i32
}
Enumerate 方法
当你需要记录你已经循环了多少次了的时候,你可以使用.enumerate()函数。
对于范围(On ranges):
for (index, value) in (5..10).enumerate() {
println!("index = {} and value = {}", index, value);
}
对于迭代器(On iterators):
let lines = "hello\nworld".lines();
for (linenumber, line) in lines.enumerate() {
println!("{}: {}", linenumber, line);
}
结果:
0: hello
1: world
提早结束迭代(Ending iteration early)
let mut x = 5;
let mut done = false;
while !done {
x += x - 3;
println!("{}", x);
if x % 5 == 0 {
done = true;
}
}
2.4 循环标签(Loop labels)
你也许会遇到这样的情形,当你有嵌套的循环而希望指定你的哪一个break或continue该起作用。就像大多数语言,默认break或continue将会作用于最内层的循环。当你想要一个break或continue作用于一个外层循环,你可以使用标签来指定你的break或continue语句作用的循环。如下代码只会在x和y都为奇数时打印他们:
'outer: for x in 0..10 {
'inner: for y in 0..10 {
if x % 2 == 0 { continue 'outer; }
if y % 2 == 0 { continue 'inner; }
println!("x: {}, y: {}", x, y);
}
}
结果
x: 1, y: 1
x: 1, y: 3
x: 1, y: 5
x: 1, y: 7
x: 1, y: 9
x: 3, y: 1
x: 3, y: 3
x: 3, y: 5
x: 3, y: 7
x: 3, y: 9
x: 5, y: 1
x: 5, y: 3
x: 5, y: 5
x: 5, y: 7
x: 5, y: 9
x: 7, y: 1
x: 7, y: 3
x: 7, y: 5
x: 7, y: 7
x: 7, y: 9
x: 9, y: 1
x: 9, y: 3
x: 9, y: 5
x: 9, y: 7
x: 9, y: 9