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

注释

所有程序员都希望自己的代码易于理解,但有时仍需要补充说明。这种情况下,程序员会在源代码中留下注释。编译器会忽略注释,但阅读源代码的人可能会觉得它们很有帮助。

下面是一条简单的注释:

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

在 Rust 中,惯用的注释风格是用两个斜杠开始注释,注释会持续到行尾。如果注释超过一行,就需要在每一行前都添加 //,如下所示:

#![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.
}

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

文件名:src/main.rs

fn main() {
    let lucky_number = 7; // I'm feeling lucky today
}

不过,你更常见到的是下面这种格式:将注释放在所注释代码上方的独立一行:

文件名:src/main.rs

fn main() {
    // I'm feeling lucky today
    let lucky_number = 7;
}

Rust 还有另一种注释,即文档注释。我们会在第 14 章“将 crate 发布到 Crates.io”一节中讨论它。