Bird
Raised Fist0
Rustprogramming~20 mins

Result enum in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Result Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code using Result?
Consider this Rust code snippet using the Result enum. What will it print?
Rust
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("division by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(10, 2) {
        Ok(val) => println!("Result is {}", val),
        Err(e) => println!("Error: {}", e),
    }
}
ACompilation error
BError: division by zero
CResult is 0
DResult is 5
Attempts:
2 left
💡 Hint
Check what happens when dividing 10 by 2 and how the match handles Ok and Err.
❓ Predict Output
intermediate
2:00remaining
What error message does this code produce?
Look at this Rust code using Result. What error message will it print?
Rust
fn parse_number(s: &str) -> Result<i32, String> {
    s.parse::<i32>().map_err(|_| String::from("parse error"))
}

fn main() {
    match parse_number("abc") {
        Ok(n) => println!("Number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}
ANumber: 0
BError: parse error
CCompilation error
DError: invalid digit found in string
Attempts:
2 left
💡 Hint
The string "abc" cannot be parsed as a number, so the error branch runs.
🔧 Debug
advanced
2:00remaining
Why does this Rust code cause a compilation error?
This Rust code tries to unwrap a Result but causes a compilation error. Why?
Rust
fn get_value(flag: bool) -> Result<i32, String> {
    if flag {
        Ok(42)
    } else {
        Err("no value".to_string())
    }
}

fn main() {
    let val = get_value(true).unwrap_or("default");
    println!("Value: {}", val);
}
AThe error string "no value" is not valid syntax
Bunwrap_or cannot be used on Result, only on Option
Cunwrap_or expects the same type as Ok, but "default" is a string, causing a type mismatch
DThe function get_value returns a Result but unwrap_or is missing parentheses
Attempts:
2 left
💡 Hint
Check the type expected by unwrap_or and the type of the argument passed.
❓ Predict Output
advanced
2:00remaining
What is the output of this Rust code using ? operator with Result?
Analyze this Rust code that uses the ? operator with Result. What will it print?
Rust
fn try_divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err("division by zero".to_string())
    } else {
        Ok(a / b)
    }
}

fn main() {
    let result = try_divide(10, 0).unwrap_or_else(|e| {
        println!("Error handled: {}", e);
        -1
    });
    println!("Result: {}", result);
}
A
Error handled: division by zero
Result: -1
BResult: 0
CError handled: division by zero
DCompilation error
Attempts:
2 left
💡 Hint
The ? operator is not used here, but unwrap_or_else handles the error case.
🧠 Conceptual
expert
2:00remaining
How many times is the closure executed in this Rust code using Result and map_err?
Consider this Rust code snippet. How many times will the closure inside map_err be executed?
Rust
fn main() {
    let res: Result<i32, &str> = Err("fail");
    let new_res = res.map_err(|e| {
        println!("Handling error: {}", e);
        "handled"
    });
    let final_res = new_res.map_err(|e| {
        println!("Second handler: {}", e);
        "final"
    });
}
A2 times
B1 time
C0 times
D3 times
Attempts:
2 left
💡 Hint
Each map_err runs only if the Result is Err. The Result stays Err after the first map_err.

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