]>
Commit | Line | Data |
---|---|---|
9346a6ac | 1 | % if |
1a4d82fc | 2 | |
9346a6ac AL |
3 | Rust’s take on `if` is not particularly complex, but it’s much more like the |
4 | `if` you’ll find in a dynamically typed language than in a more traditional | |
5 | systems language. So let’s talk about it, to make sure you grasp the nuances. | |
1a4d82fc | 6 | |
54a0048b | 7 | `if` is a specific form of a more general concept, the ‘branch’, whose name comes |
1a4d82fc JJ |
8 | from a branch in a tree: a decision point, where depending on a choice, |
9 | multiple paths can be taken. | |
10 | ||
11 | In the case of `if`, there is one choice that leads down two paths: | |
12 | ||
13 | ```rust | |
14 | let x = 5; | |
15 | ||
16 | if x == 5 { | |
17 | println!("x is five!"); | |
18 | } | |
19 | ``` | |
20 | ||
21 | If we changed the value of `x` to something else, this line would not print. | |
22 | More specifically, if the expression after the `if` evaluates to `true`, then | |
9346a6ac | 23 | the block is executed. If it’s `false`, then it is not. |
1a4d82fc JJ |
24 | |
25 | If you want something to happen in the `false` case, use an `else`: | |
26 | ||
9346a6ac | 27 | ```rust |
1a4d82fc JJ |
28 | let x = 5; |
29 | ||
30 | if x == 5 { | |
31 | println!("x is five!"); | |
32 | } else { | |
33 | println!("x is not five :("); | |
34 | } | |
35 | ``` | |
36 | ||
c34b1796 AL |
37 | If there is more than one case, use an `else if`: |
38 | ||
39 | ```rust | |
40 | let x = 5; | |
41 | ||
42 | if x == 5 { | |
43 | println!("x is five!"); | |
44 | } else if x == 6 { | |
45 | println!("x is six!"); | |
46 | } else { | |
47 | println!("x is not five or six :("); | |
48 | } | |
49 | ``` | |
50 | ||
1a4d82fc JJ |
51 | This is all pretty standard. However, you can also do this: |
52 | ||
9346a6ac | 53 | ```rust |
1a4d82fc JJ |
54 | let x = 5; |
55 | ||
56 | let y = if x == 5 { | |
57 | 10 | |
58 | } else { | |
59 | 15 | |
60 | }; // y: i32 | |
61 | ``` | |
62 | ||
63 | Which we can (and probably should) write like this: | |
64 | ||
9346a6ac | 65 | ```rust |
1a4d82fc JJ |
66 | let x = 5; |
67 | ||
68 | let y = if x == 5 { 10 } else { 15 }; // y: i32 | |
69 | ``` | |
70 | ||
9346a6ac AL |
71 | This works because `if` is an expression. The value of the expression is the |
72 | value of the last expression in whichever branch was chosen. An `if` without an | |
73 | `else` always results in `()` as the value. |