注释

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

这是一个简单的注释

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

或者您可以使用 /**/ 的多行注释语法

#![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 还有另一种注释,文档注释,我们将在“将 Crate 发布到 Crates.io”中讨论第 14 章的章节。