skip to content

A Rust doc example using ? fails cargo test with E0277; how does rustdoc wrap it, and how do hidden # lines fix it?

level: middleimportance: must knowfreq 45%

answer

  1. an implicit fn main
  2. main returns unit
  3. lines starting with #
  4. Ok::<(), E>(()) at the end

basics

~20 s

Rustdoc wraps an example lacking fn main in fn main() { ... }, which returns (), so ? cannot return an error. Add a hidden # fn main() -> Result<(), E> { with # Ok(()) and # }, or end with a hidden Ok::<(), E>(()).

solid answer

~40 s

Each Rust code block in a library's doc comments becomes a doctest: rustdoc compiles it as its own small program linked against the library, and it passes if it compiles and runs without panicking. Before compiling, rustdoc adds some `allow` lints, inserts `extern crate logfilter;`, and wraps the text in `fn main() { ... }` unless the example already contains `fn main`. That `main` returns `()`, so `?` fails with E0277. Lines starting with `# ` are compiled but hidden from the rendered docs, so you write a hidden `fn main() -> Result<(), ParseLevelError>` plus a hidden `Ok(())`. Alternatively end with `# Ok::<(), ParseLevelError>(())`: rustdoc then makes `main` return a `Result`, and the turbofish names the error type that `?`'s conversion leaves ambiguous.

code

rust · 35 lines
rust
/// The error returned for an unknown level name.
#[derive(Debug, PartialEq)]
pub struct ParseLevelError(pub String);

#[derive(Debug, PartialEq)]
pub enum Level {
    Info,
    Warn,
}

/// Parses a level name, ignoring ASCII case.
///
/// ```
/// use logfilter::{parse, Level};
/// # fn main() -> Result<(), logfilter::ParseLevelError> {
/// let min = parse("WARN")?;
/// assert_eq!(min, Level::Warn);
/// # Ok(())
/// # }
/// ```
///
/// The same idea without a hidden `fn main`:
///
/// ```
/// let min = logfilter::parse("info")?;
/// assert_eq!(min, logfilter::Level::Info);
/// # Ok::<(), logfilter::ParseLevelError>(())
/// ```
pub fn parse(name: &str) -> Result<Level, ParseLevelError> {
    match name.to_ascii_lowercase().as_str() {
        "info" => Ok(Level::Info),
        "warn" => Ok(Level::Warn),
        _ => Err(ParseLevelError(name.to_string())),
    }
}

go deeper

for a junior

Recall that code blocks in doc comments run as tests under cargo test, and that lines starting with # are hidden from the docs but still compiled.

for a middle

Walk through rustdoc's wrapping in fn main, why ? then fails with E0277, and the two fixes: a hidden Result-returning main or a final Ok::<(), E>(()).

for a senior

Keep examples honest: assert results, hide only setup, and remember doctests see the public API only, so a failing example often means a missing pub.

for a principal

Treat doc examples as tested contracts of the public API, and set the expectation that every fallible public function shows a ? example.

## What a doctest is A **doctest** is a code block in a documentation comment (`///` or `//!`) that rustdoc compiles and runs as a test. `cargo test` runs them in a `Doc-tests <crate>` section after the unit and integration tests. A block with no language tag, or tagged `rust`, counts as Rust. - A doctest **passes** if it compiles and runs without panicking, so `assert_eq!` is how an example states its expected result. - Doctests are collected from the **library target** only. - The example is compiled as a **separate crate** that links the library, so it sees only **public** items; calling a private helper fails with E0603. ## How rustdoc preprocesses an example rustdoc does not compile the block verbatim. Its documented steps are: 1. Insert common `allow` attributes such as `unused_variables` and `dead_code`. 2. Add any attributes set with `#![doc(test(attr(...)))]` in the crate. 3. Keep leading `#![...]` lines as crate attributes. 4. Insert `extern crate <mycrate>;` unless the example has its own `extern crate` line or the crate set `#![doc(test(no_crate_inject))]`. 5. If the text does not contain `fn main`, wrap the rest in `fn main() { your_code }`. Step 5 is why short examples need no boilerplate, and also why `?` breaks. ## Why ? fails with E0277 The `?` operator returns early with the error, so the enclosing function must return a `Result` or `Option`. The implicit `fn main()` returns `()`, so an example like `let min = logfilter::parse("info")?;` fails with: `error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)` The rules for `?` and `main` returning `Result` belong to the material on the question-mark operator; what is specific to doctests is how to supply that `main` without cluttering the docs. ## Hidden lines A line in the example that starts with `# ` (hash, space) is **compiled but not rendered** in the generated documentation. That lets setup code stay out of sight: - `# fn main() -> Result<(), logfilter::ParseLevelError> {` opens a hidden `main` that returns `Result`; - the visible lines show the call with `?`; - `# Ok(())` and `# }` close it, also hidden. The reader sees three clean lines; the compiler sees a full program. A line that really must begin with `#`, such as a line of a multi-line string, is written with `##` so the first hash is consumed as an escape. ## The shorter form without fn main rustdoc also accepts an example that **ends with** a hidden `Ok::<(), E>(())`. When it sees that ending, it makes the implicit `main` return a `Result`. Two details matter: - The error type must be **named**. `?` converts errors with `From`, so a bare `Ok(())` leaves the error type ambiguous; on rustc 1.99.1 `# Ok(())` alone failed with E0282, type annotations needed. - The `(())` must be written **without spaces**; `Ok::<(), E>( () )` is not recognised, and the example fails as if the line were not there. | Ending | Result on rustc 1.99.1 | |---|---| | hidden `fn main() -> Result<(), E>` with `Ok(())` | compiles and runs | | hidden `Ok::<(), E>(())` | compiles and runs | | hidden `Ok(())` only | E0282, type annotations needed | | hidden `return Ok(());` | E0277, and E0308, mismatched types | ## Common mistakes - **Relying on a hidden `fn main` that returns `()`.** Writing `# fn main() {` by hand has the same E0277 problem; the return type must be a `Result`. - **Hiding the point.** If the visible lines no longer show how to call the function, the example documents nothing, even though it passes. - **Printing instead of asserting.** An example that only calls `println!` passes whatever the function returns. - **Reaching for private items.** A doctest that needs a private helper is a sign the example should use the public API, or that the check belongs in a unit test. ## Writing examples that stay useful - Prefer `assert_eq!` over `println!`, so the doctest checks something. - Use hidden lines for setup, not for the point of the example. - Use a hidden `main` returning `Result` whenever the example calls a fallible public function; it reads the way callers write real code.

  • Why does the short form need Ok::<(), E>(()) rather than Ok(())?
    `?` converts the error with `From`, so the compiler cannot tell which error type the implicit `main` should return, and a bare `Ok(())` fails with E0282. The turbofish names it. rustdoc also looks for the `(())` written together; with spaces inside, it does not treat the example as Result-returning.
  • Can a Rust doctest call a private helper of the library it documents?
    No. The example compiles as a separate crate that links the library, so only public items are reachable and a private function fails with E0603. Test private helpers from a unit test inside the module instead.
  • How do you show a line that genuinely starts with # inside a doc example?
    Write `##` at the start. rustdoc treats the first `#` as an escape, renders and compiles the line with a single `#`, and does not hide it. It matters for multi-line string literals and for macros that match on `#` tokens.

  • Doctests are compiled inside the library crate, so they can call private functions.
  • Lines starting with # in a doc example are comments that the compiler skips.
  • A doctest passes as long as it compiles, whatever it does when it runs.
  • The ? operator works in doc examples because the test harness returns a Result.
  • Ending an example with a hidden Ok(()) is enough for rustdoc to accept ?.