Adding feature required Tag to Rust Documentation


I had a lot of trouble understanding this. Thus I am documenting it here for myself. All credit goes to the original StackOverFlow author.

  1. Add one of the following to the root of your crate. Usually lib.rs
    1.

    #![feature(doc_cfg)]
    

    This is less than ideal as it will cause compile errors when used with stable
    2. It is better to use:

    #![cfg_attr(docsrs, feature(doc_cfg))]
    

    This allows this to be conditionally compiled and does not give any errors.

  2. Add the following to items that you would like to have the tag applied to within your code documentation. As an example:

    #[cfg_attr(docsrs, doc(cfg(feature = "my-feature")))]
    #[cfg(feature = "my-feature")]
    pub fn test() {}
    
  3. Add instruction to cargo.toml

    [package.metadata.docs.rs]
    all-features = true
    rustdoc-args = ["--cfg", "docsrs"]
    

At this point you should be able to compile your code successfully with or without the feature being enabled. But you will not see the tag in your documentation.

To be able to build your documeatnion locally and confirm that tag; do the following.

  1. Install a version of nightly

    prompt> rustup toolchain install nightly
    
  2. Build your documentation with nightly to see the tag

    prompt> RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --all-features
    

Reference:

How to get a feature requirement tag in the documentation generated by cargo doc? - StackOverFlow


See also