# cargo 指令總覽

cargo 是 Rust 的建置工具兼套件管理員，本頁逐一說明最常用的子指令各自做什麼、什麼時候用。

## 一張表看懂

| 指令 | 做什麼 | 什麼時候用 |
| --- | --- | --- |
| `cargo new` | 建立新專案 | 開新專案 |
| `cargo build` | 編譯，產物放 `target/` | 需要可執行檔 |
| `cargo run` | 編譯並執行 | 開發時最常用 |
| `cargo check` | 只做型別與借用檢查，不產生執行檔 | 寫程式時快速確認能否編譯 |
| `cargo test` | 編譯並執行測試 | 改完程式確認沒壞 |
| `cargo fmt` | 用 rustfmt 排版 | 存檔或提交前 |
| `cargo clippy` | 進階 lint，指出可改進的寫法 | 提交前、CI |
| `cargo doc` | 產生 HTML 文件 | 看自己或相依套件的 API |
| `cargo add` | 新增相依套件到 `Cargo.toml` | 要用第三方 crate |
| `cargo update` | 在版本規則內更新 `Cargo.lock` | 想拿到相依套件的修補版 |

本頁範例的輸出裡，`Compiling` 等行的路徑與耗時、測試執行檔的雜湊值，都會因機器而異。

## 建立專案

### cargo new 與 --lib

`cargo new 名稱` 建立執行檔（binary）專案，入口是 `src/main.rs`；加 `--lib` 建立函式庫（library）專案，入口是 `src/lib.rs`，裡面附一個範例函式和測試。兩者的差別：binary 編譯出可執行的程式，library 則是給其他程式 `use` 的程式碼。不在 git 儲存庫內時，cargo 會順便 `git init`。

範例：
```text
cargo new --lib mathkit
ls -a mathkit
cat mathkit/src/lib.rs
```

輸出：
```text
    Creating library `mathkit` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
.
..
.git
.gitignore
Cargo.toml
src
pub fn add(left: u64, right: u64) -> u64 {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}
```

## 編譯與執行

以下用一個 `cargo new greet` 建立的專案示範，`src/main.rs` 內容如下：

```rust
use std::env;

fn greeting(name: &str) -> String {
    if name.len() == 0 {
        return String::from("哈囉，陌生人");
    }
    format!("哈囉，{name}")
}

fn main() {
    let name = env::args().nth(1).unwrap_or_default();
    println!("{}", greeting(&name));
}

#[cfg(test)]
mod tests {
    use super::greeting;

    #[test]
    fn with_name() {
        assert_eq!(greeting("Ann"), "哈囉，Ann");
    }

    #[test]
    fn empty_name() {
        assert_eq!(greeting(""), "哈囉，陌生人");
    }
}
```

### cargo run 與傳參數

`cargo run` 會在需要時編譯，然後執行。要傳命令列參數給你的程式，放在 `--` 後面，否則 cargo 會以為是給它自己的選項。`-q` 隱藏 cargo 的狀態訊息。`cargo build` 只編譯不執行，產物在 `target/debug/`，加 `--release` 則開啟最佳化，見 [第一個 Rust 程式](/start-hello-world)。

範例：
```text
cargo run
cargo run -q -- Ann
```

輸出：
```text
   Compiling greet v0.1.0 (/tmp/greet)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
     Running `target/debug/greet`
哈囉，陌生人
哈囉，Ann
```

讀取命令列參數的方式見 [std::env](/pkg-env)。

### cargo check

`cargo check` 跑完編譯器的所有檢查（型別、借用、生命週期），但跳過產生機器碼的步驟，所以比 `cargo build` 快。寫程式時頻繁用它確認「能不能編譯」，要執行時才 `cargo run`。編輯器裡的 rust-analyzer 背後也是類似的檢查。

範例：
```text
cargo check
```

輸出：
```text
    Checking greet v0.1.0 (/tmp/greet)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.10s
```

## 品質檢查

### cargo test

`cargo test` 編譯並執行所有標記 `#[test]` 的函式，函式庫專案還會執行文件註解裡的範例。後面加一段文字可以只跑名稱包含它的測試，其餘算在 `filtered out`。測試的寫法見 [單元測試](/testing-unit)。

範例：
```text
cargo test
cargo test empty
```

輸出：
```text
   Compiling greet v0.1.0 (/tmp/greet)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running unittests src/main.rs (target/debug/build/greet/6248461cc6d98fb0/out/greet-6248461cc6d98fb0)

running 2 tests
test tests::empty_name ... ok
test tests::with_name ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

running 1 test
test tests::empty_name ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
```

上面第二段只節錄 `cargo test empty` 的測試結果部分。

### cargo clippy

clippy 是官方的 lint 工具，收錄數百條規則，抓出「能編譯、但有更好寫法」的程式碼。上面的 `greeting` 用 `name.len() == 0` 判斷空字串，編譯器不會抱怨，clippy 會建議改用 `is_empty()`。尚未安裝時執行 `rustup component add clippy`。

範例：
```text
cargo clippy
```

輸出：
```text
    Checking greet v0.1.0 (/tmp/greet)
warning: length comparison to zero
 --> src/main.rs:4:8
  |
4 |     if name.len() == 0 {
  |        ^^^^^^^^^^^^^^^ help: using `is_empty` is clearer and more explicit: `name.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: `greet` (bin "greet") generated 1 warning (run `cargo clippy --fix --bin "greet" -p greet -- ` to apply 1 suggestion)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
```

把那一行改成 `if name.is_empty() {` 再跑一次，就只剩 `Checking` 與 `Finished` 兩行。`cargo clippy --fix` 可以自動套用建議。

### cargo fmt

`cargo fmt` 把整個專案排版成官方風格；`cargo fmt --check` 只檢查，格式不符時印出差異並以結束碼 1 結束，格式正確則什麼都不印、結束碼 0。CI 通常放 `--check`。排版前後的對照見 [第一個 Rust 程式](/start-hello-world)。

範例：
```text
cargo fmt --check
echo "exit $?"
```

輸出：
```text
exit 0
```

## 文件

### cargo doc

`cargo doc` 從程式碼與 `///` 文件註解產生 HTML 文件，連相依套件的文件也一起產生，放在 `target/doc/`。加 `--open` 會直接用瀏覽器開啟。沒有網路時查相依套件 API 特別好用。文件註解的寫法見 [註解與文件註解](/basics-comments-docs)。

範例：
```text
cargo doc
ls target/doc
```

輸出：
```text
 Documenting greet v0.1.0 (/tmp/greet)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.10s
   Generated /tmp/greet/target/doc/greet/index.html
crates.js
greet
help.html
search.index
settings.html
src
src-files.js
static.files
```

## 相依套件

### cargo add

`cargo add 套件名`（Rust 1.62 起內建）從 crates.io 查詢最新相容版本，寫進 `Cargo.toml` 的 `[dependencies]`，並更新 `Cargo.lock`。下例加入錯誤處理套件 anyhow（1.0.105），寫 `cargo add anyhow@1` 則會記錄為 `"1"`。

範例：
```text
cargo add anyhow
grep -A1 dependencies Cargo.toml
```

輸出：
```text
    Updating crates.io index
      Adding anyhow v1.0.105 to dependencies
             Features:
             + std
             - backtrace
    Updating crates.io index
     Locking 1 package to highest Rust 1.100.0 compatible version
[dependencies]
anyhow = "1.0.105"
```

`+ std` 是預設開啟的功能（feature），`- backtrace` 是可選但未開啟的。加了卻沒在程式中使用的相依套件，`cargo build` 會以 `cargo::unused_dependencies` 警告提醒（Rust 1.100 起）。移除用 `cargo remove anyhow`。版本規則與 features 見 [Cargo.toml 與相依套件](/modules-cargo)。

接著在程式中使用它：

```rust
use anyhow::{Context, Result};

fn parse_age(text: &str) -> Result<u32> {
    let age = text
        .trim()
        .parse()
        .with_context(|| format!("年齡格式錯誤：{text:?}"))?;
    Ok(age)
}

fn main() -> Result<()> {
    println!("{}", parse_age(" 30 ")?);
    if let Err(e) = parse_age("三十") {
        println!("{e:#}");
    }
    Ok(())
}
```

```text
cargo run -q
```

輸出：
```text
30
年齡格式錯誤："三十": invalid digit found in string
```

### cargo update

`Cargo.toml` 寫的是版本範圍（`"1"` 代表 1.x 任一版），`Cargo.lock` 記錄實際選定的確切版本，讓每次建置結果一致。`cargo update` 在範圍內把 `Cargo.lock` 更新到最新版，不會改 `Cargo.toml`。下例先用 `--precise` 刻意降到舊版，再更新回最新。

範例：
```text
cargo update anyhow --precise 1.0.100
cargo update
```

輸出：
```text
    Updating crates.io index
 Downgrading anyhow v1.0.105 -> v1.0.100
    Updating crates.io index
     Locking 1 package to highest Rust 1.100.0 compatible version
    Updating anyhow v1.0.100 -> v1.0.105
```

注意：`cargo update` 不會跨過主版本號（例如 1.x 升到 2.0），那需要手動修改 `Cargo.toml`。`cargo update --dry-run` 只列出會變動的項目，不寫入檔案。

## 重點整理

- `cargo new` 建專案，`--lib` 建函式庫
- 寫程式時用 `cargo check` 快速檢查，要執行用 `cargo run`，參數放在 `--` 之後
- `cargo test` 跑測試，可加名稱篩選
- `cargo fmt` 排版、`cargo clippy` 找出更好的寫法，兩者都適合放進 CI
- `cargo doc --open` 產生並開啟含相依套件的文件
- `cargo add` 新增相依，`cargo update` 在版本範圍內更新 `Cargo.lock`

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
