5.4.注释
最后更新于:2022-04-01 00:43:34
现在我们写了一些函数,是时候学习一下注释了。注释是你帮助其他程序猿理解你的代码的备注。编译器基本上会忽略它们。
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](http://kaisery.gitbooks.io/rust-book-chinese/content/content/4.4.Documentation%20%E6%96%87%E6%A1%A3.md)工具来将文档注释生成为HTML文档。