if/else

Branching with if-else is similar to other languages. Unlike many of them,
the boolean condition doesn’t need to be surrounded by parentheses, and each
condition is followed by a block. if-else conditionals are expressions,
and, all branches must return the same type.

  1. fn main() {
  2. let n = 5;
  3. if n < 0 {
  4. print!("{} is negative", n);
  5. } else if n > 0 {
  6. print!("{} is positive", n);
  7. } else {
  8. print!("{} is zero", n);
  9. }
  10. let big_n =
  11. if n < 10 && n > -10 {
  12. println!(", and is a small number, increase ten-fold");
  13. // This expression returns an `i32`.
  14. 10 * n
  15. } else {
  16. println!(", and is a big number, half the number");
  17. // This expression must return an `i32` as well.
  18. n / 2
  19. // TODO ^ Try suppressing this expression with a semicolon.
  20. };
  21. // ^ Don't forget to put a semicolon here! All `let` bindings need it.
  22. println!("{} -> {}", n, big_n);
  23. }