Handling Success and Errors with the Result Enum in Rust
📖 Scenario: Imagine you are writing a small program that tries to divide two numbers. Sometimes the division might fail if the divisor is zero. Rust's Result enum helps us handle such success or error cases safely.
🎯 Goal: You will create a function that divides two numbers and returns a Result enum. Then you will call this function and handle both success and error cases.
📋 What You'll Learn
Create a function called divide that takes two f64 numbers and returns Result<f64, String>
Return Ok with the division result if the divisor is not zero
Return Err with an error message if the divisor is zero
Call the divide function with example values
Use match to handle both Ok and Err cases and print appropriate messages
💡 Why This Matters
🌍 Real World
Handling success and error cases is common in real-world programs, such as reading files, network requests, or user input validation.
💼 Career
Understanding the <code>Result</code> enum is essential for Rust developers to write robust and error-resistant applications.
Progress0 / 4 steps
1
Create the divide function with Result return type
Write a function called divide that takes two f64 parameters named numerator and denominator. The function should return Result<f64, String>. For now, just return Ok(0.0) to set up the function.
Rust
Hint
Define the function with the correct parameters and return type. Use Ok(0.0) as a placeholder return value.
2
Add logic to check for zero denominator and return Err
Inside the divide function, add an if statement to check if denominator is zero. If it is, return Err with the message "Cannot divide by zero". Otherwise, return Ok with the division result numerator / denominator.
Rust
Hint
Use an if condition to check for zero and return Err. Otherwise, return Ok with the division.
3
Call divide with example values and use match to handle the result
Create two variables: result1 by calling divide(10.0, 2.0) and result2 by calling divide(5.0, 0.0). Then use a match statement on result1 with arms for Ok(value) and Err(message). Print "Result: {value}" for Ok and "Error: {message}" for Err. Repeat the same match for result2.
Rust
Hint
Call the function twice with different values. Use match to print the success or error messages.
4
Print the results of the division attempts
Run the program to print the output of both division attempts. The output should show the successful division result and the error message for division by zero.
Rust
Hint
Run the program and check that it prints the correct success and error messages.
Practice
(1/5)
1. What does the Result enum in Rust represent?
easy
A. A type for storing multiple values in a list
B. A way to loop over numbers
C. A value that can be either success (Ok) or failure (Err)
D. A function that always returns Ok
Solution
Step 1: Understand the purpose of Result
Result is used to show if an operation succeeded or failed.
Step 2: Identify the two variants
Ok means success, Err means failure or error.
Final Answer:
A value that can be either success (Ok) or failure (Err) -> Option C
Quick Check:
Result = success or failure [OK]
Hint: Remember: Result = Ok (success) or Err (failure) [OK]
Common Mistakes:
Thinking Result is a list or collection
Confusing Result with loops or arrays
Assuming Result always means success
2. Which of the following is the correct way to create a Result with a success value of 10?
easy
A. let x: Result = Result::new(10);
B. let x: Result = Err(10);
C. let x: Result = Ok("10");
D. let x: Result = Ok(10);
Solution
Step 1: Check the correct variant for success
Success uses Ok, so Ok(10) is correct.
Step 2: Verify the type matches
The type is Result, so Ok(10) matches i32 for success.
Final Answer:
let x: Result<i32, &str> = Ok(10); -> Option D
Quick Check:
Success = Ok(value) [OK]
Hint: Use Ok(value) for success, Err(value) for error [OK]
Common Mistakes:
Using Err for success value
Mismatching types inside Ok or Err
Trying to use Result::Ok instead of Ok directly
3. What will be printed by this Rust code?
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),
}
}
medium
A. Result: 0
B. Result: 5
C. Error: Divide by zero
D. Compile error
Solution
Step 1: Check the divide function call
Calling divide(10, 2) means b is 2, not zero, so it returns Ok(10 / 2) which is Ok(5).
Step 2: Match on the Result
The match sees Ok(5), so it prints Result: 5.
Final Answer:
Result: 5 -> Option B
Quick Check:
Ok(5) prints Result: 5 [OK]
Hint: Match Ok prints result, Err prints error message [OK]
Common Mistakes:
Assuming divide by 2 returns error
Confusing Ok and Err branches
Expecting compile error due to String
4. Identify the error in this Rust code using Result:
fn get_number(flag: bool) -> Result {
if flag {
Ok(42)
} else {
Err(42)
}
}
medium
A. The Err variant has wrong type; should be a String
B. The Ok variant should return a String
C. Missing semicolon after Ok(42)
D. Function must return Option not Result
Solution
Step 1: Check the function return type
The function returns Result<i32, String>, so Ok must hold i32 and Err must hold String.
Step 2: Identify the error in Err(42)
42 is an integer, but Err expects a String. This causes a type mismatch.
Final Answer:
The Err variant has wrong type; should be a String -> Option A
Quick Check:
Err type must match declared error type [OK]
Hint: Err must match error type declared in Result [OK]
Common Mistakes:
Using wrong type inside Err
Thinking Ok needs String
Ignoring type mismatch errors
5. Given a list of strings representing numbers, which Rust code correctly converts them to integers and collects only successful parses using 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);
hard
A. filter_map(Result::ok).collect()
B. filter(|r| r.is_ok()).collect()
C. map(Result::unwrap).collect()
D. collect::()
Solution
Step 1: Understand parse returns Result
Each s.parse::<i32>() returns Result<i32, _>, so we get an iterator of Results.
Step 2: Use filter_map(Result::ok) to keep only successes
filter_map(Result::ok) extracts the Ok values and skips errors, then collect() gathers them into a vector.
Final Answer:
filter_map(Result::ok).collect() -> Option A
Quick Check:
filter_map(Result::ok) keeps only successful parses [OK]
Hint: Use filter_map(Result::ok) to keep only Ok values [OK]
Common Mistakes:
Using filter without extracting Ok values
Calling unwrap on all results causing panic
Trying to collect without filtering errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.