What if your program could catch mistakes before they cause crashes, every time?
Why Result enum in Rust? - Purpose & Use Cases
Imagine you are writing a program that reads a file and then processes its content. You try to open the file, but what if the file does not exist or you don't have permission? You have to check every step manually to see if something went wrong.
Manually checking for errors after every operation is slow and easy to forget. If you miss a check, your program might crash or behave unpredictably. It becomes a big mess to handle all possible errors everywhere in your code.
The Result enum in Rust wraps the success or failure of an operation in a single value. It forces you to handle errors explicitly, making your code safer and clearer. You can easily chain operations and handle errors in one place.
let file = File::open("data.txt"); if file.is_err() { println!("Failed to open file"); return; } let file = file.unwrap();
let file = File::open("data.txt")?;
It enables writing robust programs that gracefully handle errors without crashing or confusing bugs.
When building a web server, you can use Result to handle network errors, file reads, or database queries cleanly, so your server stays reliable even if something goes wrong.
Manual error checks are slow and risky.
Result enum bundles success or error in one value.
This makes error handling clear, safe, and easy to manage.
Practice
Result enum in Rust represent?Solution
Step 1: Understand the purpose of
ResultResultis used to show if an operation succeeded or failed.Step 2: Identify the two variants
Okmeans success,Errmeans failure or error.Final Answer:
A value that can be either success (Ok) or failure (Err) -> Option CQuick Check:
Result= success or failure [OK]
- Thinking Result is a list or collection
- Confusing Result with loops or arrays
- Assuming Result always means success
Result with a success value of 10?Solution
Step 1: Check the correct variant for success
Success usesOk, soOk(10)is correct.Step 2: Verify the type matches
The type isResult, soOk(10)matchesi32for success.Final Answer:
let x: Result<i32, &str> = Ok(10); -> Option DQuick Check:
Success = Ok(value) [OK]
- Using Err for success value
- Mismatching types inside Ok or Err
- Trying to use Result::Ok instead of Ok directly
fn divide(a: i32, b: i32) -> Result {
if b == 0 {
Err(String::from("Divide by zero"))
} else {
Ok(a / b)
}
}
fn main() {
match divide(10, 2) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
}Solution
Step 1: Check the divide function call
Callingdivide(10, 2)meansbis 2, not zero, so it returnsOk(10 / 2)which isOk(5).Step 2: Match on the Result
ThematchseesOk(5), so it printsResult: 5.Final Answer:
Result: 5 -> Option BQuick Check:
Ok(5) prints Result: 5 [OK]
- Assuming divide by 2 returns error
- Confusing Ok and Err branches
- Expecting compile error due to String
Result:fn get_number(flag: bool) -> Result {
if flag {
Ok(42)
} else {
Err(42)
}
}Solution
Step 1: Check the function return type
The function returnsResult<i32, String>, soOkmust holdi32andErrmust holdString.Step 2: Identify the error in
Err(42)42is an integer, butErrexpects aString. This causes a type mismatch.Final Answer:
TheErrvariant has wrong type; should be a String -> Option AQuick Check:
Err type must match declared error type [OK]
- Using wrong type inside Err
- Thinking Ok needs String
- Ignoring type mismatch errors
Result handling?let strings = vec!["10", "abc", "20", "xyz"];
// Fill in the blank:
let numbers: Vec<i32> = strings.iter()
.map(|s| s.parse::<i32>())
.__________;
println!("{:?}", numbers);Solution
Step 1: Understand
EachparsereturnsResults.parse::<i32>()returnsResult<i32, _>, so we get an iterator of Results.Step 2: Use
filter_map(Result::ok)to keep only successesfilter_map(Result::ok)extracts theOkvalues and skips errors, thencollect()gathers them into a vector.Final Answer:
filter_map(Result::ok).collect() -> Option AQuick Check:
filter_map(Result::ok) keeps only successful parses [OK]
- Using filter without extracting Ok values
- Calling unwrap on all results causing panic
- Trying to collect without filtering errors
Ready to prove it?
Pass the test and this pattern moves unknown
