doc(cfg) 条件文档
核心概念
#[doc(cfg(...))] 属性用于在生成的文档中标注某个 API 需要特定的 feature 或平台才可用。当用户在 docs.rs 上查看文档时,会看到类似 "Available on crate feature json only" 的提示,帮助理解哪些功能需要启用哪些 feature。
这个属性本身不影响编译行为(编译行为由 #[cfg(...)] 控制),它只影响文档展示。通常与 #[cfg(...)] 和 #[cfg_attr(docsrs, doc(cfg(...)))] 配合使用。
// 在 docs.rs 上构建时标注 feature 要求
// 需要在 Cargo.toml 中配置 docs.rs 的构建参数
// #[cfg(feature = "json")]
// #[cfg_attr(docsrs, doc(cfg(feature = "json")))]
// pub fn parse_json(s: &str) -> serde_json::Value {
// serde_json::from_str(s).unwrap()
// }
// 在文档中显示:Available on crate feature json only
// #[cfg(unix)]
// #[cfg_attr(docsrs, doc(cfg(unix)))]
// pub fn unix_signal() {
// // Unix 专用功能
// }
// 在文档中显示:Available on Unix only
fn main() {
println!("doc(cfg) 在文档中标注 API 的可用条件");
}配置 docs.rs 构建
# Cargo.toml 中配置 docs.rs 的构建参数
[package]
name = "my-lib"
version = "0.1.0"
edition = "2024"
[package.metadata.docs.rs]
# 启用所有 features 来构建文档
all-features = true
# 或者指定 features
# features = ["json", "async", "tls"]
# 传递 rustdoc 标志
rustdoc-args = ["--cfg", "docsrs"]
# 指定构建目标(用于展示平台特定 API)
targets = ["x86_64-unknown-linux-gnu"]
# 也可以指定多个目标
# targets = [
# "x86_64-unknown-linux-gnu",
# "x86_64-pc-windows-msvc",
# ]使用模式
// 标准的 doc(cfg) 使用模式
// === 1. Feature 条件 ===
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub mod json {
//! JSON 序列化支持(需要启用 `json` feature)
/// 将值序列化为 JSON 字符串
pub fn to_string<T>(value: &T) -> String
where
T: std::fmt::Debug,
{
format!("{:?}", value)
}
}
// === 2. 平台条件 ===
#[cfg(windows)]
#[cfg_attr(docsrs, doc(cfg(windows)))]
pub mod windows_api {
//! Windows 平台专用 API
/// 获取 Windows 注册表值
pub fn read_registry(_key: &str) -> Option<String> {
None
}
}
#[cfg(unix)]
#[cfg_attr(docsrs, doc(cfg(unix)))]
pub mod unix_api {
//! Unix 平台专用 API
/// 发送信号给进程
pub fn send_signal(_pid: u32, _signal: i32) -> bool {
false
}
}
// === 3. 组合条件 ===
#[cfg(all(feature = "async", feature = "json"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "async", feature = "json"))))]
pub async fn fetch_json(_url: &str) -> String {
String::new()
}
fn main() {
println!("doc(cfg) 让文档清晰标注每个 API 的可用条件");
}基本示例
# Cargo.toml
[package]
name = "my-http"
version = "0.1.0"
edition = "2024"
[features]
default = ["json"]
json = []
gzip = []
tls = []
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]//! # my-http
//!
//! HTTP 客户端库,支持可选的 JSON、压缩和 TLS 功能。
/// HTTP 响应
pub struct Response {
/// 状态码
pub status: u16,
/// 响应体
pub body: Vec<u8>,
}
impl Response {
/// 获取响应体的文本内容
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).to_string()
}
/// 将响应体解析为 JSON
///
/// 需要启用 `json` feature。
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub fn json(&self) -> String {
// 实际实现会使用 serde_json
self.text()
}
/// 解压 gzip 响应体
///
/// 需要启用 `gzip` feature。
#[cfg(feature = "gzip")]
#[cfg_attr(docsrs, doc(cfg(feature = "gzip")))]
pub fn decompress(&self) -> Vec<u8> {
self.body.clone()
}
}
/// 创建 TLS 客户端
///
/// 需要启用 `tls` feature。
#[cfg(feature = "tls")]
#[cfg_attr(docsrs, doc(cfg(feature = "tls")))]
pub fn create_tls_client() -> String {
"TLS Client".to_string()
}
fn main() {
let resp = Response {
status: 200,
body: b"hello".to_vec(),
};
println!("text: {}", resp.text());
#[cfg(feature = "json")]
println!("json: {}", resp.json());
}常见问题
问题一:doc(cfg) 和 cfg 有什么区别?
#[cfg] 控制代码是否编译。#[doc(cfg)] 只在文档中添加可用性标注,不影响编译。两者通常一起使用:#[cfg] 控制编译,#[doc(cfg)] 标注文档。
问题二:docsrs 是什么条件?
docsrs 是 docs.rs 在构建文档时通过 --cfg docsrs 设置的标志。用 #[cfg_attr(docsrs, doc(cfg(...)))] 确保 doc(cfg) 只在 docs.rs 构建时生效。
问题三:为什么不直接用 #[doc(cfg)] 而要用 cfg_attr?
因为 doc(cfg) 在某些 Rust 版本中是不稳定特性。通过 cfg_attr(docsrs, ...) 包裹,只在 docs.rs 构建时启用,避免在普通编译时触发不稳定特性警告。
问题四:本地怎么预览 doc(cfg) 效果?
运行 RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features --open。需要 nightly 工具链。
适用场景
- Feature 文档标注:标注哪些 API 需要哪个 feature
- 平台特定 API:标注 Windows/Unix 专用功能
- docs.rs 展示:在在线文档中清晰展示可用条件
- 库文档完整性:展示所有 feature 下的完整 API
注意事项
doc(cfg)只影响文档展示,不影响编译- 需要在
Cargo.toml中配置[package.metadata.docs.rs] - 用
cfg_attr(docsrs, ...)包裹避免稳定性问题 all-features = true让 docs.rs 展示所有 API- 通常与
#[cfg]成对使用 - 本地预览需要 nightly 工具链
总结
#[doc(cfg(...))] 在文档中标注 API 的可用条件(feature、平台等),不影响编译行为。通常与 #[cfg] 配合使用:#[cfg] 控制编译,#[doc(cfg)] 标注文档。推荐用 #[cfg_attr(docsrs, doc(cfg(...)))] 包裹以兼容稳定版。在 Cargo.toml 的 [package.metadata.docs.rs] 段配置 all-features = true 和 rustdoc-args = ["--cfg", "docsrs"] 让 docs.rs 正确展示所有 API 及其 feature 要求。