现在我们写了一些函数,是时候学习一下注释了。注释是你帮助其他程序猿理解你的代码的备注。编译器基本上会忽略它们。
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标记支持:
/// `hello` is a function that prints a greeting that is personalized based on
/// the name given.
///
/// # Arguments
///
/// * `name` - The name of the person you"d like to greet.
///
/// # Example
///
/// ```rust
/// let name = "Steve";
/// hello(name); // prints "Hello, Steve!"
///
fn hello(name: &str) { println!("Hello, {}!", name); } `
当书写文档注释时,加上参数和返回值部分并提供一些用例将是非常有帮助的。不要担心那个&str
,我们马上会提到它。
你可以使用rustdoc工具来将文档注释生成为HTML文档。