附录 D - 有用的开发工具
在本附录中,我们将讨论一些有用的开发工具,这些工具将 Rust project 提供。我们将介绍自动格式设置和快速应用 warning 修复程序、linter 以及与 IDE 集成。
使用 rustfmt
自动格式化
该工具根据社区代码样式重新格式化您的代码。
许多协作项目使用来防止关于哪个
style 来编写 Rust 时使用:每个人都使用该工具格式化他们的代码。rustfmt
rustfmt
要安装 ,请输入以下内容:rustfmt
$ rustup component add rustfmt
此命令会给你 和 ,类似于 Rust 给你
both 和 .要格式化任何 Cargo 项目,请输入以下内容:rustfmt
cargo-fmt
rustc
cargo
$ cargo fmt
运行此命令会重新格式化当前 crate 中的所有 Rust 代码。这
应该只更改代码样式,而不更改代码语义。了解更多信息
上,请参阅其文档。rustfmt
使用 rustfix
修复您的代码
rustfix 工具包含在 Rust 安装中,可以自动修复 编译器警告,这些警告具有明确方法可以纠正可能的问题 你想要什么。您以前可能已经看到过编译器警告。例如 请考虑以下代码:
文件名: src/main.rs
fn do_something() {} fn main() { for i in 0..100 { do_something(); } }
在这里,我们调用了 100 次函数,但我们从未使用
变量。Rust 警告我们:do_something
i
for
$ 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(); } }
loop 变量现在命名为 ,并且不再显示警告。for
_i
您还可以使用该命令在以下
不同的 Rust 版本。附录 E 中介绍了各个版本。cargo fix
使用 Clippy 进行更多 lints
Clippy 工具是一组 lint 文件,用于分析您的代码,以便您可以捕获 常见错误并改进您的 Rust 代码。
要安装 Clippy,请输入以下内容:
$ rustup component add clippy
要在任何 Cargo 项目上运行 Clippy 的 lints,请输入以下内容:
$ 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 已经具有更精确的常量
定义,并且如果您使用常量
相反。然后,您将更改代码以使用常量。这
以下代码不会导致 Clippy 出现任何错误或警告:PI
PI
文件名: 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 和编程语言的规范
相互通信。不同的客户端可以使用 ,例如用于 Visual Studio Code 的 Rust 分析器插件。rust-analyzer
访问项目的主页以获取安装说明,然后在您的
特定的 IDE。您的 IDE 将获得自动补全、跳转到
定义和内联错误。rust-analyzer
本文档由官方文档翻译而来,如有差异请以官方英文文档(https://doc.rust-lang.org/)为准