Sub topic 11
Using ? and Result in doc tests
This chapter assumes you can write /// comments, run cargo test --doc, and hide lines with # . You should also know how ? and Result work in ordinary Rust code.
Why ? fails in a plain example
Rustdoc wraps your example in a generated fn main() { ... }. That main returns (), so the ? operator has nowhere to send an error. This example does not compile as a doc test:
use std::num::ParseIntError;
/// Parses a decimal port number.
///
/// ~~~
/// # use mycrate::parse_port;
/// let port = parse_port("8080")?;
/// assert_eq!(port, 8080);
/// ~~~
pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse()
}The doc comment above uses ~~~ fences so the example can sit inside this chapter's code block. Rustdoc accepts ~~~ the same way it accepts three backticks. In real source files, either form works.
The compiler reports that ? can only be used in a function that returns Result or Option. The fix is to make the generated main return a Result.
Ending the example with Ok
Rustdoc checks whether the last line of the example is an Ok(...) expression. If it is, rustdoc generates a main that returns Result, and ? works.
use std::num::ParseIntError;
/// Parses a decimal port number.
///
/// # Errors
///
/// Returns [`ParseIntError`] if `s` is not a valid `u16`.
///
/// # Examples
///
/// ~~~
/// # use mycrate::parse_port;
/// let port = parse_port("8080")?;
/// assert_eq!(port, 8080);
/// # Ok::<(), std::num::ParseIntError>(())
/// ~~~
pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse()
}The last line starts with # , so readers do not see it in the rendered docs. They see a clean example that uses ?, which is the pattern you want to teach.
Three details matter:
- The turbofish (
::<(), E>) names the error type. Without it, the compiler cannot inferEand fails with "type annotations needed". Ok(...)must be the last expression, with no trailing semicolon.- If the example returns
Err, the test fails. This is how a?in a doc test can fail a build.
Choosing the error type
Use the concrete error type when the example calls one function with one error type, as above. When the example mixes several error types, use a boxed trait object:
use std::error::Error;
use std::fs;
/// Reads a port number from a file.
///
/// # Examples
///
/// ~~~no_run
/// # use mycrate::read_port;
/// let port = read_port("port.txt")?;
/// println!("{port}");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ~~~
pub fn read_port(path: &str) -> Result<u16, Box<dyn Error>> {
let text = fs::read_to_string(path)?;
Ok(text.trim().parse()?)
}Box<dyn Error> accepts both std::io::Error and ParseIntError through ?. The no_run attribute compiles the example but does not execute it, which suits code that touches the file system.
Alternatives and their costs
| Approach | Result | Drawback |
|---|---|---|
| `# Ok::<(), E>(())` | Visible code stays short | You must remember the turbofish |
| `unwrap()` | No extra line needed | Teaches readers to ignore errors |
| Explicit `fn main() -> Result<(), E>` in the example | Full control | Rustdoc stops wrapping, so the example needs `use` lines and a visible `main`, and it gets longer |
Prefer the hidden Ok line for most examples. Use unwrap() only in short examples where the error case is not the point.
Checking your work
Run only the doc tests with:
cargo test --docA passing example shows ok next to its source line. To see how rustdoc wraps an example, temporarily remove the hidden Ok line and read the compiler error. It names the generated main.
Exercise
A doc example contains let n: i32 = "42".parse()?; and its last line is assert_eq!(n, 42);. The test fails to compile. What single hidden line fixes it, and why does it need a type annotation?
Show answer
Add # Ok::<(), std::num::ParseIntError>(()) as the last line. It makes rustdoc generate a main that returns Result, so ? compiles. The compiler cannot infer the error type from Ok(()) alone, so the turbofish ::<(), ParseIntError> supplies it.