Rust 注释
三种注释、文档注释、以及 `cargo doc` 怎么读它们。
Key Points`///` 写在声明上方生成文档,`//!` 写在模块内部描述整个模块。
三种注释
Rust
// 单行注释
/* 块注释 */
/* 可以嵌套 /* 这样 */ 也没问题 */
/// 文档注释:给紧跟着的那个条目生成文档
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
//! 模块级文档:描述整个文件/模块
//! 通常放在文件最上方文档注释
Rust
/// 计算两个整数的和。
///
/// # 参数
///
/// * `a` - 第一个加数
/// * `b` - 第二个加数
///
/// # 示例
///
/// ```
/// use mycrate::add;
/// assert_eq!(add(1, 2), 3);
/// ```
///
/// # Panics
///
/// 本函数不会 panic。
///
/// # Errors
///
/// 不返回错误。
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Rust convention uses sections: # Arguments, # Examples, # Panics, # Errors, # Safety. cargo doc renders them as headed blocks.
文档即测试
Bash
cargo test --doc
cargo doc --openOutput
Doc-tests mycrate
running 1 test
test src/lib.rs - add (line 11) ... ok
test result: ok. 1 passed; 0 failed; 0 ignoredFenced code blocks in docs are compiled and executed. A broken example turns cargo test red, keeping docs in sync with code — the root of Rust's documentation quality.
To skip execution use ```
`no_run ``; to assert it fails to compile use `` `compile_fail ``; to hide lines prefix them with # `.注释的实践
- 写为什么,不写做什么 ——
// i += 1毫无信息 - **
TODO/FIXME带上人和日期** ——// TODO(zhang, 2026-11): 换成批量接口 - 公开 API 一律写文档注释 ——
#![warn(missing_docs)]可以强制
Rust
#![warn(missing_docs)]
#![deny(missing_debug_implementations)]
//! 这个 crate 提供订单相关的核心类型。
/// 订单状态。
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Status {
/// 待支付
Pending,
/// 已支付
Paid,
/// 已取消
Cancelled,
}三种注释
Rust
// 单行注释
/* 块注释 */
/* 可以嵌套 /* 这样 */ 也没问题 */
/// 文档注释:给紧跟着的那个条目生成文档
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
//! 模块级文档:描述整个文件/模块
//! 通常放在文件最上方文档注释
Rust
/// 计算两个整数的和。
///
/// # 参数
///
/// * `a` - 第一个加数
/// * `b` - 第二个加数
///
/// # 示例
///
/// ```
/// use mycrate::add;
/// assert_eq!(add(1, 2), 3);
/// ```
///
/// # Panics
///
/// 本函数不会 panic。
///
/// # Errors
///
/// 不返回错误。
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Rust 生态里文档注释的惯例是分节写 # 参数、# 示例、# Panics、# Errors、# Safety。cargo doc 会把这些小节渲染成带标题的段落。
文档即测试
Bash
cargo test --doc
cargo doc --openOutput
Doc-tests mycrate
running 1 test
test src/lib.rs - add (line 11) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored文档里的 ``` ` `` 代码块会被抽出来编译执行。示例写错了 cargo test` 就红——这保证文档永远和代码同步,是 Rust 文档质量的根源。
文档示例里想跳过执行,用 ```
`no_run ``;想让它编译失败(演示错误用法),用 `` `compile_fail ``;想隐藏某几行,行首加 # `。注释的实践
- 写为什么,不写做什么 ——
// i += 1毫无信息 - **
TODO/FIXME带上人和日期** ——// TODO(zhang, 2026-11): 换成批量接口 - 公开 API 一律写文档注释 ——
#![warn(missing_docs)]可以强制
Rust
#![warn(missing_docs)]
#![deny(missing_debug_implementations)]
//! 这个 crate 提供订单相关的核心类型。
/// 订单状态。
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Status {
/// 待支付
Pending,
/// 已支付
Paid,
/// 已取消
Cancelled,
}