開發工具

最後更新


Rust 工具鏈內建格式化、靜態檢查、文件產生與相依樹查詢,再搭配編輯器的 rust-analyzer,就是日常開發的完整工具組。

安裝與總覽


rustup 預設安裝的 profile 已包含 rustfmt 與 clippy;如果是用 minimal profile 安裝,或執行時出現找不到指令的訊息,用下面的指令補上(工具鏈管理見 安裝 Rust 與開發環境):
  1. $ rustup component add rustfmt clippy

工具指令用途
rustfmtcargo fmt把程式碼排成官方統一風格
clippycargo clippy抓出可以寫得更好或可能有錯的寫法
rust-analyzer編輯器外掛補全、跳轉定義、即時錯誤提示
rustdoccargo doc從 /// 註解產生 HTML 文件
cargo treecargo tree列出相依套件的樹狀關係

本頁使用的版本是 rustfmt 1.11.0-stable 與 clippy 0.1.100,隨 Rust 1.100.0 發佈。

rustfmt:統一格式


cargo fmt 與 --check


Rust 社群幾乎所有專案都用 rustfmt 的預設風格,所以讀別人的程式碼時版面都很熟悉,code review 也不必再爭論空格與換行。cargo fmt 直接改寫檔案;cargo fmt --check 只列出差異、不改檔,有差異時結束碼為 1,適合放進 CI。
tidy/src/main.rs(格式凌亂的版本):
  1. fn total(items:&[u32])->u32{
  2. let mut sum=0;
  3. for x in items { sum+=x; }
  4. sum
  5. }
  6. fn main(){
  7. let prices=vec![120,80,45];
  8. println!("total = {}",total(&prices));
  9. }

執行 cargo fmt --check,輸出:
  1. Diff in /path/to/tidy/src/main.rs:1:
  2. -fn total(items:&[u32])->u32{
  3. - let mut sum=0;
  4. - for x in items { sum+=x; }
  5. +fn total(items: &[u32]) -> u32 {
  6. + let mut sum = 0;
  7. + for x in items {
  8. + sum += x;
  9. + }
  10. sum
  11. }
  12. Diff in /path/to/tidy/src/main.rs:7:
  13. -fn main(){
  14. - let prices=vec![120,80,45];
  15. - println!("total = {}",total(&prices));
  16. +fn main() {
  17. + let prices = vec![120, 80, 45];
  18. + println!("total = {}", total(&prices));
  19. }

Diff in 後面實際是檔案的絕對路徑,這裡改寫成 /path/to/tidy;在終端機裡 -/+ 行會以紅綠色顯示。接著執行 cargo fmt,檔案就變成 + 那一側的樣子,再執行 cargo run -q 輸出 total = 245。
想調整風格時,在專案根目錄放 rustfmt.toml(例如 max_width = 80),但多數專案維持預設。

clippy:更嚴格的檢查


cargo clippy 的建議


編譯器只擋「錯的」程式,clippy 則再多看一層:寫法冗長、效能較差、容易誤用的地方都會提出警告,並附上建議改法與說明連結。新手很適合把它當成「隨身導師」,從警告學到慣用寫法(idiomatic Rust)。
下面的程式能正常編譯、cargo build 沒有任何警告,但不夠道地:
  1. fn total(items: &[u32]) -> u32 {
  2. let mut sum = 0;
  3. for i in 0..items.len() {
  4. sum += items[i];
  5. }
  6. sum
  7. }
  8. fn main() {
  9. let prices = vec![120, 80, 45];
  10. if prices.len() == 0 {
  11. return;
  12. }
  13. println!("total = {}", total(&prices));
  14. }

執行 cargo clippy,輸出:
  1. Checking tidy v0.1.0 (/path/to/tidy)
  2. warning: the loop variable `i` is only used to index `items`
  3. --> src/main.rs:3:14
  4. |
  5. 3 | for i in 0..items.len() {
  6. | ^^^^^^^^^^^^^^
  7. |
  8. note: for this index operation
  9. --> src/main.rs:4:16
  10. |
  11. 4 | sum += items[i];
  12. | ^^^^^^^^
  13. = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#needless_range_loop
  14. = note: `#[warn(clippy::needless_range_loop)]` on by default
  15. help: consider using an iterator
  16. |
  17. 3 - for i in 0..items.len() {
  18. 3 + for <item> in &items {
  19. |
  20. warning: length comparison to zero
  21. --> src/main.rs:11:8
  22. |
  23. 11 | if prices.len() == 0 {
  24. | ^^^^^^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `prices.is_empty()`
  25. |
  26. = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#len_zero
  27. = note: `#[warn(clippy::len_zero)]` on by default
  28. warning: `tidy` (bin "tidy") generated 2 warnings (run `cargo clippy --fix --bin "tidy" -p tidy -- ` to apply 1 suggestion)
  29. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s

依建議改用迭代器(見 迭代器)與 is_empty:
  1. fn total(items: &[u32]) -> u32 {
  2. items.iter().sum()
  3. }
  4. fn main() {
  5. let prices = vec![120, 80, 45];
  6. if prices.is_empty() {
  7. return;
  8. }
  9. println!("total = {}", total(&prices));
  10. }

再執行 cargo clippy 與 cargo run -q,輸出:
  1. Checking tidy v0.1.0 (/path/to/tidy)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
  3. total = 245

Checking 表示 clippy 只做型別檢查、不產生執行檔,所以比 cargo build 快。耗時會因機器而異。
注意:clippy 的警告預設不會讓建置失敗;CI 裡常用 cargo clippy -- -D warnings 把警告升級成錯誤。真的需要保留某個寫法時,可以在該項目上加 #[allow(clippy::len_zero)] 這類屬性關掉單一檢查,或在 Cargo.toml 的 [lints] 表統一設定(Rust 1.74 起)。

rust-analyzer:編輯器整合


rust-analyzer 是 Rust 官方的語言伺服器(Language Server),提供程式碼補全、跳到定義、顯示推斷出的型別、即時標示編譯錯誤、一鍵套用 clippy 的修正建議等功能。它是編輯器背後的服務,平常不需要在終端機直接執行。
編輯器安裝方式
VS Code擴充功能市集搜尋「rust-analyzer」
Zed、RustRover內建 Rust 支援
Neovim、Helix、Emacs透過 LSP 設定指向 rust-analyzer

Rust 1.64 起,rustup component add rust-analyzer 可以安裝與工具鏈同版的 rust-analyzer;VS Code 擴充功能則會自帶一份,通常不必另外安裝。它以 Cargo.toml 理解專案結構,所以開啟編輯器時要開專案根目錄(工作區則開工作區根目錄,見 工作區)。

cargo doc:產生 API 文件


從文件註解產生 HTML


/// 寫在項目前面是文件註解,//! 寫在檔案開頭描述整個模組或 crate(寫法見 註解與文件註解)。cargo doc 呼叫 rustdoc 把它們轉成和 doc.rust-lang.org 相同樣式的 HTML;--no-deps 只產生自己套件的文件,--open 會在產生後用瀏覽器開啟。
stats/src/lib.rs:
  1. //! Small helpers for summarizing numbers.
  2. /// Returns the arithmetic mean of `values`.
  3. ///
  4. /// Returns `None` when `values` is empty.
  5. pub fn mean(values: &[f64]) -> Option<f64> {
  6. if values.is_empty() {
  7. return None;
  8. }
  9. Some(values.iter().sum::<f64>() / values.len() as f64)
  10. }
  11. /// A closed range of observed values.
  12. pub struct Span {
  13. /// Smallest value seen.
  14. pub min: f64,
  15. /// Largest value seen.
  16. pub max: f64,
  17. }

  1. $ cargo doc --no-deps
  2. $ ls target/doc/stats

輸出:
  1. Documenting stats v0.1.0 (/path/to/stats)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s
  3. Generated /path/to/stats/target/doc/stats/index.html
  4. all.html
  5. fn.mean.html
  6. index.html
  7. sidebar-items.js
  8. struct.Span.html

Documenting 與 Generated 行實際是絕對路徑,這裡改寫成 /path/to/stats。每個公開項目各有一個頁面(fn.mean.html、struct.Span.html),私有項目預設不會出現。文件裡的程式碼範例還能被當成測試執行,見 文件測試。

cargo tree:看相依關係


列出、反查與限制深度


相依套件還會有自己的相依,專案大了很難知道某個 crate 是被誰拉進來的。cargo tree 把整棵樹印出來:-i 名稱(invert)反過來列出「誰依賴它」,--depth 1 只看直接相依,-e features 顯示啟用的 features(見 Cargo.toml 與相依套件)。
先在 stats 加入 itertools(0.15.0,提供許多額外的迭代器方法):
  1. $ cargo add itertools

Cargo.toml 的 [dependencies] 變成:
  1. [dependencies]
  2. itertools = "0.15.0"

再讓 stats/src/lib.rs 實際用到它:在 //! 那行之後加入 use,並在檔案結尾加上 span 函式(Span 結構沿用上一節):
  1. use itertools::{Itertools, MinMaxResult};
  2. /// Returns the smallest and largest of `values`.
  3. pub fn span(values: &[f64]) -> Option<Span> {
  4. match values.iter().copied().minmax() {
  5. MinMaxResult::NoElements => None,
  6. MinMaxResult::OneElement(x) => Some(Span { min: x, max: x }),
  7. MinMaxResult::MinMax(min, max) => Some(Span { min, max }),
  8. }
  9. }

接著執行:
  1. $ cargo tree
  2. $ cargo tree -i either
  3. $ cargo tree --depth 1

輸出:
  1. stats v0.1.0 (/path/to/stats)
  2. └── itertools v0.15.0
  3. └── either v1.19.0
  4. either v1.19.0
  5. └── itertools v0.15.0
  6. └── stats v0.1.0 (/path/to/stats)
  7. stats v0.1.0 (/path/to/stats)
  8. └── itertools v0.15.0

either 不是直接相依,而是 itertools 帶進來的間接相依,所以 --depth 1 看不到它。第一次執行時,前面還會多出 Downloading crates ... 等下載訊息;套件版本取決於執行當下 crates.io 的最新版,本地套件後面括號裡的絕對路徑改寫成 /path/to/stats。
注意:Rust 1.100 起,Cargo 預設會對 [dependencies] 裡列了卻從未使用的套件發出 unused dependency 警告(cargo::unused_dependencies lint),所以加了相依就要真的用到,或用 cargo remove 移除。

重點整理


  • cargo fmt 套用官方格式,cargo fmt --check 在 CI 檢查格式
  • cargo clippy 提供慣用寫法建議,-- -D warnings 讓警告變成錯誤
  • rust-analyzer 是編輯器背後的語言伺服器,開專案根目錄才能正確理解結構
  • cargo doc --no-deps --open 從 /// 與 //! 產生並開啟 API 文件
  • cargo tree 看相依樹,-i 反查某個 crate 被誰引入

資料來源