Core Rust Questions · 13 min · free lesson

Option vs Result

Pick the type that matches what the caller must decide.

Core idea

Option: absence is normal. Result: the caller needs the reason.

Lesson map: a port lookup that sends a missing key and a bad number to separate error strings, above the rule of Option for normal absence and Result for a reason.
Missing configuration and an invalid number reach different explicit error paths.

Understand it

Option says a value may be absent and that is unremarkable. Result says an operation failed and carries why. Converting between them is routine — ok_or turns absence into an error when the caller does need a reason.

Choose the enum according to the decision the caller must make. Option<T> represents an ordinary absence: a lookup may find no element. Result<T, E> represents a success or a failure whose reason is useful: parsing text can fail because the input is malformed. These meanings affect error messages, retries, and control flow. unwrap() removes the branch by panicking when the other variant appears, so it is a poor default at a user-input boundary.

Give a layered example. A cache lookup can return Option<Value>. If a missing key is normal, the caller may supply a default. If a required key is absent, the caller can use ok_or_else to turn None into a domain error. A database lookup can return Result<Option<Value>, DbError> because 'not found' and 'database unavailable' are different outcomes. Collapsing both to None hides the operational failure.

For an interview answer, describe the successful type and each alternative with a real caller action. Match when the current layer can recover; use ? to propagate an error when a higher layer owns the decision. Add context at the boundary where you know which operation failed. Avoid saying Result is always better because it carries more information. Extra information is useful only when the domain actually has a failure to explain.

If a caller needs both absence and a possible infrastructure failure, Result<Option<T>, E> can be clearer than inventing a sentinel error. Explain which layer turns None into an error, if any.

Interview follow-up: How would Result<Option<T>, E> distinguish absence from failure? Explain how transpose changes the nesting.

Read the code

use std::collections::HashMap;
fn port(config: &HashMap<&str, &str>) -> Result<u16, String> {
    config.get("port")
        .ok_or_else(|| "port is missing".to_owned())?
        .parse()
        .map_err(|_| "port is not a u16".to_owned())
}
fn main() {
    assert_eq!(port(&HashMap::from([("port", "8080")])), Ok(8080));
}

Missing configuration and an invalid number reach different explicit error paths.

Practice starter

fn main() {
    let value: Option<u32> = Some(7);
    let result = value.ok_or_else(|| String::from("missing"));
    assert_eq!(result, Ok(7));
}

Practise this code in Playground ↗

Try it

Choose between Option and Result for two APIs and justify each.

What success looks like: Each choice is explained by what the caller needs to know.

Check your understanding

Which conversion produces a Result and computes the error only for None?

Reveal the answer
  1. unwrap_or_else preserves the Option in a new Result wrapper.
  2. ok_or_else supplies a lazily constructed error for an absent value.
  3. map_err transforms the error already stored inside an Option.

Option has no error payload. ok_or takes an error value; ok_or_else takes a closure. A missing value can be normal or erroneous depending on the API.

Go deeper

Common misconception: map_err transforms the error already stored inside an Option.

Option stores no error, and map_err is a Result method. Use ok_or_else to create the error first; map_err can then transform it.

  1. Identify the contract: Pick the type that matches what the caller must decide.
  2. Trace the concrete example: Missing configuration and an invalid number reach different explicit error paths.
  3. Test the changed constraint: How would Result<Option<T>, E> distinguish absence from failure? Explain how transpose changes the nesting.

Transfer challenge: How would Result<Option<T>, E> distinguish absence from failure? Explain how transpose changes the nesting.

Connections

  • Lifetime Reasoning: Relationships, not object duration
  • Send and Sync: Thread-safety marker traits
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Option vs Result (courseId "interview", lessonId "q-option-result")
Link: https://crabrix.com/learn/interview/q-option-result/
Goal: Option: absence is normal. Result: the caller needs the reason.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-option-result) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.