Bird
Raised Fist0
Rustprogramming~10 mins

Result enum in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Result enum
Start Operation
↓
Operation Succeeds?
No→Return Err(value)
Yes↓
Return Ok(value)
↓
Caller Handles Result
↓
Match Ok: Use value
↓
Match Err: Handle error
The Result enum represents success (Ok) or failure (Err). Code returns one, and caller matches to handle each case.
Execution Sample
Rust
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Divide by zero"))
    } else {
        Ok(a / b)
    }
}
This function divides two numbers and returns Ok with the result or Err with an error message if dividing by zero.
Execution Table
StepInput (a,b)Condition b==0?Returned ResultExplanation
1(10, 2)FalseOk(5)10 divided by 2 is 5, so return Ok(5)
2(10, 0)TrueErr("Divide by zero")Cannot divide by zero, return error
3Caller matches Result-Match Ok or ErrCaller checks if result is Ok or Err to proceed
💡 Function returns either Ok or Err based on divisor; caller must handle both cases.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
a10101010
b2 or 0200 or 2
ResultNoneOk(5)Err("Divide by zero")Ok(5) or Err("Divide by zero")
Key Moments - 2 Insights
Why do we use Result instead of just returning the value?
Result lets us handle errors explicitly. As shown in the execution_table rows 1 and 2, the function returns Ok when successful and Err when there's an error, so the caller can decide what to do.
What happens if we forget to handle the Err case?
If the caller ignores Err, the program might panic or behave unexpectedly. The execution_table row 3 shows the caller must match on Result to safely use the value or handle errors.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does the function return when b is zero?
AOk(10)
BOk(0)
CErr("Divide by zero")
DNone
💡 Hint
Check step 2 in execution_table where b == 0 condition is True.
At which step does the function return Ok(5)?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at step 1 in execution_table where b == 2 and result is Ok(5).
If we change the divisor b from 0 to 3, what changes in the variable_tracker?
AVariable a changes
BResult changes from Err to Ok
CNo change in Result
DVariable b becomes zero
💡 Hint
See variable_tracker rows for b and Result values after step 2.
Concept Snapshot
Result enum in Rust:
- Used to return success (Ok) or error (Err)
- Syntax: Result<T, E> where T is success type, E is error type
- Functions return Ok(value) on success
- Return Err(error) on failure
- Caller matches Result to handle both cases
Full Transcript
The Result enum in Rust is a way to handle operations that can succeed or fail. When a function runs, it returns Ok with a value if successful, or Err with an error message if something goes wrong. For example, a divide function returns Ok with the division result if the divisor is not zero, or Err if dividing by zero. The caller then checks the Result using match to decide what to do next. This approach helps avoid crashes and makes error handling clear and safe.

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

  1. Step 1: Understand the purpose of Result

    Result is used to show if an operation succeeded or failed.
  2. Step 2: Identify the two variants

    Ok means success, Err means failure or error.
  3. Final Answer:

    A value that can be either success (Ok) or failure (Err) -> Option C
  4. 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

  1. Step 1: Check the correct variant for success

    Success uses Ok, so Ok(10) is correct.
  2. Step 2: Verify the type matches

    The type is Result, so Ok(10) matches i32 for success.
  3. Final Answer:

    let x: Result<i32, &str> = Ok(10); -> Option D
  4. 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

  1. 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).
  2. Step 2: Match on the Result

    The match sees Ok(5), so it prints Result: 5.
  3. Final Answer:

    Result: 5 -> Option B
  4. 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

  1. Step 1: Check the function return type

    The function returns Result<i32, String>, so Ok must hold i32 and Err must hold String.
  2. Step 2: Identify the error in Err(42)

    42 is an integer, but Err expects a String. This causes a type mismatch.
  3. Final Answer:

    The Err variant has wrong type; should be a String -> Option A
  4. 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

  1. Step 1: Understand parse returns Result

    Each s.parse::<i32>() returns Result<i32, _>, so we get an iterator of Results.
  2. 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.
  3. Final Answer:

    filter_map(Result::ok).collect() -> Option A
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard