rust / beginner
Snippet
Control Flow with If Expressions
In Rust, 'if' is an expression, not just a statement. This means it returns a value that can be assigned to a variable, provided all branches return the same type.
snippet.rs
1
2
3
4
5
6
7
8
9
fn main() {let number = 7;let condition = if number < 10 {true} else {false};println!("Condition is {condition}");}
Breakdown
1
let condition = if number < 10 {
Starts an assignment where the value depends on the if-condition result.
2
true
The value returned if the condition is met (no semicolon here).
3
} else { false };
The fallback value returned if the condition is false.