`#![doc = include_str!("../README.md")]` and links to crate items

Let's say I have a library which uses #![doc = include_str!("../README.md")] for all its crate-level docs. It's often desirable to have crate docs as part of readme with its examples and high-level explanation of crate functionality.

For example:

#![doc = include_str!("README.md")]

/// Function which does stuff
pub fn do_stuff() {
    // ...

Now In the crate readme I want to reference items in the crate:

# StuffDoer

This crate contains the [`do_stuff`] function which does stuff.

When crate docs are rendered by rustdoc, the do_stuff link works as expected. But when the readme is rendered on GitHub or crates.io we get a dead link (i.e. it's rendered as "[do_stuff]").

It's possible to add explicit links to readme, but now it's unclear which links to use. Should it be https://docs.rs/stuffdoer/latest/stuffdoer/fn.do_stuff.html or maybe https://docs.rs/stuffdoer/0.1.0/stuffdoer/fn.do_stuff.html?

But manual link not only are quite annoying to add and maintain, they also will lead to external resources from locally built docs, since rustdoc will not generate local links for such items and instead will use the provided external link.

So what do you think would be the best approach to follow in such situations? Maybe it could be useful to add a way to allow rustdoc to overwrite such item links?

I do it sometimes the other way, there is the crates.io: Rust Package Registry tool to extract this from your code doc comment.

The linking is done like in normal markdown. The url in round brackets has priority. You can also create references at the end. [Struct::method]: ./somepath/somefile.html

It is documented here: Linking to items by name - The rustdoc book


Yandros has a nifty little trick for that. They just redefine the links they used in the README to point to the local item before adding the README to the docs. Like so. That way the external link is overridden in the local docs but still works in the README. You'd still have to maintain the external links though, which can be annoying for sure.

1 Like