Start with the idea
A function returning Result<T, E> makes callers handle both success and failure. match is the clearest first tool because both branches stay visible. The ? operator becomes useful once a surrounding function also returns a compatible Result. panic! and expect are better reserved for broken invariants or controlled examples, not routine bad input.
Read the code
fn half(raw: &str) -> Result<i32, String> {
let value = raw.parse::<i32>()
.map_err(|_| "not a number".to_string())?;
Ok(value / 2)
}The caller chooses what an invalid number means for this program.
Practice starter
fn read(raw: &str) -> i32 {
raw.parse().unwrap()
}
Work through it
Imagine a command that reads a port number. The user typing letters is not a broken program; it is an expected input that deserves a useful message and another attempt. Result<T, E> makes that distinction part of the function contract. Ok(value) contains the value to continue with, while Err(error) contains the reason to show, log, or transform. The caller gets to decide whether to retry, choose a default, or stop that operation.
In the example, parse::<i32>() returns a Result. map_err converts the parsing error into a message the API promises to return. The ? operator takes the number from Ok, but returns early from half on Err. It is not a general shortcut for ignoring a failure: the enclosing function must be able to return a compatible error type. Write a match first if the two paths are unfamiliar; once both branches are clear, ? keeps the successful path readable.
Avoid unwrap() on input you do not control. A panic reports a programming defect or a deliberately impossible state; it is a poor response to ordinary bad text. As a small exercise, call half("12") and half("twelve"), printing the successful answer and an actionable error. Then decide whether dividing an odd integer by two should truncate or be rejected. That is a product rule, and the function signature and tests should make the choice visible.
An error message should be useful at the boundary where it is displayed. Deep inside a reusable parser, preserve a structured error when possible; at the UI boundary, add the input context and a concrete suggestion for correction.
A recoverable error is an outcome your caller may need to handle. Result<T, E> contains either Ok(T) or Err(E), and the type makes both possibilities visible. The ? operator returns early from the current function when it sees an Err; it is concise propagation, not a way to ignore failure. The surrounding function must have a compatible return type. Use match when the current layer can make a meaningful decision, such as asking for another input or choosing a fallback.
Trace the example twice: once with valid input and once with invalid input. Mark the first operation that can fail and whether later lines run. Add a message that tells the user what to fix rather than merely printing a debug dump. Avoid unwrap() for normal bad input; reserve it for an invariant you can justify or a deliberate experiment. A good error path leaves the program in a known state and gives the next layer enough context to respond.
Try it
Return a descriptive Result for invalid input and handle it at the caller.
What success looks like: Bad text produces a normal error value, not a panic.
Check your understanding
Why is Result a better return type here?
Reveal the answer
- Invalid external text is an expected possibility
- Result parses faster
- Integers can only be returned inside Result
Let the caller decide how to recover instead of forcing a panic.
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: Handling Failure (courseId "basics", lessonId "recoverable-errors") Link: https://crabrix.com/learn/basics/recoverable-errors/ Goal: Use Result for failure the caller can reasonably respond to. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/recoverable-errors) 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.