附录 D - 有用的开发工具

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

使用 rustfmt 自动格式化

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

要安装 rustfmt,请输入以下命令

$ rustup component add rustfmt

此命令会给你 rustfmtcargo-fmt,类似于 Rust 同时给你 rustccargo。要格式化任何 Cargo 项目,请输入以下命令

$ cargo fmt

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

使用 rustfix 修复你的代码

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

文件名: src/main.rs

fn do_something() {}

fn main() {
    for i in 0..100 {
        do_something();
    }
}

在这里,我们调用 do_something 函数 100 次,但我们从未使用 for 循环体中的变量 i。Rust 会警告我们这一点

$ cargo build
   Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: unused variable: `i`
 --> src/main.rs:4:9
  |
4 |     for i in 0..100 {
  |         ^ help: consider using `_i` instead
  |
  = note: #[warn(unused_variables)] on by default

    Finished dev [unoptimized + debuginfo] target(s) in 0.50s

该警告建议我们使用 _i 作为名称:下划线表示我们希望这个变量不被使用。我们可以使用 rustfix 工具通过运行命令 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 已经更改了代码

文件名: src/main.rs

fn do_something() {}

fn main() {
    for _i in 0..100 {
        do_something();
    }
}

for 循环变量现在被命名为 _i,并且不再出现警告。

你还可以使用 cargo fix 命令在不同的 Rust 版本之间转换你的代码。版本在附录 E 中进行了介绍。

使用 Clippy 进行更多代码检查

Clippy 工具是一组代码检查器,用于分析你的代码,以便你可以捕获常见的错误并改进你的 Rust 代码。

要安装 Clippy,请输入以下命令

$ rustup component add clippy

要在任何 Cargo 项目上运行 Clippy 的代码检查,请输入以下命令

$ cargo clippy

例如,假设你编写了一个使用数学常数(例如 pi)近似值的程序,就像这个程序一样

文件名: src/main.rs

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

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

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 常量。以下代码不会导致 Clippy 的任何错误或警告

文件名: src/main.rs

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

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

使用 rust-analyzer 进行 IDE 集成

为了帮助 IDE 集成,Rust 社区建议使用rust-analyzer。此工具是一组以编译器为中心的实用程序,它使用语言服务器协议,这是 IDE 和编程语言之间相互通信的规范。不同的客户端可以使用 rust-analyzer,例如用于 Visual Studio Code 的 Rust 分析器插件

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