rustrustdoc

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

  • The bad news is: It's a nightly-only feature for now.

    The good news is: docs.rs uses nightly by default.


    To get this to work all you need is to enable the doc_cfg feature and apply #doc(cfg) to the item being documented

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

    Because this is a nightly-only feature, you probably don't want to enable it all the time. tokio defines the following in its Cargo.toml to only enable this feature on docs.rs:

    # docs.rs-specific configuration
    [package.metadata.docs.rs]
    # document all features
    all-features = true
    # defines the configuration attribute `docsrs`
    rustdoc-args = ["--cfg", "docsrs"]
    

    and then they use

    // only enables the `doc_cfg` feature when
    // the `docsrs` configuration attribute is defined
    #![cfg_attr(docsrs, feature(doc_cfg))]
    
    #[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
    pub fn test() {}