Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


x-i18n: generated_at: “2026-03-01T13:36:29Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 82b0aac1db631041ec36dc64c6eb115c2a34e0deb062464ee0ed86203b044372 source_path: ch03-04-comments.md workflow: 16

注释 (Comments)

Comments

所有的程序员都力求使他们的代码易于理解,但有时仍需要额外的解释。在这些情况下,程序员会在源代码中留下“注释 (comments)”,编译器会忽略这些注释,但阅读源代码的人可能会觉得它们很有用。

All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted. In these cases, programmers leave comments in their source code that the compiler will ignore but that people reading the source code may find useful.

这是一个简单的注释:

Here’s a simple comment:

#![allow(unused)]
fn main() {
// hello, world
}

在 Rust 中,惯用的注释风格是以两个斜杠开始注释,并且注释一直持续到行尾。对于超过一行的注释,你需要在每一行都包含 //,就像这样:

In Rust, the idiomatic comment style starts a comment with two slashes, and the comment continues until the end of the line. For comments that extend beyond a single line, you’ll need to include // on each line, like this:

#![allow(unused)]
fn main() {
// So we're doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what's going on.
}

注释也可以放在包含代码的行末:

Comments can also be placed at the end of lines containing code:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-24-comments-end-of-line/src/main.rs}}
}

但你更常看到这种格式的使用方式,即注释位于其所注释的代码上方的独立行中:

But you’ll more often see them used in this format, with the comment on a separate line above the code it’s annotating:

文件名: src/main.rs

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch03-common-programming-concepts/no-listing-25-comments-above-line/src/main.rs}}
}

Rust 还有另一种注释,即文档注释,我们将在第 14 章的“将 Crate 发布到 Crates.io”部分进行讨论。

Rust also has another kind of comment, documentation comments, which we’ll discuss in the “Publishing a Crate to Crates.io” section of Chapter 14.