Unwrap / Expect

Unwrap / Expect in Rust: There is a number painted at the end of the bridge and no weighbridge anywhere near it.

The Analogy: The Painted Weight Limit

There is a number painted at the end of the bridge and no weighbridge anywhere near it. Every lorry that crosses does so on the driver's assertion that they are under it. Nobody actually weighs anything, because a scale at every crossing would stop the road working. Most of the time the judgement is sound. When it is not, the failure is immediate, loud and unmistakably located: the deck goes, the lorry is in the river, and nobody has to wonder which bridge it was. That is unwrap -- a claim, and if the claim is false, an instant and perfectly localised collapse.

What separates a sensible crossing from a reckless one is not the number, it is whether anyone can reconstruct the reasoning afterwards. "7.5T" on its own tells an investigator nothing about how the driver decided. A note in the cab reading "empty tanker, 6.2T kerb weight, checked at the depot" tells them precisely which belief turned out to be wrong. That is the whole difference between unwrap() and expect("..."). The panic is identical; what differs is whether the next person to read the wreckage learns what you were thinking. Which is why the message should say why you expected to get across, not that something went wrong.

The road works because drivers exercise judgement, not because they refuse to cross. A codebase with zero unwraps is not automatically better than one with a dozen well-chosen ones. The distinction that matters is between the driver who read the load sheet and the driver who crossed out of habit -- and those two produce identical code, right up until the day they do not.

Finally, the numbers are painted where you can see them. You could drive the whole road in an afternoon and write down every limit, which means the route is auditable. A codebase has exactly the same property: one search for unwrap( produces the complete list of places the program has staked itself on an unproven claim. That auditability is worth protecting, and it is the argument against hiding the same assertion inside a helper called get_config_value -- the risk is unchanged, and now nothing finds it.


Syntax or Core Structure

Both methods do the same thing: hand back the value inside, or panic. They differ only in what the panic says.

fn main() {
    let good: Result<i32, String> = Ok(7);
    println!("unwrap  {}", good.unwrap());

    let good2: Result<i32, String> = Ok(9);
    println!("expect  {}", good2.expect("hard-coded, cannot fail"));

    let some: Option<i32> = Some(4);
    println!("option  {}", some.unwrap());

    let bad: Result<i32, String> = Err(String::from("no digits"));
    println!("about to unwrap an Err");
    let n = bad.unwrap();
    println!("never printed: {n}");
}

Output:

unwrap  7
expect  9
option  4
about to unwrap an Err
thread 'main' panicked at src/main.rs:13:17:
called `Result::unwrap()` on an `Err` value: "no digits"
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Four things are worth reading off that message. It names the method, so you know it was an unwrap and not an index. It names the variant. It prints the Debug form of the error, so the reason is not lost. And the location is your line 13 -- not a line somewhere inside the standard library -- which is a deliberate piece of engineering covered further down.

CallOn successThe panic message on failure
result.unwrap()the Tcalled Result::unwrap() on an Err value: (Debug of the error)
result.expect("msg")the Tmsg: (Debug of the error)
option.unwrap()the Tcalled Option::unwrap() on a None value
option.expect("msg")the Tmsg
result.unwrap_err()panicscalled Result::unwrap_err() on an Ok value: (Debug of the value)
result.expect_err("msg")panicsmsg: (Debug of the value)

Notice the asymmetry. The Result versions append the error's Debug form; the Option versions have nothing to append, because None carries nothing. This has a practical consequence: on a Result, your expect message never needs to restate the error, because the error is already coming along behind it. On an Option, the message is all anyone will ever get.


Technical Depth: What The Two Methods Actually Cost You

The Debug bound, and why it exists

Result::unwrap is not available for every error type. Its signature requires E: Debug, because it has to be able to print the error into the panic message. Try it with a type that has no Debug impl:

struct Opaque;

fn main() {
    let r: Result<i32, Opaque> = Err(Opaque);
    let n = r.unwrap();
    println!("{n}");
}

The compiler refuses to build it with E0277, reporting that Opaque does not implement Debug and cannot be formatted using {:?}, with the caret under the unwrap call. (The full transcript also prints a note: pointing at the trait bound inside Result::unwrap in the standard library, which is why it is described here rather than pasted.) The fix is #[derive(Debug)] on the error type, which is a good enough reason to put that derive on every error type you write and never think about it again.

expect carries the same bound for the same reason. Option::unwrap and Option::expect carry no bound at all, since they have nothing to format.

#[track_caller]: why the location is your line

Without special handling, a panic inside Result::unwrap would report a location inside library/core/src/result.rs. Every unwrap panic in every Rust program would point at the same handful of lines, and the report would be worthless. Both methods are annotated #[track_caller], which tells the compiler to thread the caller's location through and use that in panic!.

You can do this yourself, and you should whenever you write a function that panics on its caller's behalf:

#[track_caller]
fn require_positive(n: i32) -> u32 {
    if n <= 0 {
        panic!("expected a positive number, got {n}");
    }

    n as u32
}

fn main() {
    println!("{}", require_positive(5));
    println!("{}", require_positive(-2));
}

Output:

5
thread 'main' panicked at src/main.rs:12:20:
expected a positive number, got -2
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Line 12 column 20 is the require_positive(-2) call in main. Delete the #[track_caller] line and the same program reports src/main.rs:4:9 instead -- the panic! inside the helper, which is the one location that is identical for every caller and therefore tells you nothing. The attribute costs nothing at runtime unless the panic fires, and it is the difference between a report you can act on and a report you have to run a debugger to interpret.

The recommended message style

The standard library's own documentation is unusually opinionated here: an expect message should describe the reason you expected success, not the failure. Compare the two halves of that advice on a real panic:

fn main() {
    let port: u32 = "8O8O".parse().expect("the port literal is hard-coded above");
    println!("{port}");
}

Output:

thread 'main' panicked at src/main.rs:2:36:
the port literal is hard-coded above: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

(The ParseIntError { kind: InvalidDigit } text is that type's Debug output; the kind field is not part of its public API, so treat the shape as informative rather than something to match on.)

Read the two halves of that line separately. Everything after the colon is the compiler's contribution: something was not a digit. Everything before it is yours, and it says the input was supposed to be a literal -- which immediately points a reader at the literal, where they find 8O8O with two capital letter O characters in it. Had the message been expect("failed to parse"), the whole line would have said "parsing failed: parsing failed", and the reader would still be looking for the input.

The mirror pair: unwrap_err and expect_err

Sometimes the failure is what you are asserting. unwrap_err panics on Ok and hands back the E on Err, which is almost exclusively a testing tool:

fn parse_port(text: &str) -> Result<u32, String> {
    match text.parse::<u32>() {
        Ok(n) if n > 0 => Ok(n),
        Ok(_) => Err(String::from("port 0 is not usable")),
        Err(_) => Err(format!("{text:?} is not a number")),
    }
}

fn main() {
    println!("{}", parse_port("8080").unwrap());
    println!("{}", parse_port("0").unwrap_err());
    println!("{}", parse_port("http").unwrap_err());
}

Output:

8080
port 0 is not usable
"http" is not a number

These require T: Debug rather than E: Debug, for the mirror-image reason. In a test they are strictly better than assert!(result.is_err()), because when the assertion fails, unwrap_err prints the unexpected Ok value and assert! prints only the word false.

When is an unwrap defensible?

Apply the question from the panic lesson -- could a correct caller, doing everything right, still end up here? -- and the answers sort into a fairly stable list.

SituationVerdict
A unit test, or a doc examplefine; a panic is exactly how a test reports failure
A throwaway script or a spikefine, and a later grep will find every one of them
main in a small binaryacceptable, but expect is better because the message survives
A literal you parsed on the same linefine; expect should say the input is a literal
mutex.lock().unwrap()conventional; the Err only happens if a thread already panicked holding the lock
A pattern or template compiled from a literal at startupfine with expect; a broken literal is a bug that shows up on launch
A library function, on the caller's inputalmost never; you are ending their process for your convenience
A request handler or long-running loopno; one bad input takes down more than itself
Right after an is_some() or is_ok() checkit works, but if let says the same thing without the assertion

The mutex row is the one that surprises people, so it is worth spelling out. Mutex::lock returns a Result whose Err means "another thread panicked while it held this lock, so the data behind it may be half-updated". Unwrapping propagates that panic to this thread, which is usually the correct response: the invariant you were about to rely on is already broken. Module 8 comes back to this.

The family that does not panic

The previous lesson introduced these; here they are next to their panicking siblings so the choice is visible in one place.

If the fallback isUse
a constantunwrap_or(value)
computed, and only worth computing on failureunwrap_or_else(closure)
T::default()unwrap_or_default()
the caller's problemreturn the Result -- the next two lessons
genuinely unreachableexpect with the reason written out

Only the last row is an assertion. unwrap_or and its relatives share a prefix with unwrap and nothing else; they cannot panic, and a grep for unwrap that does not account for them will over-report badly.


Real World Example: Auditing Every Unwrap On A Startup Path

Here is a startup routine written the way startup routines usually get written -- quickly, with an unwrap wherever a Result or an Option got in the way. Five of them, numbered in comments so the audit below can refer to each one.

struct Server {
    port: u32,
    workers: u32,
    region: String,
    banner: String,
}

fn build(args: &[&str]) -> Server {
    // 1: the caller supplies this text
    let port: u32 = args[0].parse().unwrap();

    // 2: the caller supplies this text too
    let workers: u32 = args[1].parse().unwrap();

    // 3: a hard-coded literal, right here on this line
    let default_port: u32 = "8080".parse().unwrap();

    // 4: Split always yields at least one piece
    let region = args[2].split(':').next().unwrap().to_string();

    // 5: an optional argument with a fallback
    let banner = args.get(3).copied().unwrap_or("codeacademix").to_string();

    println!("default port would have been {default_port}");

    Server { port, workers, region, banner }
}

fn main() {
    let good = build(&["9000", "8", "eu-west:1a", "edge"]);
    println!(
        "{}:{} x{} banner {:?}",
        good.region, good.port, good.workers, good.banner
    );
    println!();

    let bad = build(&["nine thousand", "8", "eu-west:1a"]);
    println!("{}", bad.port);
}

Output:

default port would have been 8080
eu-west:9000 x8 banner "edge"

thread 'main' panicked at src/main.rs:10:37:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

The happy path works and the program is short, which is exactly why nobody revisits it. So revisit it. For each site, ask whether a caller who is doing everything right can still reach the panic.

SiteReachable by a correct caller?Verdict
args[0], args[1], args[2]yes -- a two-element slice panics before any parsing happensreturn an error
1: args[0].parse().unwrap()yes -- the caller chose the textreturn an error
2: args[1].parse().unwrap()yes -- samereturn an error
3: "8080".parse().unwrap()no -- the input is a literal on the same linekeep, as expect
4: split(':').next().unwrap()no -- Split yields at least one piece, even for an empty stringkeep, as expect
5: unwrap_or("codeacademix")it has no panic in it at allkeep -- a default, not an assertion

Three verdicts, not two. Here is the same routine with the two wrong ones converted, the length check hoisted so the indexing is genuinely safe, and the two defensible ones kept -- one of them now carrying its reason.

#[derive(Debug)]
enum StartupError {
    MissingArgs { got: usize, need: usize },
    BadNumber { field: &'static str, text: String },
}

struct Server {
    port: u32,
    workers: u32,
    region: String,
    banner: String,
}

fn build(args: &[&str]) -> Result<Server, StartupError> {
    if args.len() < 3 {
        return Err(StartupError::MissingArgs {
            got: args.len(),
            need: 3,
        });
    }

    let port: u32 = match args[0].parse() {
        Ok(n) => n,
        Err(_) => {
            return Err(StartupError::BadNumber {
                field: "port",
                text: args[0].to_string(),
            })
        }
    };

    let workers: u32 = match args[1].parse() {
        Ok(n) => n,
        Err(_) => {
            return Err(StartupError::BadNumber {
                field: "workers",
                text: args[1].to_string(),
            })
        }
    };

    let region = args[2]
        .split(':')
        .next()
        .expect("split always yields at least one piece")
        .to_string();

    let banner = args.get(3).copied().unwrap_or("codeacademix").to_string();

    Ok(Server {
        port,
        workers,
        region,
        banner,
    })
}

fn main() {
    let full = ["9000", "8", "eu-west:1a", "edge"];
    let bad_port = ["nine thousand", "8", "eu-west:1a"];
    let bad_workers = ["9000", "many", "eu-west:1a"];
    let too_short = ["9000"];

    let cases: [&[&str]; 4] = [&full, &bad_port, &bad_workers, &too_short];

    for args in cases {
        match build(args) {
            Ok(s) => println!(
                "ok    {}:{} x{} banner {:?}",
                s.region, s.port, s.workers, s.banner
            ),
            Err(StartupError::MissingArgs { got, need }) => {
                println!("error need {need} arguments, got {got}")
            }
            Err(StartupError::BadNumber { field, text }) => {
                println!("error {field} is not a number: {text:?}")
            }
        }
    }
}

Output:

ok    eu-west:9000 x8 banner "edge"
error port is not a number: "nine thousand"
error workers is not a number: "many"
error need 3 arguments, got 1

The audit sorted five sites into three groups rather than two, and the middle group is the interesting one. Sites 1 and 2 parse text the caller supplied, and no amount of care on the caller's part makes that text numeric -- the panic is reachable by someone doing nothing wrong, so it became a returned error. Sites 3 and 4 cannot fail: the input to site 3 is a literal on the same line as the parse, and site 4 relies on a documented guarantee that Split always yields at least one piece, which holds even for the empty string. Site 5 was never an assertion; unwrap_or has no panic in it and appears in the list only because it shares a prefix.

The slice indexing earns its own row even though it contains no unwrap. args[0], args[1] and args[2] each panic on a short slice, with a message about index and length that mentions nothing about arguments -- and they panic before any of the numbered sites, so the first version's real failure mode on a two-element slice was never one of the five things a reader was auditing. It is the same claim an unwrap makes, "I have established this is in range", with none of the searchability. Hoisting one args.len() < 3 check to the top of the function turns three hopeful assertions into one checked precondition, and every index below it is then provably fine.

Notice what the rewrite deliberately did not change. Site 4's unwrap became expect("split always yields at least one piece"), which is not defensive programming -- the panic is exactly as unreachable as before -- it is a note in the cab. The next reader does not have to re-derive the guarantee, and if somebody later replaces split with something that can yield nothing, the message stands there being visibly wrong, which is a much better outcome than a bare unwrap() that silently changes category. Site 5 was left byte for byte identical.

The honest limits. BadNumber carries a &'static str field name, which is free but only works because every field name here is a literal in this function; a config-driven version needs a String and an allocation per error. MissingArgs { got, need } reports counts and not which argument is missing, which is adequate for positional arguments and useless the moment they become named. The two match blocks are eighteen lines doing what the next two lessons will do in two characters. And the audit is a snapshot with no mechanism behind it: the day someone moves the "8080" literal into a configuration file, site 3 changes category and nothing in the code notices -- which is the strongest argument for writing the reason into an expect, because a message claiming the input is hard-coded is self-evidently false the moment it stops being true.


Common Mistakes

  1. Reaching for unwrap as the default while prototyping, then never auditing. The habit is fine; the missing second step is the problem. The grep takes a minute and finds every claim you made in a hurry.
  1. expect("failed to parse"). The message describes the failure, which the error already described. On a Result you get "failed to parse: invalid digit found in string" and have learned nothing. Say why you expected success instead.
  1. Restating the error inside the message. Result::expect appends the error's Debug form automatically. Writing it in yourself gets you the same information twice on one line.
  1. if r.is_ok() { use(r.unwrap()) }. Two operations, one of them an assertion, where if let Ok(v) = r is shorter and asserts nothing. Worse, the check and the unwrap can drift apart during editing.
  1. unwrap in a library, on the caller's input. You are ending someone else's process because handling the error was inconvenient. A library's job is to return the Result and let its caller decide.
  1. unwrap inside a request handler or a long-running loop. One malformed input takes down every other request in flight. The blast radius of a panic is the whole thread, and often the whole process.
  1. Hiding the unwrap inside a helper. fn config(key: &str) -> String that unwraps internally is exactly as dangerous as the unwrap it replaced, and now no search finds it. If a function panics, its name or its documentation should say so.
  1. Writing a panicking helper without #[track_caller]. Every panic then reports the same line inside your helper, and the one fact you needed -- which caller was wrong -- is gone.
  1. Err(e) => panic!("{e:?}") written out by hand. That is expect with more lines, a worse location, and no message. If you have decided to panic, say so in one word and use the word to explain yourself.

Best Practices

  • Prefer expect over unwrap at every site you decide to keep. The cost is a string literal; the return is that the panic explains itself.
  • Write the message as the reason you expected success -- "hard-coded above", "checked non-empty on the previous line", "Split always yields one piece" -- not as a description of the failure.
  • Audit periodically with a search for .unwrap() and .expect(, and treat the count as a number you know rather than one you discover during an incident.
  • Use unwrap freely in tests and doc examples. A panic is how a test reports failure, and an expect message there is a test name in disguise.
  • Put #[derive(Debug)] on every error type you define. unwrap and expect both require it, and you will want it in logs regardless.
  • Add #[track_caller] to any function of yours that panics on its caller's behalf, including assertion helpers and thin wrappers around indexing.
  • Never leave an unwrap on a path that touches untrusted input. That includes anything parsed from a network request, a file, an environment variable or a command line.
  • In tests, assert failure with unwrap_err or expect_err rather than assert!(r.is_err()). When the assertion is wrong, the first prints the unexpected value and the second prints false.

Practice Exercises

  1. Take the five-unwrap build function and add a sixth site: read a timeout from args.get(4) and parse it, defaulting to 30 when the argument is absent but reporting an error when it is present and not a number. Explain in a comment why unwrap_or(30) on the parse result would be the wrong tool here.
  1. Rewrite these four messages so each states an expectation rather than a failure, and say for each one what a reader learns from your version that they did not learn from the original: expect("parse error"), expect("no value"), expect("lock failed"), expect("bad config").
  1. Write fn nth_word(text: &str, n: usize) -> &str that returns the nth whitespace-separated word and panics with a message naming both n and the number of words available. Run it twice with an out-of-range index, once with #[track_caller] on the function and once without, and record the two reported locations.
  1. Convert the two match blocks in the rewritten build to use unwrap_or_else so the fallback is computed rather than returned, then explain why the result is worse than the match version -- specifically, what unwrap_or_else cannot do that return Err(...) can.