I Stopped Writing if/else Chains in Rust. Here’s What I Write Instead.
Java trained me to think in if/else. Check the condition, branch left or right, nest another if inside if you need more cases. After years of it the pattern becomes muscle memory. You stop noticing how much ceremony it takes just to dispatch on a value.
Rust has a different tool for this. Once I started using it properly I stopped reaching for if/else chains almost entirely.
The Java way of checking a value
Here is a typical Java dispatch — check what kind of message came in and handle it:
String messageType = message.getType();
if (messageType.equals("ERROR")) {
logger.error(message.getBody());
} else if (messageType.equals("WARNING")) {
logger.warn(message.getBody());
} else if (messageType.equals("INFO")) {
logger.info(message.getBody());
} else {
throw new IllegalArgumentException("Unknown type: " + messageType);
}
String messageType = message.getType();
if (messageType.equals("ERROR")) {
logger.error(message.getBody());
} else if (messageType.equals("WARNING")) {
logger.warn(message.getBody());
} else if (messageType.equals("INFO")) {
logger.info(message.getBody());
} else {
throw new IllegalArgumentException("Unknown type: " + messageType);
}
This works. It is also tedious. If you add a new message type you might forget one of these branches. The compiler will not tell you. You find out when a message gets silently swallowed.
match
Rust’s match does the same job:
log::error!("{}", message.body),
MessageType::Warning => log::warn!("{}", message.body),
MessageType::Info => log::info!("{}", message.body),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
match message.message_type {
MessageType::Error => log::error!("{}", message.body),
MessageType::Warning => log::warn!("{}", message.body),
MessageType::Info => log::info!("{}", message.body),
}
match message.message_type {
MessageType::Error => log::error!("{}", message.body),
MessageType::Warning => log::warn!("{}", message.body),
MessageType::Info => log::info!("{}", message.body),
}
The critical difference: match is exhaustive. If you add a new variant to MessageType and forget to handle it here, the program does not compile. The compiler tells you exactly which variant you missed. You cannot ship incomplete dispatch logic.
match is also an expression, not a statement. It evaluates to a value:
"OK",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown",
};” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
let label = match status_code {
200 => "OK",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown",
};
let label = match status_code {
200 => "OK",
404 => "Not Found",
500 => "Internal Server Error",
_ => "Unknown",
};
No intermediate variable, no early return, no assignment inside each branch. Just the value.
Matching on data inside variants
This is where match pulls ahead of anything Java’s switch can do. Rust enums carry data, and match can destructure that data in the same expression:
println!("Got: {}", body),
Response::Failure { code, message } => {
println!("Failed with {}: {}", code, message)
}
Response::Timeout => println!("Request timed out"),
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
enum Response {
Success(String),
Failure { code: u32, message: String },
Timeout,
}
fn handle(response: Response) {
match response {
Response::Success(body) => println!("Got: {}", body),
Response::Failure { code, message } => {
println!("Failed with {}: {}", code, message)
}
Response::Timeout => println!("Request timed out"),
}
}
enum Response {
Success(String),
Failure { code: u32, message: String },
Timeout,
}
fn handle(response: Response) {
match response {
Response::Success(body) => println!("Got: {}", body),
Response::Failure { code, message } => {
println!("Failed with {}: {}", code, message)
}
Response::Timeout => println!("Request timed out"),
}
}
In Java you would check an enum value and then call separate getter methods to get the payload. In Rust the match arm extracts the payload directly. The data and the dispatch happen in one place.
Guards
Match arms can have conditions attached:
&'static str {
match n {
0 => "zero",
n if n "negative",
n if n > 100 => "large",
_ => "normal",
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn classify(n: i32) -> &'static str {
match n {
0 => "zero",
n if n < 0 => "negative",
n if n > 100 => "large",
_ => "normal",
}
}
fn classify(n: i32) -> &'static str {
match n {
0 => "zero",
n if n < 0 => "negative",
n if n > 100 => "large",
_ => "normal",
}
}
The if after the pattern is a guard. The arm only fires if the pattern matches AND the condition holds. This replaces the pattern of matching on a value and then nesting another if inside the branch.
if let
Sometimes you only care about one variant and want to ignore the rest. A full match for that is noise:
apply_timeout(t),
None => {},
}
// cleaner
if let Some(t) = config.timeout {
apply_timeout(t);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// verbose
match config.timeout {
Some(t) => apply_timeout(t),
None => {},
}
// cleaner
if let Some(t) = config.timeout {
apply_timeout(t);
}
// verbose
match config.timeout {
Some(t) => apply_timeout(t),
None => {},
}
// cleaner
if let Some(t) = config.timeout {
apply_timeout(t);
}
if let pairs a pattern with a value. If the pattern matches, the binding is available inside the block. If it does not match, the block is skipped. No arms, no exhaustiveness requirement, no placeholder for the case you do not care about.
It reads the same way the logic reads: “if there is a timeout, apply it.”
while let
The same idea applies to loops. This drains a stack until it is empty:
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("{}", top);
}
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("{}", top);
}
stack.pop() returns Option<i32>. While it returns Some, the loop runs with top bound to the value. When the stack is empty it returns None and the loop ends. No index variable, no length check, no off-by-one risk.
Destructuring without match
The same pattern syntax works in let bindings and function parameters:
let (x, y, z) = (1, 2, 3);
let Point { x, y } = get_point();
fn process((name, score): (&str, u32)) {
println!("{} scored {}", name, score);
}
let (x, y, z) = (1, 2, 3);
let Point { x, y } = get_point();
fn process((name, score): (&str, u32)) {
println!("{} scored {}", name, score);
}
When a function receives a tuple or struct and immediately pulls out the fields, you can do it in the parameter declaration. No unpacking inside the body.
Matching multiple patterns
One arm can match several values with |:
println!("vowel"),
'a'..='z' => println!("consonant"),
_ => println!("other"),
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
match key {
'a' | 'e' | 'i' | 'o' | 'u' => println!("vowel"),
'a'..='z' => println!("consonant"),
_ => println!("other"),
}
match key {
'a' | 'e' | 'i' | 'o' | 'u' => println!("vowel"),
'a'..='z' => println!("consonant"),
_ => println!("other"),
}
And ranges with ..=. This replaces the Java pattern of checking membership in a set or writing five separate else-if branches for five related values.
The exhaustiveness guarantee is the point
Java’s switch statements are not exhaustive by default. You can add a default case or leave it out and silently miss values. Java’s switch expressions (from Java 14 onwards) are exhaustive when you use them as expressions, but it took twenty-something years to get there.
Rust’s match has been exhaustive since day one. The compiler rejects incomplete matches. If you handle ten variants but the enum has eleven, you get a compile error telling you exactly which one you missed.
For enums that represent states in a system — order statuses, event types, command variants — this guarantee is not a nice-to-have. Missing a case in production means a silent failure or a panic. The compiler catching it at compile time means neither of those happens.
Java 21 brought exhaustive pattern matching too, it took twenty years to get there, but it is there now.
Fun fact: Java is still my favourite language though.
What I actually write now
Before Rust, a typical piece of dispatch code I wrote looked like this: check a type string, branch on it, extract data with getters, handle the case I forgot about three months later when a new type was added.
Now it looks like this: define an enum with variants that carry their own data, write a match, let the compiler tell me if I ever add a variant and forget to handle it somewhere. The feedback loop went from “production incident” to “compile error.”
I spent six months writing about Rust and turned it into a 23-chapter field guide with a full Redis clone as the capstone. If you are working through this language seriously, it covers everything from ownership to production-level concurrency.
$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample
The enum chapter that started this: Rust Enums Are Not Java Enums. They’re Something Better.


