2015-04-10 10:35:19 -05:00
|
|
|
|
% if
|
2015-04-07 21:16:02 -05:00
|
|
|
|
|
2015-04-10 10:50:28 -05:00
|
|
|
|
Rust’s take on `if` is not particularly complex, but it’s much more like the
|
|
|
|
|
`if` you’ll find in a dynamically typed language than in a more traditional
|
|
|
|
|
systems language. So let’s talk about it, to make sure you grasp the nuances.
|
2015-04-07 21:16:02 -05:00
|
|
|
|
|
2015-04-10 10:50:28 -05:00
|
|
|
|
`if` is a specific form of a more general concept, the ‘branch’. The name comes
|
2015-04-07 21:16:02 -05:00
|
|
|
|
from a branch in a tree: a decision point, where depending on a choice,
|
|
|
|
|
multiple paths can be taken.
|
|
|
|
|
|
|
|
|
|
In the case of `if`, there is one choice that leads down two paths:
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
let x = 5;
|
|
|
|
|
|
|
|
|
|
if x == 5 {
|
|
|
|
|
println!("x is five!");
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
If we changed the value of `x` to something else, this line would not print.
|
|
|
|
|
More specifically, if the expression after the `if` evaluates to `true`, then
|
2015-04-10 10:50:28 -05:00
|
|
|
|
the block is executed. If it’s `false`, then it is not.
|
2015-04-07 21:16:02 -05:00
|
|
|
|
|
|
|
|
|
If you want something to happen in the `false` case, use an `else`:
|
|
|
|
|
|
2015-04-10 10:50:28 -05:00
|
|
|
|
```rust
|
2015-04-07 21:16:02 -05:00
|
|
|
|
let x = 5;
|
|
|
|
|
|
|
|
|
|
if x == 5 {
|
|
|
|
|
println!("x is five!");
|
|
|
|
|
} else {
|
|
|
|
|
println!("x is not five :(");
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
If there is more than one case, use an `else if`:
|
|
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
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 :(");
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
This is all pretty standard. However, you can also do this:
|
|
|
|
|
|
2015-04-10 10:50:28 -05:00
|
|
|
|
```rust
|
2015-04-07 21:16:02 -05:00
|
|
|
|
let x = 5;
|
|
|
|
|
|
|
|
|
|
let y = if x == 5 {
|
|
|
|
|
10
|
|
|
|
|
} else {
|
|
|
|
|
15
|
|
|
|
|
}; // y: i32
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
Which we can (and probably should) write like this:
|
|
|
|
|
|
2015-04-10 10:50:28 -05:00
|
|
|
|
```rust
|
2015-04-07 21:16:02 -05:00
|
|
|
|
let x = 5;
|
|
|
|
|
|
|
|
|
|
let y = if x == 5 { 10 } else { 15 }; // y: i32
|
|
|
|
|
```
|
|
|
|
|
|
2015-04-10 10:50:28 -05:00
|
|
|
|
This works because `if` is an expression. The value of the expression is the
|
|
|
|
|
value of the last expression in whichever branch was chosen. An `if` without an
|
|
|
|
|
`else` always results in `()` as the value.
|