Documentation (docstrings) with example

I'm writing documentation for a module and I'd like to make it a narrated story, something like:

//! You can easily create a vector with a macro:
//! ```
//! let mut v = vec![1, 2];
//! ```
//! Later you can [`push`] values onto the end of a vector (which will grow the vector
//! as needed):
//!
//! ```
//! v.push(3);
//! ```

I'd like these two snippets to be run as a single test.

I'm sure I have seen that feature described somewhere a while ago but now I can't google the answer...

You can see a similar thing in second example here: Documentation tests - The rustdoc book

The solution they have is to duplicate the entire test and comment out different parts. This is good and works, but it does mean that the same test will run multiple times. If you are concerned about test runtime, you can add ignore to all but one of them to fix that. Generally though, doctests are tested to ensure that they are synced with changes to the library and not to verify the library's correctness, so adding ignore would defeat that purpose.

//! You can easily create a vector with a macro:
//! ```
//! let mut v = vec![1, 2];
//! ```
//! Later you can [`push`] values onto the end of a vector (which will grow the vector
//! as needed):
//! ```
//! # let mut v = vec![1, 2];
//! v.push(3);
//! ```

Another thing you could do is move your text into the code block as a comment.

//! You can easily create a vector with a macro:
//! ```
//! let mut v = vec![1, 2];
//! // Later you can `push` values onto the end of a vector (which will grow the vector
//! // as needed):
//! v.push(3);
//! ```

The downside is that you can't put links and other markdown features, but this may be easier to read and will make more sense to people familiar with how doctests work.

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.