Sub topic 11
Using ? and Result in doc tests
This chapter assumes you can write /// comments and fenced examples, and that you know how ? and Result work in ordinary Rust. It covers why ? fails in a doc test, the fixes, and the edge cases that trip people up.
Why ? fails in a doc test
Examples in documentation should look like real code, and real code propagates errors with ?. Try it in a doc test and the test fails to compile:
/// Parses a decimal port number.
///
/// ~~~
/// let port = mycrate::parse_port("8080")?;
/// assert_eq!(port, 8080);
/// ~~~
pub fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.trim().parse()
}The example fences here use ~~~ because this chapter cannot nest triple-backtick fences. Rustdoc accepts both styles. In your own code, use triple backticks.
cargo test --doc reports an error like "the ? operator can only be used in a function that returns Result or Option". The cause is how rustdoc builds the test. Unless your example defines its own fn main, rustdoc wraps the whole snippet in fn main() { ... }. That main returns (), so ? has nowhere to send an error.
Fix 1: end the example with Ok::<(), E>(())
Rustdoc checks whether the last line of the example ends with (()). If it does, rustdoc wraps the code in a function that returns a Result instead of in a plain main. Your example can then use ?, and an Err fails the test.
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 does two jobs:
- It supplies the
Ok(())the wrapper function must return. - The turbofish
::<(), std::num::ParseIntError>gives the compiler the error type. PlainOk(())leaves that type open, and you get a "type annotations needed" error.
Readers of the rendered docs would see this extra line as noise. To hide it, prefix it with # :
~~~ /// # Ok::<(), std::num::ParseIntError>(()) ~~~
Hidden lines are still compiled. Only the rendered HTML omits them.
Fix 2: write a hidden main that returns Result
The other approach is to write the wrapper yourself. If the example contains fn main, rustdoc uses it as written. Hide the wrapper lines with # so readers see only the useful code:
~~~ /// # fn main() -> Result<(), Box<dyn std::error::Error>> { /// let port = mycrate::parseport(" 443 ")?; /// asserteq!(port, 443); /// # Ok(()) /// # } ~~~
This works because Rust lets main return any type that implements Termination, and Result<(), E> does when E: Debug. If main returns Err, the process exits with a failure status and prints the error with its Debug format. The test fails.
The program below is a standalone equivalent of what the compiler sees. You can run it with cargo run to see the same behavior.
use std::error::Error;
use std::num::ParseIntError;
fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse()
}
fn main() -> Result<(), Box<dyn Error>> {
let port = parse_port(" 443 ")?;
assert_eq!(port, 443);
Ok(())
}Change " 443 " to "http" and the program exits with Error: ParseIntError { kind: InvalidDigit }. A doc test with the same input fails and shows that output.
Choosing between the approaches
| Approach | Lines added to the example | Visible in rendered docs | Best when |
|---|---|---|---|
| `Ok::<(), E>(())` as the last line | 1 | Hidden with `# ` | One error type, short example |
| Hidden `fn main() -> Result<...>` | 3 | Hidden with `# ` | Several error types, or you want `Box<dyn Error>` |
| `.unwrap()` on each fallible call | 0 | Yes, as noise | Quick one-off, not for public APIs |
The Ok::<(), E>(()) form is the common default. Use Box<dyn std::error::Error> as E when the example calls functions with different error types. Every standard error converts into it through ?:
~~~ /// let port: u16 = "8080".parse()?; /// let n: i32 = "-5".parse()?; /// assert_eq!((port, n), (8080, -5)); /// # Ok::<(), Box<dyn std::error::Error>>(()) ~~~
Here u16::from_str and i32::from_str both return ParseIntError, but the same pattern works if one call returns an io::Error.
Edge cases and common mistakes
- Option is not accepted. Returning
Option<()>frommaindoes not compile, becauseOptiondoes not implementTermination. If the example uses anOption, turn it into aResultfirst, for examplemap.get("key").ok_or("missing key")?, and end withOk::<(), &str>(()). - Showing the error path. Do not use
?to demonstrate a failure, because the test would fail. Assert on the result instead:
~~~ /// assert!(mycrate::parseport("http").iserr()); ~~~
Use should_panic only when the function itself panics, as in a # Panics section. An Err value is not a panic.
- Hidden lines and import placement. Hidden lines can appear anywhere, including between visible lines. The compiler sees the lines in the order written, so a hidden
# usemust come before the code that needs it. - Literal
#at the start of a line. If a visible line must begin with#, such as#[derive(Debug)], write##[derive(Debug)]. Rustdoc strips one#and shows the rest.#[is already treated as an attribute, not a hidden line, so this mainly matters for lines like# definein non-attribute text. - Failed doc tests are reported per example. The test name includes the file, the item path, and the line of the opening fence. Use that line number to find the example.
- Reading the error. When an example with the
(())ending fails at run time, the output contains theDebugform of your error. ImplementingDebugwith useful detail makes doc test failures easier to diagnose.
When to use no_run instead
Sometimes an example needs ? and also cannot run, for instance when it opens a network socket or reads a file that does not exist on the test machine. Combine the no_run attribute with the same Result technique. The code is compiled, so the types and the ? usage are still checked, but it is not executed:
~~~norun /// let text = std::fs::readto_string("config.toml")?; /// println!("{} bytes", text.len()); /// Ok::<(), std::io::Error>(()) ~~~
Compare this with ignore, which skips compilation too and lets the example drift out of date unnoticed.
Exercise
A doc test contains let n: u8 = "300".parse()?; followed by Ok::<(), std::num::ParseIntError>(()); (note the semicolon). The test fails to compile with a message about ?. Why, and what is the fix?
Show answer
Rustdoc only switches to a Result-returning wrapper when the example's text ends with (()). The trailing semicolon means the text ends with ;, so rustdoc uses a main that returns (), and ? is not allowed there. Remove the semicolon. Note that the example would still fail at run time, because "300" does not fit in a u8, so the input should also change to a valid value such as "200".
Exercise
You are documenting a function whose example calls "8080".parse::<u16>()? and std::fs::read_to_string("a.txt")?. Which single error type works for the final line, and why is ParseIntError not enough?
Show answer
Use Box<dyn std::error::Error>, as in Ok::<(), Box<dyn std::error::Error>>(()). The two calls fail with different types (ParseIntError and std::io::Error). The ? operator converts each into the boxed trait object through From, but it cannot convert an io::Error into a ParseIntError.
Exercise
Write the lines of a doc test, using # to hide the wrapper, that calls mycrate::parse_port("80")? and asserts the result is 80, by defining your own main that returns a Result.
Show answer
Lines: # fn main() -> Result<(), Box<dyn std::error::Error>> {, then let port = mycrate::parse_port("80")?;, then assert_eq!(port, 80);, then # Ok(()), then # }. Because the example contains fn main, rustdoc uses it as written. Readers see only the two visible lines.