Ways to globally define a string for rustdoc?

We have a crate that serves as an client API for working against a server. The functions in the crate are documented, but there’s a lot of stuff that is documented in a separate document. So we want to leave a comment in each function’s rustdoc documentation along the line of “See document Some Document Title under section Some Section for more information”.

The problem is that the exact title of the document has not yet been determined. We can simply search and replace the title once we have it, but it made me wonder: Is there some way to reference some kind of variable in rustdoc? Could we define the name somewhere globally and simply reference it in all the rustdoc comments? I suspect the answer is “no”, but one never knows what hidden features one might have missed.

1 Like

Doc “comments” are actually attributes, which in normal attribute syntax would be #[doc = "..."], and macros can produce and manipulate attributes. You can even use macros inside the #[doc] attribute, as long as they end up producing a literal string. The most common use of this is include_str!("foo.md"), but you can use it in more template-like ways. For example:

macro_rules! section_ref {
    ($section:literal) => {
        concat!("See *Document Title*, section “", $section, "”.")
    };
}

/// Foo blah blah lorem ipsum.
///
#[doc = section_ref!("foo")]
pub mod foo {}

This produces the documentation text:

Foo blah blah lorem ipsum.

See Document Title, section “foo”.

10 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.