附录 D:实用开发工具¶
这份附录是什么: Rust 官方工具链的四件套速览——格式化、自动修错、代码检查、IDE 集成。 每个都自带、每个都只要一条命令。主题只有一句:把"风格与惯用法"交给工具,别交给 code review。
1. 四件套¶
① rustfmt / cargo fmt:自动格式化。 cargo fmt 按社区风格重排整个 crate 的代码——只动风格、不动语义。协作项目的标准做法:人人都跑 fmt,风格争论直接消失1。
② rustfix:自动应用编译器的修复建议。 有些警告自带"改成这样就能好"的建议(比如忘了写 mut),cargo fix 批量应用。书里演示:一个无害的多余 mut 警告,rustfix 自己修好2。
③ cargo clippy:惯用法检查器(linter)。 编译器 rustc 管"对不对";clippy 管"地道不地道"——它内置几百条社区沉淀的规则。书里的例子:代码里写了 let x = 3.14;,clippy 报错"你大概想用 std::f64::consts::PI"(近似常数规则),并给出修正建议。CI 里常把 clippy 警告当错误拦3。
④ rust-analyzer:IDE 能力的发动机。 语言服务器(实现 LSP 协议),给 VS Code 等编辑器提供自动补全、跳转到定义、行内错误提示(边写边看到 borrow checker 的抱怨)。书在第 1 章就提过 Rust 团队通过 rust-analyzer 专注做好 IDE 支持,这里是它的正式介绍4。
2. 定位:它们在工具链中的分工¶
编译器 rustc 对不对(类型/借用)——错误,拒编
clippy 地道不地道(惯用法)——通常是警告
rustfmt 好不好看(风格)——直接替你改
rustfix 编译器建议的批量执行者
rust-analyzer 以上一切的编辑器界面
图说:从"拒编"到"替你改",自动化程度递增。
3. 作者的判断与证据¶
判断(我们的,不是书里的): 四件套共享一个工程哲学:可自动化的规范不要人盯。 这和 Rust 全书的气质一致——编译器管正确性,这里四件工具接管风格和惯用法; code review 的注意力因此被省下来给真正的设计问题。 如果错,会错在: clippy 的部分 lint 对新手的"我的代码怎么了"造成噪音 (某些惯用法规则只有老手才觉得显然);把 clippy 当硬性门禁的项目需要花时间裁 lint 清单。
4. 可带走的¶
cargo fmt:提交前跑一遍,风格零争论。- 编译器说"考虑加上 mut"时:
cargo fix。 cargo clippy:比编译器多管一层惯用法。- 编辑器装 rust-analyzer,行内报错边写边见。
5. 原文地图¶
| 主题 | 原书章 | 原文位置 |
|---|---|---|
| rustfmt / cargo fmt | Appendix D: Useful Development Tools | text/32-apx-d-appendix-d-useful-development-tools.txt:8(搜「Automatic Formatting」) |
| rustfix | 同上 | text/32-apx-d-appendix-d-useful-development-tools.txt:24(搜「rustfix」) |
| clippy 与 PI 例子 | 同上 | text/32-apx-d-appendix-d-useful-development-tools.txt:78(搜「cargo clippy」) |
| rust-analyzer / IDE | 同上 | text/32-apx-d-appendix-d-useful-development-tools.txt:6(搜「integrating with IDEs」) |
-
出处:「Appendix D: Useful Development Tools」第 8 段(
text/32-apx-d-appendix-d-useful-development-tools.txt:8,搜「Automatic Formatting」)。 ↩↩ -
出处:「Appendix D: Useful Development Tools」第 24 段(
text/32-apx-d-appendix-d-useful-development-tools.txt:24,搜「rustfix」)。 ↩ -
出处:「Appendix D: Useful Development Tools」第 78 段(
text/32-apx-d-appendix-d-useful-development-tools.txt:78,搜「cargo clippy」)。 ↩↩ -
出处:「Appendix D: Useful Development Tools」第 6 段(
text/32-apx-d-appendix-d-useful-development-tools.txt:6,搜「integrating with IDEs」)。 ↩