開發工具
最後更新
Rust 工具鏈內建格式化、靜態檢查、文件產生與相依樹查詢,再搭配編輯器的 rust-analyzer,就是日常開發的完整工具組。
安裝與總覽
rustup 預設安裝的 profile 已包含 rustfmt 與 clippy;如果是用 minimal profile 安裝,或執行時出現找不到指令的訊息,用下面的指令補上(工具鏈管理見 安裝 Rust 與開發環境):- $ rustup component add rustfmt clippy
| 工具 | 指令 | 用途 |
|---|---|---|
| rustfmt | cargo fmt | 把程式碼排成官方統一風格 |
| clippy | cargo clippy | 抓出可以寫得更好或可能有錯的寫法 |
| rust-analyzer | 編輯器外掛 | 補全、跳轉定義、即時錯誤提示 |
| rustdoc | cargo doc | 從 /// 註解產生 HTML 文件 |
| cargo tree | cargo 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(格式凌亂的版本):- fn total(items:&[u32])->u32{
- let mut sum=0;
- for x in items { sum+=x; }
- sum
- }
- fn main(){
- let prices=vec![120,80,45];
- println!("total = {}",total(&prices));
- }
執行
cargo fmt --check,輸出:- Diff in /path/to/tidy/src/main.rs:1:
- -fn total(items:&[u32])->u32{
- - let mut sum=0;
- - for x in items { sum+=x; }
- +fn total(items: &[u32]) -> u32 {
- + let mut sum = 0;
- + for x in items {
- + sum += x;
- + }
- sum
- }
-
- Diff in /path/to/tidy/src/main.rs:7:
- -fn main(){
- - let prices=vec![120,80,45];
- - println!("total = {}",total(&prices));
- +fn main() {
- + let prices = vec![120, 80, 45];
- + println!("total = {}", total(&prices));
- }
-
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 沒有任何警告,但不夠道地:- fn total(items: &[u32]) -> u32 {
- let mut sum = 0;
- for i in 0..items.len() {
- sum += items[i];
- }
- sum
- }
- fn main() {
- let prices = vec![120, 80, 45];
- if prices.len() == 0 {
- return;
- }
- println!("total = {}", total(&prices));
- }
執行
cargo clippy,輸出:- Checking tidy v0.1.0 (/path/to/tidy)
- warning: the loop variable `i` is only used to index `items`
- --> src/main.rs:3:14
- |
- 3 | for i in 0..items.len() {
- | ^^^^^^^^^^^^^^
- |
- note: for this index operation
- --> src/main.rs:4:16
- |
- 4 | sum += items[i];
- | ^^^^^^^^
- = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#needless_range_loop
- = note: `#[warn(clippy::needless_range_loop)]` on by default
- help: consider using an iterator
- |
- 3 - for i in 0..items.len() {
- 3 + for <item> in &items {
- |
- warning: length comparison to zero
- --> src/main.rs:11:8
- |
- 11 | if prices.len() == 0 {
- | ^^^^^^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `prices.is_empty()`
- |
- = help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.100.0/index.html#len_zero
- = note: `#[warn(clippy::len_zero)]` on by default
- warning: `tidy` (bin "tidy") generated 2 warnings (run `cargo clippy --fix --bin "tidy" -p tidy -- ` to apply 1 suggestion)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
依建議改用迭代器(見 迭代器)與
is_empty:- fn total(items: &[u32]) -> u32 {
- items.iter().sum()
- }
- fn main() {
- let prices = vec![120, 80, 45];
- if prices.is_empty() {
- return;
- }
- println!("total = {}", total(&prices));
- }
再執行
cargo clippy 與 cargo run -q,輸出:- Checking tidy v0.1.0 (/path/to/tidy)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.03s
- 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:- //! Small helpers for summarizing numbers.
- /// Returns the arithmetic mean of `values`.
- ///
- /// Returns `None` when `values` is empty.
- pub fn mean(values: &[f64]) -> Option<f64> {
- if values.is_empty() {
- return None;
- }
- Some(values.iter().sum::<f64>() / values.len() as f64)
- }
- /// A closed range of observed values.
- pub struct Span {
- /// Smallest value seen.
- pub min: f64,
- /// Largest value seen.
- pub max: f64,
- }
- $ cargo doc --no-deps
- $ ls target/doc/stats
輸出:
- Documenting stats v0.1.0 (/path/to/stats)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s
- Generated /path/to/stats/target/doc/stats/index.html
- all.html
- fn.mean.html
- index.html
- sidebar-items.js
- 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,提供許多額外的迭代器方法):- $ cargo add itertools
Cargo.toml 的 [dependencies] 變成:- [dependencies]
- itertools = "0.15.0"
再讓
stats/src/lib.rs 實際用到它:在 //! 那行之後加入 use,並在檔案結尾加上 span 函式(Span 結構沿用上一節):- use itertools::{Itertools, MinMaxResult};
- /// Returns the smallest and largest of `values`.
- pub fn span(values: &[f64]) -> Option<Span> {
- match values.iter().copied().minmax() {
- MinMaxResult::NoElements => None,
- MinMaxResult::OneElement(x) => Some(Span { min: x, max: x }),
- MinMaxResult::MinMax(min, max) => Some(Span { min, max }),
- }
- }
接著執行:
- $ cargo tree
- $ cargo tree -i either
- $ cargo tree --depth 1
輸出:
- stats v0.1.0 (/path/to/stats)
- └── itertools v0.15.0
- └── either v1.19.0
- either v1.19.0
- └── itertools v0.15.0
- └── stats v0.1.0 (/path/to/stats)
- stats v0.1.0 (/path/to/stats)
- └── 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 被誰引入