Basic Match Expressions: Categorizing HTTP Status Codes
Level: intro (score: 1)
In Rust, match
is a powerful alternative to a long chain of if/else if
statements.
It allows you to clearly express multiple conditions while ensuring all cases are handled safely.
Implement the function: http_status_category(code: u16) -> &'static str
Given an HTTP status code, return a category:
- 1xx (100-199) →
"Informational: Hold tight..."
- 2xx (200-299) →
"Success: Everything is awesome!"
- 3xx (300-399) →
"Redirection: Hang on, we’re moving!"
- 4xx (400-499) →
"Client Error: Oops! Something went wrong on your end."
- 5xx (500-599) →
"Server Error: It’s not you, it’s us."
- Otherwise →
"Unknown Status: Are we even on the internet?"
The function returns &'static str
, meaning it returns a reference to a string that never changes and always exists.
This works because all return values are string literals, which are built into the program and don’t need to be allocated at runtime.
We’ll explore lifetimes in more detail in a future exercise, but for now, just know that Rust safely manages these string references for us.
Why use match
?
Image using if/else if statements to categorize HTTP status codes:
if code >= 100 && code <= 199 {
"Informational: Hold tight..."
} else if code >= 200 && code <= 299 {
"Success: Everything is awesome!"
} else if code >= 300 && code <= 399 {
"Redirection: Hang on, we’re moving!"
} else if code >= 400 && code <= 499 {
"Client Error: Oops! Something went wrong on your end."
} else if code >= 500 && code <= 599 {
"Server Error: It’s not you, it’s us."
} else {
"Unknown Status: Are we even on the internet?"
}
Pretty ugly, right? match
is a much cleaner and more readable way to handle this kind of logic:
✅ match is more readable: Each case is clearly separated.
✅ match ensures completeness: If a case isn’t covered, Rust forces you to handle it.
✅ match is optimized: Rust can internally optimize pattern matching better than multiple if/else checks.
Hint: Use Rust’s range patterns like 100..=199 inside the match arms to simplify conditions.
Mastering match
will help you write clean, efficient Rust code—especially when dealing with multiple conditions.
Enough talking, now go ahead and use it yourself! 🚀