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

附录 D:有用的开发工具

Appendix D: Useful Development Tools

在本附录中,我们将讨论 Rust 项目提供的一些有用的开发工具。我们将了解自动格式化、应用警告修复的快速方法、代码检查工具(linter)以及与 IDE 的集成。

In this appendix, we talk about some useful development tools that the Rust project provides. We’ll look at automatic formatting, quick ways to apply warning fixes, a linter, and integrating with IDEs.

使用 rustfmt 进行自动格式化

Automatic Formatting with rustfmt

rustfmt 工具根据社区代码风格重新格式化你的代码。许多协作项目使用 rustfmt 来防止在编写 Rust 时由于使用哪种风格而产生争论:每个人都使用该工具格式化他们的代码。

The rustfmt tool reformats your code according to the community code style. Many collaborative projects use rustfmt to prevent arguments about which style to use when writing Rust: Everyone formats their code using the tool.

Rust 的安装默认包含 rustfmt,因此你的系统上应该已经有了 rustfmtcargo-fmt 程序。这两个命令类似于 rustccargo,因为 rustfmt 允许进行更精细的控制,而 cargo-fmt 则理解使用 Cargo 的项目的约定。要格式化任何 Cargo 项目,请输入以下内容:

Rust installations include rustfmt by default, so you should already have the programs rustfmt and cargo-fmt on your system. These two commands are analogous to rustc and cargo in that rustfmt allows finer grained control and cargo-fmt understands conventions of a project that uses Cargo. To format any Cargo project, enter the following:

$ cargo fmt

运行此命令会重新格式化当前 crate 中的所有 Rust 代码。这应该只会改变代码风格,而不会改变代码语义。有关 rustfmt 的更多信息,请参阅 其文档

Running this command reformats all the Rust code in the current crate. This should only change the code style, not the code semantics. For more information on rustfmt, see its documentation.

使用 rustfix 修复代码

Fix Your Code with rustfix

rustfix 工具包含在 Rust 安装中,它可以自动修复具有明确纠正方法的编译器警告,这些纠正方法很可能就是你想要的。你以前可能见过编译器警告。例如,考虑这段代码:

The rustfix tool is included with Rust installations and can automatically fix compiler warnings that have a clear way to correct the problem that’s likely what you want. You’ve probably seen compiler warnings before. For example, consider this code:

文件名: src/main.rs Filename: src/main.rs

fn main() {
    let mut x = 42;
    println!("{x}");
}

在这里,我们将变量 x 定义为可变的,但我们从未实际修改过它。Rust 对此发出了警告:

Here, we’re defining the variable x as mutable, but we never actually mutate it. Rust warns us about that:

$ cargo build
   Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: variable does not need to be mutable
 --> src/main.rs:2:9
  |
2 |     let mut x = 0;
  |         ----^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` on by default

警告建议我们删除 mut 关键字。我们可以使用 rustfix 工具,通过运行 cargo fix 命令来自动应用该建议:

The warning suggests that we remove the mut keyword. We can automatically apply that suggestion using the rustfix tool by running the command cargo fix:

$ cargo fix
    Checking myprogram v0.1.0 (file:///projects/myprogram)
      Fixing src/main.rs (1 fix)
    Finished dev [unoptimized + debuginfo] target(s) in 0.59s

当我们再次查看 src/main.rs 时,我们会发现 cargo fix 已经修改了代码:

When we look at src/main.rs again, we’ll see that cargo fix has changed the code:

文件名: src/main.rs Filename: src/main.rs

fn main() {
    let x = 42;
    println!("{x}");
}

变量 x 现在是不可变的,警告不再出现。

The variable x is now immutable, and the warning no longer appears.

你还可以使用 cargo fix 命令在不同的 Rust 版本(Edition)之间迁移代码。版本在 附录 E 中有介绍。

You can also use the cargo fix command to transition your code between different Rust editions. Editions are covered in Appendix E.

使用 Clippy 获得更多 Lint

More Lints with Clippy

Clippy 工具是一系列用于分析代码的检查项(lint)集合,以便你可以发现常见错误并改进你的 Rust 代码。Clippy 包含在标准的 Rust 安装中。

The Clippy tool is a collection of lints to analyze your code so that you can catch common mistakes and improve your Rust code. Clippy is included with standard Rust installations.

要在任何 Cargo 项目上运行 Clippy 的检查,请输入以下内容:

To run Clippy’s lints on any Cargo project, enter the following:

$ cargo clippy

例如,假设你编写了一个使用数学常数(如圆周率)近似值的程序,如下所示:

For example, say you write a program that uses an approximation of a mathematical constant, such as pi, as this program does:

fn main() {
    let x = 3.1415;
    let r = 8.0;
    println!("the area of the circle is {}", x * r * r);
}

在该项目上运行 cargo clippy 会导致此错误:

Running cargo clippy on this project results in this error:

error: approximate value of `f{32, 64}::consts::PI` found
 --> src/main.rs:2:13
  |
2 |     let x = 3.1415;
  |             ^^^^^^
  |
  = note: `#[deny(clippy::approx_constant)]` on by default
  = help: consider using the constant directly
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant

此错误让你知道 Rust 已经定义了一个更精确的 PI 常数,如果使用该常数,你的程序将更正确。然后,你应该修改代码以使用 PI 常数。

This error lets you know that Rust already has a more precise PI constant defined, and that your program would be more correct if you used the constant instead. You would then change your code to use the PI constant.

以下代码不会导致 Clippy 产生任何错误或警告:

The following code doesn’t result in any errors or warnings from Clippy:

fn main() {
    let x = std::f64::consts::PI;
    let r = 8.0;
    println!("the area of the circle is {}", x * r * r);
}

有关 Clippy 的更多信息,请参阅 其文档

For more information on Clippy, see its documentation.

使用 rust-analyzer 进行 IDE 集成

IDE Integration Using rust-analyzer

为了帮助进行 IDE 集成,Rust 社区建议使用 rust-analyzer。该工具是一套以编译器为核心的实用程序,它们遵循 语言服务器协议 (Language Server Protocol),这是 IDE 和编程语言之间通信的规范。不同的客户端可以使用 rust-analyzer,例如 Visual Studio Code 的 Rust analyzer 插件

To help with IDE integration, the Rust community recommends using rust-analyzer. This tool is a set of compiler-centric utilities that speak Language Server Protocol, which is a specification for IDEs and programming languages to communicate with each other. Different clients can use rust-analyzer, such as the Rust analyzer plug-in for Visual Studio Code.

访问 rust-analyzer 项目的 主页 以获取安装说明,然后在你的特定 IDE 中安装语言服务器支持。你的 IDE 将获得诸如自动补全、跳转到定义和内联错误等功能。

Visit the rust-analyzer project’s home page for installation instructions, then install the language server support in your particular IDE. Your IDE will gain capabilities such as autocompletion, jump to definition, and inline errors.