]> git.proxmox.com Git - rustc.git/blob - src/doc/book/if.md
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / doc / book / if.md
1 % if
2
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.
6
7 `if` is a specific form of a more general concept, the ‘branch’, whose name comes
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
23 the block is executed. If it’s `false`, then it is not.
24
25 If you want something to happen in the `false` case, use an `else`:
26
27 ```rust
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
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
51 This is all pretty standard. However, you can also do this:
52
53 ```rust
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
65 ```rust
66 let x = 5;
67
68 let y = if x == 5 { 10 } else { 15 }; // y: i32
69 ```
70
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.