如何在`cargo doc`生成的文档中获取功能需求标签?

SBS*_*STP 11 rust rustdoc

如果您查看docs.rs上的Tokio 文档,有一个蓝色标签表示必须激活某个功能才能访问此 API:

在此处输入图片说明

我也想为我的板条箱启用此功能,如何做到这一点?

mca*_*ton 15

坏消息是:目前这是一项仅限夜间使用的功能。

好消息是:docs.rs 默认每晚使用。


要使其正常工作,您只需要启用该doc_cfg功能并应用于#doc(cfg)正在记录的项目

#![feature(doc_cfg)]

#[doc(cfg(feature = "macros"))]
pub fn test() {}
Run Code Online (Sandbox Code Playgroud)

由于这是一项仅限夜间使用的功能,您可能不想一直启用它。tokio在其中定义以下内容Cargo.toml以仅在 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"]
Run Code Online (Sandbox Code Playgroud)

然后他们使用

#![feature(doc_cfg)]

#[doc(cfg(feature = "macros"))]
pub fn test() {}
Run Code Online (Sandbox Code Playgroud)

  • 要在本地测试,请使用: `RUSTDOCFLAGS="--cfg docsrs" Cargo +nightly doc --all-features` (5认同)

Spr*_*ite 11

在最新的 nightly 中(可能从 v1.57 开始),您可以使用 feature doc_auto_cfg(合并在PR#90502中),并且不再需要手动标记 的 features ,只需像以前一样doc编写:cfg

#![feature(doc_auto_cfg)]

#[cfg(feature = "macros")]
pub fn test() {}
Run Code Online (Sandbox Code Playgroud)

要在本地检查它,请运行cargo +nightly doc --all-features.

如果您想继续使用 stable 以外的命令cargo doc,您可以:

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

#[cfg(feature = "macros")]
pub fn test() {}
Run Code Online (Sandbox Code Playgroud)

更新:上述方法仍然需要doc-tests每晚运行,并且还需要依赖者的doc命令每晚运行。解决方法是我们doc_auto_cfg只能在夜间启用该功能。

在 中Cargo.toml,添加:

[build-dependencies]
rustc_version = "0.4.0"
Run Code Online (Sandbox Code Playgroud)

创建一个build.rs包含以下内容的文件:

[build-dependencies]
rustc_version = "0.4.0"
Run Code Online (Sandbox Code Playgroud)

然后我们可以通过以下方式启用该功能doc_auto_cfg

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)
}
Run Code Online (Sandbox Code Playgroud)

由于docs.rs默认使用 nightly,因此那里的文档将按您的预期显示。