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