rustrustdoc

Idiomatic way to repeat a paragraph in rustdoc


I am finally taking some time to properly document my first Rust library and I would like to keep my doc as idiomatic as possible. In my library, there are two classes (I will call them Alpha and Beta for simplicity) that represent the same data in slightly different ways, optimized for different uses. The difference is subtle but important and I would like to make it as understandable as possible for my end user.

So when I got do document Alpha I started with:

/// [`Alpha`] is a `struct` doing so and so.
///
/// # The difference between [`Alpha`]s and [`Beta`]s
///
/// While [`Alpha`]s do some important thing in this way, [`Beta`]s
/// do kind of the same important thing, but in this other way!
struct Alpha {
   // ...
}

I am very proud of my explanation, so when I got to documenting Beta, I felt the urge to copy-paste:

/// [`Beta`] is a `struct` doing so and so.
///
/// # The difference between [`Alpha`]s and [`Beta`]s
///
/// The same exact text as in [`Alpha`]'s documentation!
struct Beta {
   // ...
}

Now, I can immediately see the problem ahead. One day I will change the paragraph in Alpha's doc, forget to change it in Beta's, and voilĂ , my documentation is uncomfortably inconsistent.

So I am thinking: what is the most idiomatic way to work around this problem? I would like to avoid, e.g., making a fake DifferenceBetweenAlphaAndBeta empty struct just to put documentation there. What is the usual way to go about this? I reckon there are no "import paragraph of doc from an external file" commands in rustdoc, right?


Solution

  • I'd avoid duplicating the documentation, that spares readers the need to read the same text twice and possibly wonder "Is it the same?". To still document both you can just refer from the documentation of one item to the others documentation, saves time reading, still documents everything.

    If you still want to duplicate the exact same text twice you can do so by putting it in a separate file shared.md:

     # The difference between `Alpha`s and `Beta`s
    
     While [`Alpha`]s do some important thing in this way, [`Beta`]s
     do kind of the same important thing, but in this other way!
    

    and include it in both places:

    /// `Alpha` is a `struct` doing so and so.
    ///
    #[doc = include_str!("shared.md")]
    struct Alpha {
       // ...
    }
    /// `Beta` is a `struct` doing so and so.
    ///
    #[doc = include_str!("shared.md")]
    struct Beta {
       // ...
    }
    

    as Jonas Fassbender suggests