let number = 5;if number < 0 && number > -10 { println!("The number is negative");} else if number == 0 { println!("The number is zero");} else { println!("The number is positive");}
Note
Conditions must be bool. There is no implicit conversion from integers to booleans as in other languages.
if as an expression
In Rust, if is an expression and returns a value:
let approved = if number > 4 { true } else { false };
Match
match is a control pattern that allows branching the code according to a value. It must cover all possible cases.
match number { x if x < 0 => println!("Negative"), // Guard 0 => println!("Zero"), // Exact literal 1..=4 => println!("Between 1 and 4"), // Inclusive range _ => println!("Other"), // Wildcard}
Note
The range 1..=4 includes 4. If you want to exclude the upper bound use 1..4.
Match as an expression
let approved = match number { x if x < 5 => false, 5..=10 => true, _ => false,};
Special patterns in match
// Multiple valuesmatch color { Color::Red | Color::Green => println!("Red or green"), _ => println!("Another color"),}// Destructuringmatch point { (0, 0) => println!("Origin"), (x, 0) => println!("X axis: {}", x), (0, y) => println!("Y axis: {}", y), (x, y) => println!("Point: {}, {}", x, y),}// Binding with @ (stores the data in a variable (n in this case))match age { n @ 18..=65 => println!("Age {} in working range", n), _ => println!("Out of range"),}
Tip
match is heavily used with Option and Result to elegantly handle missing values or errors:
// Reference to the array (avoids the copy)for value in &array { println!("The value is: {}", value);}// With enumeration (index + value)for (i, value) in array.iter().enumerate() { println!("Index: {}, Value: {}", i, value);}// Iterating over a HashMapfor (name, age) in &hashmap { println!("{} {}", name, age);}// Mutable reference (modifies the elements)for element in &mut vector { *element += 1; // dereference to modify}
Tip
for is preferable to while or loop when you know how many iterations you need. The compiler can optimize it better.