]> git.proxmox.com Git - rustc.git/blame - src/doc/book/if.md
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / src / doc / book / if.md
CommitLineData
9346a6ac 1% if
1a4d82fc 2
9346a6ac
AL
3Rust’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
5systems 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
8from a branch in a tree: a decision point, where depending on a choice,
9multiple paths can be taken.
10
11In the case of `if`, there is one choice that leads down two paths:
12
13```rust
14let x = 5;
15
16if x == 5 {
17 println!("x is five!");
18}
19```
20
21If we changed the value of `x` to something else, this line would not print.
22More specifically, if the expression after the `if` evaluates to `true`, then
9346a6ac 23the block is executed. If it’s `false`, then it is not.
1a4d82fc
JJ
24
25If you want something to happen in the `false` case, use an `else`:
26
9346a6ac 27```rust
1a4d82fc
JJ
28let x = 5;
29
30if x == 5 {
31 println!("x is five!");
32} else {
33 println!("x is not five :(");
34}
35```
36
c34b1796
AL
37If there is more than one case, use an `else if`:
38
39```rust
40let x = 5;
41
42if 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
51This is all pretty standard. However, you can also do this:
52
9346a6ac 53```rust
1a4d82fc
JJ
54let x = 5;
55
56let y = if x == 5 {
57 10
58} else {
59 15
60}; // y: i32
61```
62
63Which we can (and probably should) write like this:
64
9346a6ac 65```rust
1a4d82fc
JJ
66let x = 5;
67
68let y = if x == 5 { 10 } else { 15 }; // y: i32
69```
70
9346a6ac
AL
71This works because `if` is an expression. The value of the expression is the
72value of the last expression in whichever branch was chosen. An `if` without an
73`else` always results in `()` as the value.