注释
代码能做到自注释,文档要干练简洁
- 代码能够做到自注释,避免冗余的普通代码注释。
注释固然很重要, 但最好的代码应当本身就是文档。有意义的类型名、函数名和变量名, 要远胜过要用注释解释的含糊不清的名字。当有意义的类型名、函数名和变量名还不能表达完整的语义时,再使用注释。
不要描述显而易见的现象, 永远不要用自然语言翻译代码作为注释。
- 文档注释要干练简洁:
文档注释中内容用语应该尽量简短精干,不宜篇幅过长。请确保你的代码注释良好并且易于他人理解,好的注释能够传达上下文关系和代码目的。
注释内容始终围绕两个关键点来构建:
What : 用于阐述代码为了什么而实现。
how : 用于阐述代码如何去使用。
注释和文档注释使用的自然语言要保持一致。
Rust 项目文档应该始终基于 rustdoc 工具来构建,rustdoc 支持 Markdown 格式,为了使得文档更加美观易读,文档注释应该使用 Markdown 格式。
模块级文档
//! # The Rust core allocation and collections library
//!
//! This library provides smart pointers and collections for managing
//! heap-allocated values.
//!
//! This library, like libcore, normally doesn’t need to be used directly
//! since its contents are re-exported in the [`std` crate](../std/index.html).
//! Crates that use the `#![no_std]` attribute however will typically
//! not depend on `std`, so they’d use this crate instead.
//!
//! ## Boxed values
//!
//! The [`Box`] type is a smart pointer type. There can only be one owner of a
//! [`Box`], and the owner can decide to mutate the contents, which live on the
//! heap.
普通文档注释示例
#![allow(unused)]
/// Constructs a new, empty `Vec<T>`.
///
/// The vector will not allocate until elements are pushed onto it.
///
/// # Examples
///
/// ```
/// # #![allow(unused_mut)]
/// let mut vec: Vec<i32> = Vec::new();
/// ```
#[inline]
#[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
#[stable(feature = "rust1", since = "1.0.0")]
pub const fn new() -> Self {
Vec { buf: RawVec::NEW, len: 0 }
}
使用行注释而避免使用块注释
尽量使用行注释(// 或 ///),而非块注释。这是Rust社区的约定俗成。
对于文档注释,仅在编写模块级文档时使用 //!,在其他情况使用 ///更好。
说明: #![doc] 和 #[doc] 对于简化文档注释有特殊作用,没有必要通过 rustfmt 将其强制转化为 //! 或 /// 。
文件头注释包含版权说明
文件头(即,模块级)注释应先包含版权说明。如果文件头注释需要增加其他内容,可以在版权说明下面补充。
可以包括:
- 文件功能说明。
- 作者。
- 创建日期 和 最后修改日期。
- 注意事项。
- 开源许可证(比如, Apache 2.0, BSD, LGPL, GPL)。
- 其他。
在注释中使用 FIXME 和 TODO 来帮助任务协作
通过在注释中开启 FIXME 和 TODO 可以方便协作。正式发布版本可以不做此类标注。
在公开的返回Result类型的函数文档中增加 Error 注释
在公开(pub)的返回Result类型的函数文档中,建议增加 # Error 注释来解释什么场景下该函数会返回什么样的错误类型,方便用户处理错误。
fn main() {
use std::io;
// 符合:增加了规范的 Errors 文档注释
/// # Errors
///
/// Will return `Err` if `filename` does not exist or the user does not have
/// permission to read it.
pub fn read(filename: String) -> io::Result<String> {
unimplemented!();
}
}
如果公开的API在某些情况下会发生Panic,则相应文档中需增加 Panic 注释
在公开(pub)函数文档中,建议增加 # Panic 注释来解释该函数在什么条件下会 Panic,便于使用者进行预处理。
// 符合:增加了规范的 Panic 注释
/// # Panics
///
/// Will panic if y is 0
pub fn divide_by(x: i32, y: i32) -> i32 {
if y == 0 {
panic!("Cannot divide by 0")
} else {
x / y
}
}