How does Rust handle errors with Result and Option, and when is it appropriate to panic instead?
technical-conceptual · Junior level · software-engineering
What the interviewer is really asking
Probes whether the candidate distinguishes recoverable errors handled in the type system from unrecoverable panics, and knows idiomatic propagation.
What to say
- Explain that Rust models recoverable failure in the type system: Result<T, E> is Ok or Err for operations that can fail, and Option<T> is Some or None for a value that may be absent, so the caller is forced to handle both cases.
- Describe idiomatic propagation: the ? operator unwraps an Ok/Some or returns the Err/None early from a function whose return type allows it, which keeps the happy path readable without nested match blocks.
- Draw the line for panic: reserve panic! (and unwrap/expect) for unrecoverable bugs or invariant violations like an index out of bounds, not for ordinary expected failures such as a missing file or bad user input.
What to avoid
- Treating unwrap() as the normal way to get a value out of a Result in production code; it converts every error into a crash.
- Saying Result and exceptions are the same thing; Rust has no exception unwinding for recoverable errors, the error is a value you must handle.
- Claiming you should panic on any error because it's simpler, ignoring that libraries should return errors and let the caller decide.
Example answers
Strong: Result<T, E> represents something that can fail with Ok or Err, and Option<T> represents a value that might be missing with Some or None, so the compiler makes me handle both. To propagate I use the ? operator, which returns the error early if it's Err and otherwise gives me the value, keeping the code flat. I only panic for real bugs, like an invariant being broken, and return a Result for expected failures like a file not existing.
Weak: If something might fail you wrap it in a Result, and then you call .unwrap() to get the value out. If it errors it just crashes, which is usually fine because it tells you something went wrong. Option is similar but for nulls.