附录 D:实用开发工具
本附录介绍 Rust 项目提供的一些实用开发工具,包括自动格式化、快速应用警告修复、代码检查工具,以及与 IDE 集成。
使用 rustfmt 自动格式化
rustfmt 工具会按照社区代码风格重新格式化代码。许多协作项目都使用 rustfmt,以避免 Rust 代码风格之争:每个人都使用该工具格式化代码。
Rust 安装包默认包含 rustfmt,因此你的系统上应该已经有 rustfmt 和 cargo-fmt 这两个程序。这两个命令类似于 rustc 和 cargo:rustfmt 提供更细致的控制,而 cargo-fmt 了解使用 Cargo 的项目所遵循的约定。若要格式化任意 Cargo 项目,请运行:
$ cargo fmt
运行此命令会重新格式化当前 crate 中的所有 Rust 代码。它应该只改变代码风格,不会改变代码语义。有关 rustfmt 的更多信息,请参阅其文档。
使用 rustfix 修复代码
rustfix 随 Rust 一同安装,可以自动修复那些有明确解决方式的编译器警告。通常,这类修复正是你所需要的。你可能已经见过编译器警告,例如,考虑下面这段代码:
Filename: src/main.rs
fn main() {
let mut x = 42;
println!("{x}");
}
这里我们将变量 x 定义为可变变量,但实际上从未修改它。Rust 会对此发出警告:
$ 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 关键字。运行 cargo fix 命令即可使用 rustfix 工具自动应用这项建议:
$ 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 已经修改了代码:
Filename: src/main.rs
fn main() {
let x = 42;
println!("{x}");
}
现在变量 x 是不可变的,警告也不再出现。
你还可以使用 cargo fix 命令在不同 Rust 版本之间迁移代码。Rust 版本详见附录 E。
使用 Clippy 进行更多代码检查
Clippy 是一组用于分析代码的 lint,可以帮助你发现常见错误并改进 Rust 代码。标准 Rust 安装包中包含 Clippy。
若要对任意 Cargo 项目运行 Clippy 的 lint,请执行:
$ cargo clippy
例如,假设你编写了一个程序,像下面这样使用数学常量的近似值,例如圆周率:
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 的错误或警告:
fn main() {
let x = std::f64::consts::PI;
let r = 8.0;
println!("the area of the circle is {}", x * r * r);
}
為了幫助 IDE 集成,Rust 社区推荐使用 rust-analyzer。该工具是一组以编译器为中心的实用程序,使用语言服务器协议(Language Server Protocol)进行通信。该协议规定了 IDE 与编程语言如何彼此通信。不同客户端都可以使用 rust-analyzer,例如 Visual Studio Code 的 Rust Analyzer 插件。
请访问 rust-analyzer 项目的主页查看安装说明,然后在所用 IDE 中安装语言服务器支持。之后,IDE 将提供自动补全、跳转到定义以及行内错误提示等功能。