The Analogy: The Toll Gantry You Never Slow Down For
You drive under the gantry at full speed. A transponder answers, a light blinks somewhere you cannot see, and nothing else happens -- no barrier, no queue, no ceremony. That is the entire point of the design: the case that works has to cost nothing, because it is the case that happens ten thousand times an hour. If it cost even a five-second stop, the road would not work. The ? operator is that gantry, and the successful case is that invisible: you write one character and the value carries on down the road as though the Result had never been there.
When the transponder does not answer, you are not waved into the next lane. You are diverted onto a slip road that leaves the motorway entirely, and everything you were going to do further along -- the junction, the services, the exit you actually wanted -- simply does not happen. This is the part people underestimate. ? is not a check; it is an exit. Every line below it in the function is skipped, and the function is over.
The interesting engineering is in what arrives afterwards. The gantry's internal fault code is not what lands on your doormat. Somewhere between the roadside and your letterbox, the code is translated into the receiving system's vocabulary: a letter, in your language, referencing your registration. The ? operator does exactly this on the way out -- it converts the error it caught into whatever error type the enclosing function promised to return, using a conversion you wrote once and never think about again.
And a gantry needs a slip road. Put one on a stretch of road with no exit and the design has nowhere to divert to, which is not a fault you want to discover at speed. Rust discovers it at compile time instead: ? in a function that returns nothing is an error, not a surprise, and the message tells you exactly which promise is missing from the signature.
Syntax or Core Structure
Here is the previous lesson's opening program again, unchanged in behaviour, with the propagation written as punctuation.
fn digits(text: &str) -> Result<u32, String> {
match text.parse::<u32>() {
Ok(n) => Ok(n),
Err(_) => Err(format!("{text:?} is not a number")),
}
}
fn doubled(text: &str) -> Result<u32, String> {
let n = digits(text)?;
Ok(n * 2)
}
fn quadrupled(text: &str) -> Result<u32, String> {
let n = doubled(text)?;
Ok(n * 2)
}
fn main() {
for text in ["7", "seven"] {
match quadrupled(text) {
Ok(n) => println!("{text:>7} -> {n}"),
Err(e) => println!("{text:>7} -> error: {e}"),
}
}
}
Output:
7 -> 28
seven -> error: "seven" is not a number
Byte-identical output, and the two four-line propagation blocks became two characters. doubled and quadrupled are now three lines each and say exactly what they do: get the number or leave, then double it.
The desugaring is worth memorising, because every question about ? is answered by it. This:
let n = doubled(text)?;
means this:
let n = match doubled(text) {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
};
Three things follow immediately. ? evaluates to the value inside Ok, so it is an expression and can appear anywhere a value can. On Err it returns from the enclosing function, not from the expression or the loop. And it calls From::from on the error, which is why the previous lesson spent time on From -- when the two error types are the same, the standard library's identity impl makes that a no-op, and when they differ, your impl runs.
(The real machinery is the Try and FromResidual traits, which is how ? also works on Option. Implementing them for your own types is still unstable, so the desugaring above is the useful mental model rather than the literal one. The operator replaced an older macro called try!, which is why try is a reserved word and cannot be used as an identifier.)
Technical Depth: One Character, Two Traits, Several Rules
| The expression | If Ok(v) or Some(v) | If Err(e) or None |
|---|---|---|
expr? inside -> Result<T, F> | evaluates to v | returns Err(F::from(e)) from the function |
expr? inside -> Option<T> | evaluates to v | returns None from the function |
expr? inside -> () | does not compile | -- |
The conversion doing real work
One function, two failing calls, two unrelated error types from the standard library, one return type. The two From impls are the whole reason the two ? marks are legal.
use std::num::{ParseFloatError, ParseIntError};
#[derive(Debug)]
enum MixError {
Int(ParseIntError),
Float(ParseFloatError),
}
impl From<ParseIntError> for MixError {
fn from(cause: ParseIntError) -> MixError {
MixError::Int(cause)
}
}
impl From<ParseFloatError> for MixError {
fn from(cause: ParseFloatError) -> MixError {
MixError::Float(cause)
}
}
fn scaled(count: &str, factor: &str) -> Result<f64, MixError> {
let n: u32 = count.parse()?;
let f: f64 = factor.parse()?;
Ok(n as f64 * f)
}
fn describe(e: &MixError) -> String {
match e {
MixError::Int(cause) => format!("count: {cause}"),
MixError::Float(cause) => format!("factor: {cause}"),
}
}
fn main() {
let cases = [("6", "1.25"), ("six", "1.25"), ("6", "one point two")];
for (count, factor) in cases {
match scaled(count, factor) {
Ok(v) => println!("{count:>4} x {factor:<14} = {v}"),
Err(e) => println!("{count:>4} x {factor:<14} ! {}", describe(&e)),
}
}
}
Output:
6 x 1.25 = 7.5
six x 1.25 ! count: invalid digit found in string
6 x one point two ! factor: invalid float literal
Delete either From impl and the corresponding ? stops compiling with E0277, saying the trait bound is not satisfied. That is the cleanest way to think about the operator: ? is only as capable as the conversions you have provided, and every one you provide makes one more call site collapse to a single character.
? on Option
The same operator, the same early exit, no conversion involved -- None is None.
fn first_word(text: &str) -> Option<&str> {
let word = text.split_whitespace().next()?;
Some(word)
}
fn initial(text: &str) -> Option<char> {
let word = first_word(text)?;
let c = word.chars().next()?;
Some(c.to_ascii_uppercase())
}
fn main() {
for text in ["hello world", " ", "rust"] {
match initial(text) {
Some(c) => println!("{text:?} -> {c}"),
None => println!("{text:?} -> nothing"),
}
}
}
Output:
"hello world" -> H
" " -> nothing
"rust" -> R
Three ? marks across two functions, and initial never mentions the word None. The middle case exits at the first one, inside first_word, because split_whitespace on a string of spaces yields nothing at all.
Crossing between Option and Result
What you cannot do is mix them. An Option inside a function returning Result will not take a ?, because there is no error to convert -- None carries nothing. You have to supply one, and ok_or is the adapter that does it.
use std::error::Error;
fn port(line: &str) -> Result<u32, Box<dyn Error>> {
let eq = line.find('=').ok_or("no '=' in the line")?;
let key = line[..eq].trim();
if key != "port" {
return Err(format!("expected key port, got {key:?}").into());
}
let n: u32 = line[eq + 1..].trim().parse()?;
Ok(n)
}
fn main() {
for line in ["port = 8080", "port=80", "host = local", "8080"] {
match port(line) {
Ok(n) => println!("{line:>13} -> {n}"),
Err(e) => println!("{line:>13} ! {e}"),
}
}
}
Output:
port = 8080 -> 8080
port=80 -> 80
host = local ! expected key port, got "host"
8080 ! no '=' in the line
Three different things became a Box<dyn Error> in that function without a single From impl written by hand. The &str from ok_or converted because the standard library has an impl for it; the String converted through .into() for the same reason; and the ParseIntError converted because any type implementing the Error trait can be boxed. That convenience is exactly why Box<dyn Error> is so common in binaries, and exactly why it is a poor choice on a library's public signature -- the caller receives something they can print and cannot inspect.
Going the other way is easier: .ok() throws the error away and hands you an Option, so some_result.ok()? is the idiom inside a function returning Option.
Where ? cannot go
| Context | What you get |
|---|---|
a function returning () | E0277, saying ? needs a function returning Result or Option |
fn main() with no return type | the same error; change the signature |
a Result in a function returning Option | E0277; use .ok()? to discard the error |
an Option in a function returning Result | E0277; use .ok_or(value)? to supply one |
a Result<T, A> where the function returns Result<T, B> and no From<A> for B exists | E0277 on the trait bound; write the impl or convert by hand |
| inside a closure | it compiles, and returns from the closure -- see Module 7 |
main can take a ? too
Give main a Result return type and the top level of a program stops needing unwrap.
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let n: u32 = "8080".parse()?;
println!("port {n}");
let bad: u32 = "80O80".parse()?;
println!("never printed: {bad}");
Ok(())
}
Output:
port 8080
Error: ParseIntError { kind: InvalidDigit }
The runtime prints Error: followed by the Debug form of whatever came back and exits with status 1 -- the same 1 the Result lesson measured, and not the 101 a panic produces. This is the cheapest possible improvement to a small program: the failure is reported, the exit status is right, and nothing was unwrapped. The trailing Ok(()) is easy to forget and the compiler will remind you.
What ? does not do
It does not add context, and this is its one real cost. Every ? in a function produces an error that looks identical to every other ? producing the same type, so if three parse calls in one function can each fail with ParseIntError, the caller learns that a number was bad and not which one. The previous lesson's hand-written return Err(...) blocks were verbose precisely because they were attaching that information. Choosing ? is choosing brevity over provenance, and the right move is to use it everywhere and then convert by hand at the two or three sites where the ambiguity actually matters.
It also does not log, does not retry, and has nothing to do with panics -- a ? cannot catch one and a panic will not be turned into an Err. And it is not exception handling in disguise: the function's signature still announces that it can fail, every caller is still forced to deal with the Result, and there is no invisible propagation through functions that did not opt in.
Real World Example: A Booking Request, Validated End To End
A booking arrives as one line: date | time | party size | seating. Almost every step of reading it can fail, which makes it a fair test of how much ? actually removes.
use std::num::ParseIntError;
#[derive(Debug)]
enum BookingError {
WrongFieldCount { got: usize, want: usize },
Number(ParseIntError),
Month(u32),
Day(u32),
Hour(u32),
Minute(u32),
PartySize(u32),
UnknownSeating(String),
}
impl From<ParseIntError> for BookingError {
fn from(cause: ParseIntError) -> BookingError {
BookingError::Number(cause)
}
}
enum Seating {
Window,
Booth,
Bar,
}
struct Booking {
year: u32,
month: u32,
day: u32,
hour: u32,
minute: u32,
party: u32,
seating: Seating,
}
fn numbers(text: &str, sep: char, want: usize) -> Result<Vec<u32>, BookingError> {
let mut raw: Vec<&str> = Vec::new();
for part in text.split(sep) {
raw.push(part.trim());
}
if raw.len() != want {
return Err(BookingError::WrongFieldCount {
got: raw.len(),
want,
});
}
let mut out = Vec::new();
for part in raw {
out.push(part.parse()?);
}
Ok(out)
}
fn seating_of(text: &str) -> Result<Seating, BookingError> {
match text {
"window" => Ok(Seating::Window),
"booth" => Ok(Seating::Booth),
"bar" => Ok(Seating::Bar),
other => Err(BookingError::UnknownSeating(other.to_string())),
}
}
fn booking(request: &str) -> Result<Booking, BookingError> {
let mut fields: Vec<&str> = Vec::new();
for field in request.split('|') {
fields.push(field.trim());
}
if fields.len() != 4 {
return Err(BookingError::WrongFieldCount {
got: fields.len(),
want: 4,
});
}
let date = numbers(fields[0], '-', 3)?;
let time = numbers(fields[1], ':', 2)?;
let party: u32 = fields[2].parse()?;
let seating = seating_of(fields[3])?;
let (year, month, day) = (date[0], date[1], date[2]);
let (hour, minute) = (time[0], time[1]);
if month == 0 || month > 12 {
return Err(BookingError::Month(month));
}
if day == 0 || day > 31 {
return Err(BookingError::Day(day));
}
if hour > 23 {
return Err(BookingError::Hour(hour));
}
if minute > 59 {
return Err(BookingError::Minute(minute));
}
if party == 0 || party > 12 {
return Err(BookingError::PartySize(party));
}
Ok(Booking {
year,
month,
day,
hour,
minute,
party,
seating,
})
}
fn show(b: &Booking) -> String {
let seat = match b.seating {
Seating::Window => "window",
Seating::Booth => "booth",
Seating::Bar => "bar",
};
format!(
"{}-{:02}-{:02} {:02}:{:02} party of {} at the {seat}",
b.year, b.month, b.day, b.hour, b.minute, b.party
)
}
fn explain(e: &BookingError) -> String {
match e {
BookingError::WrongFieldCount { got, want } => {
format!("{got} parts, expected {want}")
}
BookingError::Number(cause) => format!("not a number: {cause}"),
BookingError::Month(m) => format!("month {m} is not 1-12"),
BookingError::Day(d) => format!("day {d} is not 1-31"),
BookingError::Hour(h) => format!("hour {h} is not 0-23"),
BookingError::Minute(m) => format!("minute {m} is not 0-59"),
BookingError::PartySize(p) => format!("party of {p} is not 1-12"),
BookingError::UnknownSeating(s) => {
format!("seating {s:?} is not window, booth or bar")
}
}
}
fn main() {
let requests = [
"2026-09-04 | 14:30 | 4 | window",
"2026-09-04 | 14:30 | 4 | balcony",
"2026-13-04 | 14:30 | 4 | booth",
"2026-09-04 | 14:70 | 4 | bar",
"2026-09-04 | 14:30 | 40 | bar",
"2026-09-04 | 14:30 | four | bar",
"2026-09-04 | 14:30 | 4",
"2026-9 | 14:30 | 4 | bar",
];
for request in requests {
match booking(request) {
Ok(b) => println!("ok {}", show(&b)),
Err(e) => println!("error {}", explain(&e)),
}
}
}
Output:
ok 2026-09-04 14:30 party of 4 at the window
error seating "balcony" is not window, booth or bar
error month 13 is not 1-12
error minute 70 is not 0-59
error party of 40 is not 1-12
error not a number: invalid digit found in string
error 3 parts, expected 4
error 2 parts, expected 3
Five ? marks across two functions, and not one match written for the purpose of propagating. Two of the five convert -- part.parse()? in numbers and fields[2].parse()? in booking both turn a ParseIntError into a BookingError through the single From impl at the top. The other three are already returning BookingError, so they go through the standard library's identity conversion and cost nothing at all. Compare that with the previous lesson's importer, which spent five lines on a match to forward one error unchanged.
Now look at line six of the output, which is where the bill arrives. not a number: invalid digit found in string is true and almost useless: the request had a party size of four, but the identical message would appear for a bad year, month, day, hour or minute, because all six numbers travel through a ? that converts the same way. Six possible origins, one message. The last two lines have a milder version of the same problem -- 2 parts, expected 3 happens to identify the date only because the date is the field that wants three parts, and changing the time format to hh:mm:ss would make the two indistinguishable.
Fixing it does not mean giving up the operator. It means converting by hand at the sites where the ambiguity is worth a name, and one extra variant is enough to see the shape:
BadField {
field: &'static str,
cause: ParseIntError,
},
let party: u32 = match fields[2].parse() {
Ok(n) => n,
Err(cause) => {
return Err(BookingError::BadField {
field: "party size",
cause,
})
}
};
That one site now reports party size: invalid digit found in string, and the other five ? marks are untouched. Doing it at all six sites would hand back the whole verbosity of the previous lesson, which is why nobody does; the honest answer is map_err, which turns each conversion into one line without a match at all, and which needs closures -- Module 7.
The rest of the honest limits. The range checks all run after every field has been parsed, so a request that is wrong in two ways reports whichever check comes first in the source, and that priority order is a real design decision that nothing in the code documents. Day 31 in February is accepted, because these are range checks and not a calendar; a real validator needs a date library and would also have to decide what "valid" means for a booking two years out. numbers allocates two Vecs to handle at most three integers, which is only tolerable because this runs once per request rather than once per row of a large file. And the format is positional, so adding a fifth field breaks every request already in flight -- WrongFieldCount will report it accurately and nobody will thank you.
Common Mistakes
?in a function that returns(). The error names the problem exactly, and the fix is a signature, not a workaround. Reaching forunwrapinstead is how a propagation chain gets broken at its last link.
?on anOptionin a function returningResult. There is no error to convert..ok_or(value)?supplies one;.unwrap()supplies a panic instead.
- Expecting
?to record where it fired. It does not. Five?marks converting the same error type produce five indistinguishable results, and only you can decide which of them deserves a name.
- Treating
?as try-catch. It cannot catch a panic, it does not unwind, and it propagates only through functions that opted in by declaring aResultreturn type.
?inside a closure, expecting it to leave the enclosing function. It returns from the closure. The compiler usually catches this as a type error, and the message points at the closure rather than at your intent.
- Adding
?and forgetting the trailingOk(()). The function body no longer ends in an expression of the right type, and the error appears at the closing brace rather than where you were working.
- Choosing
Box<dyn Error>for a library because it makes?compile. It does, and it also tells every caller that inspecting the failure is not supported. Pick the error type from the caller's needs, then make?work withFrom.
- A function whose error type is
String, expectingparse()?to work. There is noFrom<ParseIntError> for String, so it will not compile -- which is the compiler pointing out that a string is not an error type.
- A stray
.unwrap()in a function that is otherwise all?. The signature already promises to propagate; the unwrap is one line that can still take the process down, and it will be the line nobody reads.
Best Practices
- Use
?for every propagation that adds nothing. If the block you are about to write would take a value out of oneResultand put it into an identical one, it is a?.
- Write one
Fromimpl per leaf error type your module has to absorb, once, near the enum. Every call site afterwards is a single character.
- Give
mainaResultreturn type in any binary bigger than a scratch file. You get a printed error and a correct exit status for the price of oneOk(()).
- Reach for
.ok_or(...)at theOptiontoResultboundary and.ok()going the other way, rather than unwrapping to get past a type mismatch.
- When two or more
?sites in one function can produce the same error, convert one of them by hand so the message can tell them apart. Do it where the ambiguity actually costs someone time.
- Keep the number of
?marks in a single expression low enough to read.a()?.b()?.c()?has three exits and one line number.
- Choose the error type from what the caller needs to do, then make
?work with it. Letting the operator pick your types is howBox<dyn Error>ends up in a public API.
- Put the range and validity checks as close to the parse as you can bear. Parsing everything first and validating afterwards makes the priority of the error messages an accident of statement order.
Practice Exercises
- Add the
BadFieldvariant sketched above toBookingErrorand use it for both the party size and the hour, so that a bad hour reportshourand a bad party size reportsparty size. Then say whatnumberswould need to change for a bad month to reportmonth.
- Rewrite
initialso it returnsResult<char, String>instead ofOption<char>, keepingfirst_wordas it is. Useok_orfor both failure points and give each a different message, then explain why the?infirst_worddid not have to change.
- Give
scaleda third step that divides by a parsedu32and returns an error when that number is zero, without adding a thirdFromimpl. Say which of the two available techniques you used and why the other one would not work here.
- Take the
portfunction and replaceBox<dyn Error>with a named three-variant enum, adding whateverFromimpls the three?and.into()sites need. Then write down one thingmaincan do with the new type that it could not do with the box.