Adding harness to doctests

Is there a way to tell Rust that the code snippets that doctest finds should be placed inside some kind of harness harness?

Typically I am documenting a library that requires a runtime to be initialized before its functions can be used. Were I to put the runtime initialization code in each and every doctest, I would waste about 20 lines of documentation per function, and I would have to change ALL the doctests the minute the runtime initialization code needs to be changed.

Thanks!

I don't think so. There is the default "harness" that does a few things like wrapping your code inside a fn main() { ... } if your doctest doesn't have a main function.

If you look at the tokio[1] API docs, you will notice that their examples are quite verbose and contain the initialization of the runtime in each doctest. Personally I think that is actually quite helpful for understanding what is going on and what is required of me, the user.

If you find the process of writing the initialization for your runtime in each doctest too bothersome, maybe you could discuss the possibility of adding a feature that allows customizing the pre-processing of doctests with the rustdoc team?


  1. Itself a runtime similar to what you are describing ↩ī¸Ž

1 Like

You could write a helper function so that the 20 lines of initialization become 1. You could then hide it in the doc-test with the leading "# " that makes a line hidden.

#[doc(hidden)]
fn initialize_runtime_for_example() -> Runtime { ... }

/// Blah blah blah...
///
/// ```
/// # let runtime = initialize_runtime_for_example();
/// runtime.do_thing();
/// ```
impl Runtime {
    fn do_thing(&self) ...
}

However, I would suggest not actually hiding the initialization, but doing what you can to make it shorter in a way users of your library can actually use in their own programs. This means that users get to see how the example actually works (as @jofas mentioned already), and arranging for it to be shorter will help any users writing quick experimental programs.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.