注释

欢马劈雪     最近更新时间:2020-08-04 05:37:59

233

comments.md
commit 024aa9a345e92aa1926517c4d9b16bd83e74c10d

现在我们写了一些函数,是时候学习一下注释了。注释是你帮助其他程序员理解你的代码的备注。编译器基本上会忽略它们。

Rust有两种需要你了解的注释格式:行注释line comments)和文档注释doc comments)。

// Line comments are anything after ‘//’ and extend to the end of the line.

let x = 5; // this is also a line comment.

// If you have a long explanation for something, you can put line comments next
// to each other. Put a space between the // and your comment so that it’s
// more readable.

另一种注释是文档注释。文档注释使用///而不是//,并且内建Markdown标记支持:

/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// # fn add_one(x: i32) -> i32 {
/// #     x + 1
/// # }
/// ```
fn add_one(x: i32) -> i32 {
    x + 1
}

有另外一种风格的文档注释,//!,用来注释包含它的项(也就是说,crate,模块或者函数),而不是位于它之后的项。它经常用在crate根文件(lib.rs)或者模块根文件(mod.rs):

//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
展开阅读全文