if expressions

You use if expressions exactly like if statements in other languages:

  1. fn main() {
  2.     let x = 10;
  3.     if x == 0 {
  4.         println!("zero!");
  5.     } else if x < 100 {
  6.         println!("biggish");
  7.     } else {
  8.         println!("huge");
  9.     }
  10. }

In addition, you can use if as an expression. The last expression of each block becomes the value of the if expression:

  1. fn main() {
  2.     let x = 10;
  3.     let size = if x < 20 { "small" } else { "large" };
  4.     println!("number size: {}", size);
  5. }

This slide should take about 4 minutes.

Because if is an expression and must have a particular type, both of its branch blocks must have the same type. Show what happens if you add ; after "small" in the second example.

An if expression should be used in the same way as the other expressions. For example, when it is used in a let statement, the statement must be terminated with a ; as well. Remove the ; before println! to see the compiler error.