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.
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.
11 In the case of `if`, there is one choice that leads down two paths:
17 println!("x is five!");
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.
25 If you want something to happen in the `false` case, use an `else`:
31 println!("x is five!");
33 println!("x is not five :(");
37 If there is more than one case, use an `else if`:
43 println!("x is five!");
45 println!("x is six!");
47 println!("x is not five or six :(");
51 This is all pretty standard. However, you can also do this:
63 Which we can (and probably should) write like this:
68 let y = if x == 5 { 10 } else { 15 }; // y: i32
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.