Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

if/else - Rust By Example 09.10.

2023 13:04

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
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 }
11
12 let big_n =
13 if n < 10 && n > -10 {
14 println!(", and is a small number, increase ten-fold");
15
16 // This expression returns an `i32`.
17 10 * n
18 } else {
19 println!(", and is a big number, halve the number");
20
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.
26
27 println!("{} -> {}", n, big_n);
28 }

https://doc.rust-lang.org/rust-by-example/flow_control/if_else.html Stránka 1 z 1

You might also like