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.
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.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.