trpl-zh-cn/src/ch03-04-comments.md

45 lines
1.4 KiB
Markdown
Raw Normal View History

2017-02-13 15:43:15 +08:00
## 注释
2021-06-03 12:26:20 +08:00
> [ch03-04-comments.md](https://github.com/rust-lang/book/blob/main/src/ch03-04-comments.md)
2017-02-13 15:43:15 +08:00
> <br>
> commit 25a1530ccbf0a79c8df2920ee2af8beb106122e8
2017-02-13 15:43:15 +08:00
2018-08-28 14:39:09 +08:00
所有程序员都力求使其代码易于理解,不过有时还需要提供额外的解释。在这种情况下,程序员在源码中留下记录,或者 **注释***comments*),编译器会忽略它们,不过阅读代码的人可能觉得有用。
2017-02-13 15:43:15 +08:00
2018-08-28 14:39:09 +08:00
这是一个简单的注释:
2017-02-13 15:43:15 +08:00
```rust
2018-08-28 14:39:09 +08:00
// hello, world
2017-02-13 15:43:15 +08:00
```
在 Rust 中,惯用的注释样式是以两个斜杠开始注释,并持续到本行的结尾。对于超过一行的注释,需要在每一行前都加上 `//`,像这样:
2017-02-13 15:43:15 +08:00
```rust
// So were doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain whats going on.
```
2021-12-01 11:44:57 +08:00
注释也可以放在包含代码的行的末尾:
2017-02-13 15:43:15 +08:00
2017-08-15 14:13:09 +08:00
<span class="filename">文件名: src/main.rs</span>
2017-02-13 15:43:15 +08:00
```rust
fn main() {
2018-08-28 14:39:09 +08:00
let lucky_number = 7; // Im feeling lucky today
2017-02-13 15:43:15 +08:00
}
```
2019-11-20 00:43:49 +08:00
不过你更经常看到的是以这种格式使用它们,也就是位于它所解释的代码行的上面一行:
2017-02-13 15:43:15 +08:00
2017-08-15 14:13:09 +08:00
<span class="filename">文件名: src/main.rs</span>
2017-02-13 15:43:15 +08:00
```rust
fn main() {
2018-08-28 14:39:09 +08:00
// Im feeling lucky today
2017-02-13 15:43:15 +08:00
let lucky_number = 7;
}
2017-02-14 22:42:54 +08:00
```
2017-02-13 15:43:15 +08:00
2019-11-20 00:43:49 +08:00
Rust 还有另一种注释,称为文档注释,我们将在 14 章的 “将 crate 发布到 Crates.io” 部分讨论它。