'How to get a feature requirement tag in the documentation generated by `cargo doc`?

If you look at the Tokio docs on docs.rs there's a blue tag indicating that a feature must be activated in order to access this API:

enter image description here

I would like to enable this for my crate as well, how can this be done?



Solution 1:[1]

In the latest nightly (since v1.57 maybe), you can use feature doc_auto_cfg (merged in PR#90502) and you no longer need to manually mark features for doc, just write cfg as before:

#![feature(doc_auto_cfg)]

#[cfg(feature = "macros")]
pub fn test() {}

To check it locally, run cargo +nightly doc --all-features.

If you want to continue using stable for commands other than cargo doc, you can:

#![cfg_attr(doc, feature(doc_auto_cfg))]

#[cfg(feature = "macros")]
pub fn test() {}

UPDATE: The above method still requires doc-tests to run nightly, and it also requires dependents' doc command to run nightly. A workaround is that we can enable the doc_auto_cfg feature only under nightly.

In Cargo.toml, adding:

[build-dependencies]
rustc_version = "0.4.0"

Create a build.rs file with the following contents:

use rustc_version::{version_meta, Channel};

fn main() {
    // Set cfg flags depending on release channel
    let channel = match version_meta().unwrap().channel {
        Channel::Stable => "CHANNEL_STABLE",
        Channel::Beta => "CHANNEL_BETA",
        Channel::Nightly => "CHANNEL_NIGHTLY",
        Channel::Dev => "CHANNEL_DEV",
    };
    println!("cargo:rustc-cfg={}", channel)
}

Then we can enable the feature doc_auto_cfg this way:

#![cfg_attr(all(doc, CHANNEL_NIGHTLY), feature(doc_auto_cfg))]

Since docs.rs uses nightly by default, the documentation on there will be shown as you expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1