Rustdoc

Rust 中的所有语言元素都可以通过特殊的 /// 语法进行文档化。

/// Determine whether the first argument is divisible by the second argument.
///
/// If the second argument is zero, the result is false.
///
/// # Example
/// ```
/// assert!(is_divisible_by(42, 2));
/// ```
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
    if rhs == 0 {
        return false;  // Corner case, early return
    }
    lhs % rhs == 0     // The last expression in a block is the return value
}

The contents are treated as Markdown. All published Rust library crates are automatically documented at docs.rs using the rustdoc tool. It is idiomatic to document all public items in an API using this pattern. Code snippets can document usage and will be used as unit tests.

  • 向学生展示在 docs.rs/rand 中为 rand crate 生成的文档。

  • 本课程的幻灯片中不包含 rustdoc,这是为了节省空间,但是在实际的代码中,应当编写相关的程序文档。

  • 内部文档注释将在稍后(在讲解模块的页面)讨论,这里无需进行说明。

  • Rustdoc 注释可以包含我们可使用“cargo test”运行和测试的代码段。我们将在“测试”部分中讨论这些测试。