capypad
0 day streak
rust / beginner
Snippet

If Expressions and Conditional Branching

If expressions in Rust work similarly to other languages but have a key difference: they are expressions that return values. Each branch must evaluate to the same type if used as an expression. The condition does not need to be wrapped in parentheses, but the block must be wrapped in curly braces. You can chain multiple conditions with `else if`. Since if is an expression, you can assign its result directly to a variable as shown with `is_even`.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
fn main() {
let number = 7;
if number < 5 {
println!("Number is less than 5");
} else if number == 5 {
println!("Number equals 5");
} else {
println!("Number is greater than 5");
}
let is_even = if number % 2 == 0 { true } else { false };
println!("Is {} even? {}", number, is_even);
}
Breakdown
1
let number = 7;
Variable binding with type inference (i32 by default)
2
if number < 5 {
If expression evaluating a comparison - no parentheses needed
3
println!("Number is less than 5");
Execute if condition is true
4
} else if number == 5 {
Chaining alternative condition with equality check
5
} else {
Final catch-all branch when all conditions are false
6
let is_even = if number % 2 == 0 { true } else { false };
If as an expression - both branches return bool, result assigned to variable