[翻译完成][tech]: 20230501.1 ️ Rust Basics Series 6 Conditional Statements

This commit is contained in:
Cubik 2023-06-06 14:06:47 -04:00
parent cf0eadeba6
commit 70d0365d15
No known key found for this signature in database
GPG Key ID: 163F16CA3A3795DD

View File

@ -7,59 +7,59 @@
[#]: publisher: " "
[#]: url: " "
Rust Basics Series #6: Conditional Statements
Rust 基础系列 #6: 条件语句
======
In the [previous article][1] in this series, you looked at Functions. In this article, let's look at managing the control flow of our Rust program using conditional statements.
在 [上一篇文章][1] 中,你学习了函数。在这篇文章中,我们将学习使用条件语句来管理 Rust 程序的控制流。
### What are conditional statements?
### 什么是条件语句?
When writing some code, one of the most common tasks is to perform a check for certain conditions to be `true` or `false`. "If the temperature is higher than 35°C, turn on the air conditioner."
在编写代码的时候,最常见的任务之一就是检查某些条件是否为 `true``false`。"如果温度高于 35°C打开空调。"
By using keywords like `if` and `else` (sometimes in combination), a programmer can change what the program does based on conditions like the number of arguments provided, the options passed from the command line, the names of files, error occurrence, etc.
通过使用 `if``else` 这样的关键字(有时候结合使用),程序员可以根据条件(例如提供的参数数量、从命令行传递的选项、文件名、错误发生等)改变程序的行为。
So it is critical for a programmer to know control flow in any language, let alone in Rust.
所以,对一个程序员来说,了解任何语言的控制流都是至关重要的,更不用说 Rust 了。
#### Conditional operators
#### 条件运算符
The following table shows all the frequently used operators for an individual condition:
下表列出了所有常用的单个条件运算符:
| Operator | Example | Interpretation |
| 运算符 | 示例 | 解释 |
| :- | :- | :- |
| `>` | `a > b` | `a` is **greater** than `b` |
| `<` | `a < b` | `a` is **less** than `b` |
| `==` | `a == b` | `a` is **equal** to `b` |
| `!=` | `a != b` | `a` is **not equal** to `b` |
| `>=` | `a >= b` | `a` is **greater than** OR **equal** to `b` |
| `<=` | `a <= b` | `a` is **less than** OR **equal** to `b` |
| `>` | `a > b` | `a` **大于** `b` |
| `<` | `a < b` | `a` **小于** `b` |
| `==` | `a == b` | `a` **等于** `b` |
| `!=` | `a != b` | `a` **不等于** `b` |
| `>=` | `a >= b` | `a` **大于****等于** `b` |
| `<=` | `a <= b` | `a` **小于****等于** `b` |
And following is the table for logical operators, they are used between one or more conditions:
以及下表是逻辑运算符,它们用于一个或多个条件之间:
| Operator | Example | Interpretation |
| 运算符 | 示例 | 解释 |
| :- | :- | :- |
| `||` (Logical OR) | `COND1 || COND2` | At least one of the condition `COND1` or `COND2` evaluates to `true` |
| `&&` (Logical AND) | `COND1 && COND2` | **All** conditions evaluate to `true` |
| `!` (Logical NOT) | `!COND` | Opposite boolean value of what `COND` evaluates to |
| `||` (逻辑或) | `条件1 || 条件2` | `条件1``条件2` 中至少有一个为 `true` |
| `&&` (逻辑与) | `条件1 && 条件2` | **所有** 条件都为 `true` |
| `!` (逻辑非) | `!条件` | `条件` 的布尔值的相反值 |
> 📋 Like in Mathematics, you can use parentheses (round brackets) to specify the precedence of an operation compared to others.
> 📋 与数学相似,你可以使用圆括号来指定操作的优先级。
### Using if else
### 使用 if else
To handle the basic flow of Rust code, two keywords are used: `if` and `else`. This helps you create two "execution paths" based on the state of the provided condition.
要控制 Rust 代码的基本流程,使用两个关键字:`if` 和 `else`。这可以根据提供的条件的状态创建两个“执行路径”。
The syntax of a simple if block with an alternative execution path is as follows:
一个简单的带有替代执行路径的 if 块的语法如下:
```
if condition {
<statement(s)>;
if 条件 {
<语句>;
} else {
<statement(s)>;
<语句>;
}
```
> 📋 When only one condition is provided, enclosing it in round brackets is not compulsory. The use of round brackets is optional, according to the syntax. You should still use them to specify precedence and for better readability.
> 📋 当只有一个条件时,将其括在圆括号中并不是强制性的。根据语法,使用圆括号是可选的。你仍然应该使用它们来指定优先级并优化可读性。
Let's look at an example.
来看看一个例子。
```
fn main() {
@ -67,54 +67,54 @@ fn main() {
let b = 25;
if a > b {
println!("a is greater than b");
println!("a 大于 b");
} else {
println!("b is greater than a");
println!("b 大于 a");
}
}
```
Here, I have declared two integer variables `a` and `b` with the values '36' and '25'. On line 5, I check if the value stored in variable `a` is greater than the value stored in variable `b`. If the condition evaluates to `true`, the code on line 6 will be executed. If the condition evaluates to `false`, due to the fact that we have an `else` block (which is optional), the code on line 8 will get executed.
这里,我声明了两个整数变量 `a``b`,它们的值分别为 '36' 和 '25'。在第 5 行,我检查变量 `a` 中存储的值是否大于变量 `b` 中存储的值。如果条件计算结果为 `true`,则会执行第 6 行的代码。如果条件计算结果为 `false`,由于我们有一个 `else` 块(可选),第 8 行的代码将被执行。
Let's verify this by looking at the program output.
来看看程序的输出。
```
a is greater than b
a 大于 b
```
Perfect!
完美!
Let's modify the value of variable `a` to be less than value of variable `b` and see what happens. I will change `a`'s value to '10'. Following is the output after this modification:
来修改一下变量 `a` 的值,使其小于变量 `b` 的值,看看会发生什么。我将把 `a` 的值改为 '10'。修改后的输出如下:
```
b is greater than a
b 大于 a
```
But, what if I store the same value in variables `a` and `b`? To see this, I will set both variables' value to be '40'. Following is the output after this particular modification:
但是,如果我将相同的值存储在变量 `a``b` 中呢?为了看到这一点,我将两个变量的值都设置为 '40'。修改后的输出如下:
```
b is greater than a
b 大于 a
```
Huh? Logically, this doesn't make any sense... :(
嗯?从逻辑上讲,这没有任何意义... :(
But this can be improved! Continue reading.
但是这可以改进!我们继续。
### Using 'else if' conditional
### 使用 'else if' 条件
Like any other programming language, you can put an `else if` block to provide more than two execution paths. The syntax is as follows:
与其他任何编程语言一样,你可以使用 `else if` 块来提供多于两个的执行路径。语法如下:
```
if condition {
<statement(s)>;
} else if condition {
<statement(s)>;
if 条件 {
<语句>;
} else if 条件 {
<语句>;
} else {
<statement(s)>;
<语句>;
}
```
Now, with the use of an `else if` block, I can improve the logic of my program. Following is the modified program.
现在,通过使用 `else if` 块,我可以改进程序的逻辑。下面是修改后的程序。
```
fn main() {
@ -122,28 +122,28 @@ fn main() {
let b = 40;
if a == b {
println!("a and b are equal");
println!("a 与 b 是相等的");
} else if a > b {
println!("a is greater than b");
println!("a 大于 b");
} else {
println!("b is greater than a");
println!("b 大于 a");
}
}
```
Now, the logic of my program is correct. It has handled all edge cases (that I can think of). The condition where `a` is equal to `b` is handled on line 5. The condition where `a` might be greater than `b` is handled on line 7. And, the condition where `a` is less than `b` is intrinsically handled by the `else` block on line 9.
现在,我的程序的逻辑是正确的。它已经处理了所有的边缘情况(我能想到的)。第 5 行处理了 `a` 等于 `b` 的情况。第 7 行处理了 `a` 可能大于 `b` 的情况。而 `a` 小于 `b` 的情况则由第 9 行的 `else` 块隐式处理。
Now, when I run this code, I get the following output:
现在,当我运行这段代码时,我得到了以下输出:
```
a and b are equal
a 与 b 是相等的
```
Now that's perfect!
现在这就完美了!
### Example: Find the greatest
### 示例:找到最大值
I know that the use of `if` and `else` is easy, but let us look at one more program. This time, let's compare three numbers. I will also make use of a logical operator in this instance!
我知道使用 `if``else` 很容易,但是让我们再看一个程序。这次,我们来比较三个数字。我还将在这个实例中使用逻辑运算符!
```
fn main() {
@ -153,39 +153,39 @@ fn main() {
if (a != b) && (a != c) && (b != c) {
if (a > b) && (a > c) {
println!("a is the greatest");
println!("a 是最大的");
} else if (b > a) && (b > c) {
println!("b is the greatest");
println!("b 是最大的");
} else {
println!("c is the greatest");
println!("c 是最大的");
}
}
}
```
This might look complicated at first sight, but fear not; I shall explain this!
这个程序第一眼看上去可能很复杂,但是不要害怕,我会解释的!
Initially, I declare three variables `a`, `b` and `c` with random values that I could think of at that time. Then, on line 6, I check for the condition where no variable's value is same as any other variable. First, I check the values of `a` and `b`, then `a` and `c` and then `b` and `c`. This way I can be sure that there are no duplicate values stored in either variable.
最开始,我声明了三个变量 `a`、`b` 和 `c`,并赋予了我能想到的随机值。然后,在第 6 行,我检查了没有变量的值与其他变量相同的条件。首先,我检查 `a``b` 的值,然后是 `a``c`,最后是 `b``c`。这样我就可以确定没有变量中存储了重复的值。
Then, on line 7, I check if the value stored in variable `a` is the greatest. If that condition evaluates to `true`, code on line 8 gets executed. Otherwise the execution path on line 9 is checked.
然后,在第 7 行,我检查了变量 `a` 中存储的值是否是最大的。如果这个条件计算结果为 `true`,则会执行第 8 行的代码。否则,将检查第 9 行的执行路径。
On line 9, I check if the value stored in variable `b` is the greatest. If this condition evaluates to `true`, code on line 10 gets executed. If this condition is also `false`, then it means only one thing. Neither variable `a`, nor variable `b` is the greatest among all 3.
在第 9 行,我检查了变量 `b` 中存储的值是否是最大的。如果这个条件计算结果为 `true`,则会执行第 10 行的代码。如果这个条件也是 `false`那么只有一种可能。3 个变量中的最大值既不是 `a` 也不是 `b`
So naturally, in the `else` block, I print that the variable `c` holds the greatest value.
所以,自然地,在 `else` 块中,我打印出变量 `c` 拥有最大值。
Let's verify this with the program output:
来看看程序的输出:
```
a is the greatest
a 是最大的
```
And this is as expected. Try and modify the values assigned to each variable and test it out yourself! :)
这是预期的结果。尝试修改分配给每个变量的值,并自己测试一下! :)
### Conclusion
### 总结
You learned to use if and else statements. Before you go on making your own AI with lost of if else-if statements (haha), let' learn about loops in Rust in the next chapter of the series.
你学习到了如何使用 if 和 else 语句。在你继续使用大量 if else-if 语句制作自己的 AI 之前(哈哈),让我们在本系列的下一篇文章中学习 Rust 中的循环。
Stay tuned.
持续关注。
--------------------------------------------------------------------------------
@ -200,4 +200,4 @@ via: https://itsfoss.com/rust-if-else/
[a]: https://itsfoss.com/author/pratham/
[b]: https://github.com/lkxed/
[1]: https://itsfoss.com/rust-functions
[1]: https://linux.cn/article-15855-1.html