坏消息是:目前这只是夜间版本的功能。
好消息是:docs.rs默认使用夜间版本。
doc_cfg
功能并将#doc(cfg)
应用于正在记录文档的项。#![feature(doc_cfg)]
#[doc(cfg(feature = "macros"))]
pub fn test() {}
# docs.rs-specific configuration
[package.metadata.docs.rs]
# document all features
all-features = true
# defines the configuration attribute `docsrs`
rustdoc-args = ["--cfg", "docsrs"]
然后他们使用{{}}。
// 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() {}
doc_auto_cfg
(合并在PR#90502中),无需手动标记doc
的特性,只需像以前一样编写cfg
即可。#![feature(doc_auto_cfg)]
#[cfg(feature = "macros")]
pub fn test() {}
要在本地检查它,请运行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() {}
更新: 上述方法仍需要运行每夜版的 doc-tests
,并且它还需要依赖项的 doc
命令在每夜版下运行。一种解决方法是我们可以仅在每夜版下启用 doc_auto_cfg
功能。
在 Cargo.toml
文件中添加:
[build-dependencies]
rustc_version = "0.4.0"
创建一个 build.rs
文件,内容如下:
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)
}
我们可以通过以下方式启用doc_auto_cfg
功能:
#![cfg_attr(all(doc, CHANNEL_NIGHTLY), feature(doc_auto_cfg))]
由于docs.rs
默认使用夜间版,因此那里的文档将会按照您的期望显示。
doc
功能。我还尝试过 #![cfg_attr(all(doc, not(test)), feature(doc_auto_cfg))]
和 #![cfg_attr(all(doc, not(doctest)), feature(doc_auto_cfg))]
,但没有成功。 - FujiApplecfg
禁用,Rustc 将无法看到它。 - Sprite
RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features
- Niklas