Rust 注释

三种注释、文档注释、以及 `cargo doc` 怎么读它们。

Beginner
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 --open
Output
   Doc-tests mycrate
running 1 test
test src/lib.rs - add (line 11) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored

Fenced 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,
}

Friends & Partners