skip to content

As the lead of a Rust service team, what policy would you set for unwrap, expect and panics in production code, and how would you enforce it?

level: principalimportance: should knowfreq 40%

answer

  1. expected failure versus bug
  2. expect only with a should reason
  3. clippy restriction lints are opt-in
  4. a panic boundary per request
  5. the hook logs, a supervisor restarts

basics

~20 s

Return Result for failures input, I/O or the network can cause; allow expect only for documented invariants with a should message; keep unwrap in tests; enforce with opt-in clippy lints; contain and log the panics that still ship.

solid answer

~40 s

I'd draw the line between expected failures and bugs. Anything driven by input, configuration, I/O or the network returns a `Result`. `expect` is allowed for invariants the compiler cannot see, such as a literal that always parses, with a message saying why it *should* hold, the style std's docs recommend; bare `unwrap` stays in tests, examples and prototypes. Enforcement uses clippy's restriction lints, which are off by default: `unwrap_used`, `expect_used`, `panic` and, if the team wants it, `indexing_slicing`, with `allow-unwrap-in-tests` in `clippy.toml` and a reviewed `#[allow]` on each justified exception. Public functions that can panic say so in a `# Panics` doc section. Because some panic will still ship, the service installs a logging hook, contains panics per request or task, and relies on a supervisor to restart a process that dies.

code

rust · 18 lines
rust
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]

use std::net::Ipv4Addr;

fn listen_port(raw: &str) -> Result<u16, String> {
    raw.parse().map_err(|e| format!("PORT={raw:?} is not a port: {e}"))
}

fn main() {
    // Reviewed exception: the input is a literal, so Err would be a bug in this file.
    #[allow(clippy::expect_used)]
    let bind: Ipv4Addr = "0.0.0.0".parse().expect("literal bind address should parse");

    match listen_port("80a") {
        Ok(port) => println!("listening on {bind}:{port}"),
        Err(e) => eprintln!("config error: {e}"),
    }
}

go deeper

for a junior

Know the house rule your team uses: Result for input and I/O failures, unwrap only in tests, expect only with a clear should message.

for a middle

Explain which clippy lints enforce the rule, that they are opt-in restriction lints, and how test code is exempted through clippy.toml.

for a senior

Review exceptions on their merits, spot unwraps reachable from untrusted input, and make sure panics that do ship are logged and contained per request.

for a principal

Own the trade-off: strict bans that hide bugs behind defaults versus reviewed expects, how the panic strategy changes the stakes, and how containment and restarts back the policy up.

## Start from the distinction A useful policy grows from one sentence the Rust Book and std's own docs agree on: **`Result` is for failures the caller should handle, panics are for bugs**. `Option::unwrap` and `Result::unwrap` are documented as "generally discouraged" because they convert the first kind into the second. In a service that matters more than in a script: a panic on attacker-controlled input is a remote crash, which is why code that parses untrusted messages, in a blockchain node or a game server, should treat "no panic reachable from input" as a security property. The lead's job is to turn that into rules a reviewer can apply in seconds and a tool can check. ## A workable policy 1. **Input, configuration, I/O and the network return `Result`.** No `unwrap` on a parse, a file read or a socket call outside tests. 2. **`expect` is for invariants**, with a message that says why the value *should* be present: `"bind address literal should parse"`. std recommends this "should" style; the message is the reviewer's evidence. 3. **`unwrap` is for tests, examples, benchmarks and prototypes.** A failing `unwrap` is exactly how a test should fail. 4. **Explicit `panic!`, `unreachable!` and `todo!` need the same justification as `expect`.** 5. **Library crates document panics.** A public function that can panic on a contract violation states it in a `# Panics` doc section; it never panics on data that came from outside the program. 6. **Every exception is visible.** A scoped `#[allow(clippy::expect_used)]` on the line, never a crate-wide opt-out. ## Enforcement The checks live in clippy. None of the lints below is in clippy's default set; they are opted into in the crate root or the manifest's lint table: | Lint or setting | Flags | Group | |---|---|---| | `clippy::unwrap_used` | `unwrap()` on `Option` and `Result` | restriction | | `clippy::expect_used` | `expect()` on `Option` and `Result` | restriction | | `clippy::panic` | `panic!` calls | restriction | | `clippy::indexing_slicing` | `v[i]` and slicing that may panic | restriction | | `clippy::missing_panics_doc` | public functions that may panic without a `# Panics` section | pedantic | | `allow-unwrap-in-tests`, `allow-expect-in-tests` | `clippy.toml` keys exempting test code | configuration | `-D warnings` in CI makes the policy binding; the scoped `#[allow]` then marks each reviewed exception in the diff. ## Trade-offs a lead weighs - **Over-banning hides bugs.** Forbid `expect` outright and people write `unwrap_or_default()`, which turns a broken invariant into silently wrong data, which is worse than a crash. - **Impossible error variants.** Mapping every "cannot happen" into an `Err` bloats error enums and hands callers failures they cannot act on. - **`indexing_slicing` is noisy** in numeric and parsing code where indices are correct by construction; many teams enable it only in crates that handle untrusted bytes. - **"No unwrap" is not "no panic".** Indexing, `RefCell` borrows, integer overflow in debug builds and panics inside dependencies remain, so containment still matters. - **The panic strategy changes the stakes.** Under unwind, a panic can be contained to one request; under abort every panic ends the process, so the policy must be stricter and restarts faster. ## Containing what slips through - Install one **panic hook** at startup that writes a structured log line (thread, location, message, backtrace) and chains to the default hook. - Keep a **panic boundary** per request or job, a worker thread whose `join` reports the panic or a `catch_unwind` around the handler, so one bad request returns an error instead of killing the server. Async runtimes report a panicking task through the task's join handle in much the same way. - Count panics as a metric and **alert** on them: each one is a bug report. - Let a **supervisor** restart a process that dies anyway, and treat any panic reachable from external input as a defect to fix, not a case to catch. ## Rolling it out on an existing codebase 1. Enable the lints at **warn** level and count the hits per crate. 2. Triage by **reachability from input**: unwraps on request data, file contents and network replies are fixed first; unwraps on literals become reviewed `expect`s. 3. Switch the crates that parse untrusted data to **deny**, then the rest, so new code cannot reintroduce what was cleaned up.

  • Should a Rust library crate ever panic on input from its caller?
    Only for a documented contract violation where continuing would be wrong, as slice indexing does, and then the function says so in a `# Panics` section. Anything the caller could reasonably get wrong at run time, especially data from outside the program, should come back as a `Result`, so the application decides.
  • Why not ban expect entirely in a Rust codebase and map every impossible case to an error variant?
    Callers cannot act on an error that only a bug can produce, so the variant bloats the API and usually ends up unwrapped somewhere else. A total ban also pushes people towards `unwrap_or_default`, hiding a broken invariant behind plausible data. A reviewed `expect` with a should message is more honest.
  • How does building a Rust service with the abort strategy change an unwrap policy?
    Per-request containment disappears: `catch_unwind` and worker-thread `join` no longer stop a panic, so any panic in any thread ends the process. The policy has to be stricter about panics reachable from input, and the deployment has to restart crashed processes quickly.

  • Replace every unwrap with unwrap_or_default to make the service safe.
  • Clippy flags every unwrap by default, so no configuration is needed.
  • A codebase with no unwrap calls can never panic.
  • expect is acceptable anywhere as long as it has some message.