Making Decisions in Rust: The Power of if
and match
Every good program needs to make decisions, just like you deciding whether to have coffee or tea in the morning! In Rust, we have two main ways to handle conditional logic: if
statements and the match
expression. Let’s explore them!
1. if
Statements: The Classic Decision Maker
Rust’s if
works just like in most programming languages but with some extra strictness to keep things safe!
a) Basic if
statement
fn main() {
let temperature = 30;
if temperature > 25 {
println!("It's hot outside!");
} else {
println!("It's cool outside!");
}
}
No parentheses needed around conditions! Curly braces {}
are mandatory, even for one-line blocks.
b) if
with else if
fn main() {
let score = 85;
if score >= 90 {
println!("You got an A!");
} else if score >= 75 {
println!("You got a B!");
} else {
println!("Better luck next time!");
}
}
Rust checks conditions top to bottom, so order matters!
c) Using if
as an Expression
fn main() {
let is_raining = true;
let message = if is_raining { "Bring an umbrella!" } else { "Enjoy the sunshine!" };
println!("{}", message);
}
if
returns a value, but both arms must return the same type.
2. match
: The Supercharged Switch
For complex decision-making, match
is Rust’s pattern-matching powerhouse!
a) Basic match
fn main() {
let traffic_light = "green";
match traffic_light {
"green" => println!("Go!"),
"yellow" => println!("Slow down!"),
"red" => println!("Stop!"),
_ => println!("Invalid color!"),
}
}
No fall-through like in C/C++. The _
case acts as a catch-all for unmatched values.
b) Matching with Enums
match
is best when working with enums!
enum Weather {
Sunny,
Rainy,
Cloudy,
}
fn main() {
let today = Weather::Rainy;
match today {
Weather::Sunny => println!("Wear sunglasses!"),
Weather::Rainy => println!("Take an umbrella!"),
Weather::Cloudy => println!("Maybe bring a jacket!"),
}
}
Pattern matching is exhaustive, ensuring all cases are handled.
Wrapping Up
Now, you’re a Rust decision-making master! You’ve learned: if
statements for simple conditions, Using if
as an expression, match
for powerful pattern matching, How Rust ensures safety in decision-making
0 Comments