
Recall first from Panics and the Result type
- panic! stops normal execution in the current thread, and RUST_BACKTRACE=1 requests a backtrace from the default panic hook.
- Result carries either a success value or an error, while Option represents a present or absent value.
- unwrap_or evaluates its fallback eagerly, while unwrap_or_else calls its fallback only when needed.
Propagating a failure with `?`
4 min readYou saw Result and Option as the error types. This lesson answers how the question-mark operator propagates errors and how combinators chain them.
An embedded Linux program that loads a sampling interval at startup has to account for a missing settings file. Linux documents this case as ENOENT in open(2). Even when the file can be read, its contents may fail to parse as an integer. If the program requires that setting, the startup code should return the failure before it prints or uses the interval. Rust lets the same function describe both checks in the order they happen.
use std::error::Error;
use std::fs;
fn read_interval(path: &str) -> Result<u32, Box<dyn Error>> {
let text = fs::read_to_string(path)?;
let interval = text.trim().parse::<u32>()?;
Ok(interval)
}
The first ? acts on the Result returned by read_to_string. With Ok(text), the expression yields the String and execution reaches the parse. With Err(error), read_interval returns an Err immediately, so execution skips both the parse and Ok(interval). The parse uses the same rule. Its Ok yields a u32, and its Err ends the function. On the success path, the last expression wraps the interval in Ok to match the function’s declared return type.
Read the ? as applying to the expression immediately before it. In text.trim().parse::<u32>()?, trim() supplies a string slice to parse. The question mark then handles the Result from parse. The binding interval therefore has type u32. The distinction also matters at the end of a function. If the last operation already returns the exact Result the caller should receive, you can return that expression directly. If you need its successful value for another operation, use ? and construct the final success result after that work.
The read produces a std::io::Error on failure, and the parse produces a std::num::ParseIntError. Both can be converted through From into the declared Box<dyn Error>. The function signature fixes the type of error callers receive, and each ? site needs a compatible conversion even if you expect that operation to succeed. Returning early is an ordinary return. The caller receives the Err and can handle it or use another ? to return it again. A function declared to return u32 has no return value for that early error path, so a Result-based ? there fails to compile.
Going deeperExplore the mechanism
For a Result, this function shows the control-flow equivalent of let text = fs::read_to_string(path)?; using match:
fn read_text(path: &str) -> Result<String, Box<dyn std::error::Error>> {
let text = match std::fs::read_to_string(path) {
Ok(value) => value,
Err(error) => return Err(From::from(error)),
};
Ok(text)
}
The expected return type tells Rust that From::from(error) must produce Box<dyn std::error::Error>. The call converts the error value inside Err. The success arm yields the original String. When the source and destination error types are the same, the identity From conversion passes the error value through.
Choose a From conversion when a source error has the same interpretation wherever it enters the destination type. Choose map_err at the call site when the conversion needs information from the operation, such as the path it tried to read. From::from(error) receives the error value alone. A closure passed to map_err can also use the local path. For example, fs::read_to_string(path).map_err(|error| format!("reading {path}: {error}"))? turns a read error into a String in a function returning Result<_, String>. That representation carries a path and message. Code that needs to inspect the original io::ErrorKind later should retain the original error in its chosen representation.
Using `?` with `Option` and in `main`
3 min readIn a function returning Option<T>, ? yields the value inside Some and returns None immediately when it encounters None. Consider a settings line split at the first equals sign. A helper can return the value for interval_ms when the key matches and the value is present.
fn interval_field(line: &str) -> Option<&str> {
let (key, value) = line.split_once('=')?;
let value = value.trim();
if key.trim() == "interval_ms" && !value.is_empty() {
Some(value)
} else {
None
}
}
split_once('=') yields Some((key, value)) when the separator exists. The ? extracts the pair and the binding destructures it. A line with no separator returns None at that statement. A line with the wrong key or an empty value reaches the explicit None in the else branch. The caller sees absence in all three cases. The helper’s return type deliberately gives callers one outcome for those cases.
When the caller requires the field, turn absence into a Result before applying ?. In a function returning Result<_, &str>, interval_field(line).ok_or("expected interval_ms=value")? yields the slice or returns an Err with that message. The explicit conversion lets the caller choose what a missing field means. Going the other way, .ok() converts a Result to an Option, discarding the error. Use that when the caller handles every failure as absence. Applying ? directly to an Option in a Result function, or to a Result in an Option function, fails to compile.
A command-line program can also give main a return type that supports ?. Put this main in the same source file as the read_interval function from the first section, which already imports Error.
fn main() -> Result<(), Box<dyn Error>> {
let interval = read_interval("sensor.conf")?;
println!("Sample interval: {interval} ms");
Ok(())
}
Here () is the success value because the program’s useful action is printing the interval. The relative path sensor.conf is resolved from the process’s working directory. If the file contains a valid u32 after trimming whitespace, main reaches the print and returns Ok(()). Rust reports a successful exit status. If the read or parse fails, the ? in main returns Err before the print. Rust’s standard handling of a Result from main prints a debug representation of the error to standard error and sets a failure exit status. The parent process can use that status to decide whether the command succeeded, as described by the normal termination interface in exit(3). These are real runs of this program built with rustc 1.100.1 (the exact Os text comes from the operating system):
$ ./target/debug/p4 # sensor.conf missing
Error: Os { code: 2, kind: NotFound, message: "No such file or directory" }
$ echo $?
1
$ echo fast > sensor.conf; ./target/debug/p4
Error: ParseIntError { kind: InvalidDigit }
$ echo $?
1
$ echo 250 > sensor.conf; ./target/debug/p4
Sample interval: 250 ms
$ echo $?
0
The binary name p4 is only the name of the test project.
The two uses of ? operate at different levels. A ? inside read_interval returns control to main with an error value. The ? in main then returns that error from the entry point. If main needs a different policy, such as selecting a default for a missing file, it can handle that case before returning. This is also why a helper can use ? without deciding whether a failure should end the whole program.
Composing results with methods
4 min readA combinator takes a Result and returns a transformed Result. The method you choose says which variant runs the supplied operation and what type comes out. In the interval reader, and_then can parse the file contents only after a successful read. map_err can convert the read and parse errors to a shared type before they meet in the same chain.
fn read_interval_chain(path: &str) -> Result<u32, String> {
std::fs::read_to_string(path)
.map_err(|error| format!("reading {path}: {error}"))
.and_then(|text| {
text.trim()
.parse::<u32>()
.map_err(|error| format!("parsing {path}: {error}"))
})
}
The first map_err changes Result<String, std::io::Error> into Result<String, String>. An Ok still carries the file contents. An Err now carries a message that says which read failed. and_then receives that converted result. On Ok(text) it calls the closure, the expression beginning with |text|, and returns the Result<u32, String> that the closure produces. On Err it forwards the read error without calling the closure. Both paths must have the same error type, so the map_err inside the closure converts the parse error to String as well. On either success path through map_err, the error-formatting code is skipped.
or_else runs a closure only on Err. Use it when the program has an operation that can recover from a particular failure. A policy for optional configuration files might choose a default only when the read reports ErrorKind::NotFound. Apply that policy while the error is still an io::Error, as in this independent read helper:
fn read_optional_settings(path: &str, default: &str) -> std::io::Result<String> {
std::fs::read_to_string(path).or_else(|error| {
if error.kind() == std::io::ErrorKind::NotFound {
Ok(default.to_owned())
} else {
Err(error)
}
})
}
If the read succeeds, or_else passes the file contents through. If the read reports NotFound, the closure returns the default as a successful String. Other read failures are returned to the caller. The function can still fail even though it has a fallback. Parse the returned text afterward so malformed contents from an existing file still produce a parse error. The difference between or_else and map_err is visible in what the closure returns. An or_else closure returns a whole Result, which can be successful. A map_err closure returns a new error value, which the method places inside Err.
You will sometimes encounter Result<Result<T, E>, E> after using map with a fallible operation. map wraps the closure’s return value in Ok on the success path, so a parsing failure in this case is represented by Ok(Err(error)). Call flatten() to remove one level when both error types are E.
fn parse_with_flatten(source: Result<&str, String>) -> Result<u32, String> {
let nested = source.map(|text| {
text.trim()
.parse::<u32>()
.map_err(|error| error.to_string())
});
nested.flatten()
}
flatten() turns Ok(Ok(value)) into Ok(value) and Ok(Err(error)) into Err(error). It passes an outer Err(error) through. It receives an already constructed nested value and runs no parsing closure of its own. In this example source.and_then(...) with the same closure produces the same flat result directly. Result::flatten is a recent addition to the standard library. It compiles on rustc 1.100.1. If an older toolchain reports it as unstable, nested.and_then(|inner| inner) does the same job. When a function hands you a nested result with different inner and outer error types, select a common type and explicitly convert the errors before flattening.
For a startup sequence, use ? where successive statements need successful values. Use and_then when a method chain expresses the dependency directly, or_else for a recovery decision, and map_err where the error needs a local description or type conversion. When reading the code, identify which operation can fail, which code runs after that failure, and what the caller receives. In the settings example, those answers tell you whether the program reports a missing file, uses default text, or reports a bad interval.
The next lesson, “Custom errors and thiserror,” answers how to give callers a named error type for failures such as reading settings and parsing an interval. Once you can trace where each error returns, you can decide what information that type should carry.
Key takeaways
- The ? operator extracts a success value or returns early from its enclosing function or closure.
- On Result, ? converts the error into the enclosing return type’s error type through From.
- A main function returning Result reports Err to standard error and exits with a failure status.
- and_then runs on success, or_else and map_err run on error, and flatten removes one layer of nested Result.
Reflect
- Explain to a colleague, in two sentences: trace the success and early-return paths of ? on Result and Option.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Rust docsThe Rust Book: Recoverable errors with Result (the ? operator)
- Rust docsstd::result::Result
- Rust docsstd::process::Termination
- Man pageopen(2): opening files and missing-path errors
- Man pageexit(3): normal termination and process exit status
Official documentation first. Links checked when the lesson was published.