Rust 基础系列 #6: 条件语句
Rust
![](/data/attachment/album/202306/11/094832bkkbs7oxntx7zxas.jpg)


在 [上一篇文章](/article-15855-1.html) 中，你学习了函数。在这篇文章中，我们将学习使用条件语句来管理 Rust 程序的控制流。


### 什么是条件语句？


在编写代码的时候，最常见的任务之一就是检查某些条件是否为 `true` 或 `false`。“如果温度高于 35°C，打开空调。”


通过使用 `if` 和 `else` 这样的关键字（有时候结合使用），程序员可以根据条件（例如提供的参数数量、从命令行传递的选项、文件名、错误发生等）改变程序的行为。


所以，对一个程序员来说，了解任何语言的控制流都是至关重要的，更不用说 Rust 了。


#### 条件运算符


下表列出了所有常用的单个条件运算符：




| 运算符 | 示例 | 解释 |
| --- | --- | --- |
| `>` | `a > b` | `a` **大于** `b` |
| `<` | `a < b` | `a` **小于** `b` |
| `==` | `a == b` | `a` **等于** `b` |
| `!=` | `a != b` | `a` **不等于** `b` |
| `>=` | `a >= b` | `a` **大于** 或 **等于** `b` |
| `<=` | `a <= b` | `a` **小于** 或 **等于** `b` |


以及下表是逻辑运算符，它们用于一个或多个条件之间：




| 运算符 | 示例 | 解释 |
| --- | --- | --- |
| `||` （逻辑或） | `条件1 || 条件2` | `条件1` 或 `条件2` 中至少有一个为 `true` |
| `&&` （逻辑与） | `条件1 && 条件2` | **所有** 条件都为 `true` |
| `!` （逻辑非） | `!条件` | `条件` 的布尔值的相反值 |



> 
> ? 与数学相似，你可以使用圆括号来指定操作的优先级。
> 
> 
> 


### 使用 if else


要控制 Rust 代码的基本流程，使用两个关键字：`if` 和 `else`。这可以根据提供的条件的状态创建两个“执行路径”。


一个简单的带有替代执行路径的 if 块的语法如下：



```
if 条件 {
    <语句>;
} else {
    <语句>;
}

```


> 
> ? 当只有一个条件时，将其括在圆括号中并不是强制性的。根据语法，使用圆括号是可选的。你仍然应该使用它们来指定优先级并优化可读性。
> 
> 
> 


来看看一个例子。



```
fn main() {
    let a = 36;
    let b = 25;

    if a > b {
        println!("a 大于 b");
    } else {
        println!("b 大于 a");
    }
}

```

这里，我声明了两个整数变量 `a` 和 `b`，它们的值分别为 '36' 和 '25'。在第 5 行，我检查变量 `a` 中存储的值是否大于变量 `b` 中存储的值。如果条件计算结果为 `true`，则会执行第 6 行的代码。如果条件计算结果为 `false`，由于我们有一个 `else` 块（可选），第 8 行的代码将被执行。


来看看程序的输出。



```
a 大于 b

```

完美！


来修改一下变量 `a` 的值，使其小于变量 `b` 的值，看看会发生什么。我将把 `a` 的值改为 '10'。修改后的输出如下：



```
b 大于 a

```

但是，如果我将相同的值存储在变量 `a` 和 `b` 中呢？为了看到这一点，我将两个变量的值都设置为 '40'。修改后的输出如下：



```
b 大于 a

```

嗯？从逻辑上讲，这没有任何意义... :frowning:


但是这可以改进！我们继续。


### 使用 else if 条件


与其他任何编程语言一样，你可以使用 `else if` 块来提供多于两个的执行路径。语法如下：



```
if 条件 {
    <语句>;
} else if 条件 {
    <语句>;
} else {
    <语句>;
}

```

现在，通过使用 `else if` 块，我可以改进程序的逻辑。下面是修改后的程序。



```
fn main() {
    let a = 40;
    let b = 40;

    if a == b {
        println!("a 与 b 是相等的");
    } else if a > b {
        println!("a 大于 b");
    } else {
        println!("b 大于 a");
    }
}

```

现在，我的程序的逻辑是正确的。它已经处理了所有的边缘情况（我能想到的）。第 5 行处理了 `a` 等于 `b` 的情况。第 7 行处理了 `a` 可能大于 `b` 的情况。而 `a` 小于 `b` 的情况则由第 9 行的 `else` 块隐式处理。


现在，当我运行这段代码时，我得到了以下输出：



```
a 与 b 是相等的

```

现在这就完美了！


### 示例：找到最大值


我知道使用 `if` 和 `else` 很容易，但是让我们再看一个程序。这次，我们来比较三个数字。我还将在这个实例中使用逻辑运算符！



```
fn main() {
    let a = 73;
    let b = 56;
    let c = 15;

    if (a != b) && (a != c) && (b != c) {
        if (a > b) && (a > c) {
            println!("a 是最大的");
        } else if (b > a) && (b > c) {
            println!("b 是最大的");
        } else {
            println!("c 是最大的");
        }
    }
}

```

这个程序第一眼看上去可能很复杂，但是不要害怕，我会解释的！


最开始，我声明了三个变量 `a`、`b` 和 `c`，并赋予了我能想到的随机值。然后，在第 6 行，我检查了没有变量的值与其他变量相同的条件。首先，我检查 `a` 和 `b` 的值，然后是 `a` 和 `c`，最后是 `b` 和 `c`。这样我就可以确定没有变量中存储了重复的值。


然后，在第 7 行，我检查了变量 `a` 中存储的值是否是最大的。如果这个条件计算结果为 `true`，则会执行第 8 行的代码。否则，将检查第 9 行的执行路径。


在第 9 行，我检查了变量 `b` 中存储的值是否是最大的。如果这个条件计算结果为 `true`，则会执行第 10 行的代码。如果这个条件也是 `false`，那么只有一种可能。3 个变量中的最大值既不是 `a` 也不是 `b`。


所以，自然地，在 `else` 块中，我打印出变量 `c` 拥有最大值。


来看看程序的输出：



```
a 是最大的

```

这是预期的结果。尝试修改分配给每个变量的值，并自己测试一下！ :smiley:


### 总结


你学习到了如何使用 `if` 和 `else` 语句。在你继续使用大量 `if` `else if` 语句制作自己的 AI 之前（哈哈），让我们在本系列的下一篇文章中学习 Rust 中的循环。


持续关注。


*（题图：MJ/3eea3bbb-b630-4470-ae21-391ab86cd5bf）*




---


via: <https://itsfoss.com/rust-if-else/>


作者：[Pratham Patel](https://itsfoss.com/author/pratham/) 选题：[lkxed](https://github.com/lkxed/) 译者：[Cubik65536](https://github.com/Cubik65536) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
# Rust Basics Series #6: Conditional Statements

You can control the flow of your program by using conditional statements. Learn to use if-else in Rust.

In the [previous article](https://itsfoss.com/rust-functions) 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.

## 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."

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.

So it is critical for a programmer to know control flow in any language, let alone in 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` |


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 |


## Using 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.

The syntax of a simple if block with an alternative execution path is as follows:

```
if condition {
<statement(s)>;
} else {
<statement(s)>;
}
```


Let's look at an example.

```
fn main() {
let a = 36;
let b = 25;
if a > b {
println!("a is greater than b");
} else {
println!("b is greater than 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.

Let's verify this by looking at the program output.

`a is greater than 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:

`b is greater than 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:

`b is greater than a`


Huh? Logically, this doesn't make any sense... :(

But this can be improved! Continue reading.

## Using 'else if' conditional

Like any other programming language, you can put an `else if`

block to provide more than two execution paths. The syntax is as follows:

```
if condition {
<statement(s)>;
} else if condition {
<statement(s)>;
} 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.

```
fn main() {
let a = 40;
let b = 40;
if a == b {
println!("a and b are equal");
} else if a > b {
println!("a is greater than b");
} else {
println!("b is greater than 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.

Now, when I run this code, I get the following output:

`a and b are equal`


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!

```
fn main() {
let a = 73;
let b = 56;
let c = 15;
if (a != b) && (a != c) && (b != c) {
if (a > b) && (a > c) {
println!("a is the greatest");
} else if (b > a) && (b > c) {
println!("b is the greatest");
} else {
println!("c is the greatest");
}
}
}
```


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.

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.

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.

So naturally, in the `else`

block, I print that the variable `c`

holds the greatest value.

Let's verify this with the program output:

`a is the greatest`


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.

Stay tuned.