Rust Conditionals
Overview
Conditional statements allow different code branches to be executed based on conditions. Rust provides conditional statements such as if, else if, and else.
🎯 if Expressions
Basic Usage
rust
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}Multiple Conditions
rust
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}if in let Statements
rust
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {}", number);
}📝 Chapter Summary
Conditional statements are an important part of program control flow. Mastering their usage is crucial for writing complex logic.
Continue learning: Next chapter - Rust Loops