# Cargo.toml 與相依套件

`Cargo.toml` 描述套件是誰、用哪些外部套件、提供哪些可選功能；`Cargo.lock` 則記下實際用到的確切版本。

## package 區段

`Cargo.toml` 使用 TOML 格式：`[區段]` 底下是一行行 `鍵 = 值`。`cargo new` 產生的檔案只有最基本的三個欄位，其餘可依需要補上。

### 常用欄位

| 欄位 | 用途 |
| --- | --- |
| `name` | 套件名稱，也是預設的 crate 名稱（`-` 會換成 `_`） |
| `version` | 套件版本，格式為「主版號.次版號.修訂號」 |
| `edition` | 使用哪個 Rust 版次（edition），新專案是 `2024`，見 [版次](/evolution-editions) |
| `rust-version` | 最低支援的 Rust 版本（MSRV），太舊的編譯器會直接拒絕編譯 |
| `description`、`license` | 發佈到 crates.io 時需要的說明與授權 |

這些值在編譯時可以用 `env!("CARGO_PKG_...")` 讀到，常拿來印 `--version`。

目錄結構：

```text
greeter/
├── Cargo.toml
└── src/
    └── main.rs
```

`Cargo.toml`：

```toml
[package]
name = "greeter"
version = "0.3.1"
edition = "2024"
rust-version = "1.85"
description = "A tiny greeting tool"
license = "MIT"

[dependencies]
```

`src/main.rs`：

```rust
fn main() {
    println!("name: {}", env!("CARGO_PKG_NAME"));
    println!("version: {}", env!("CARGO_PKG_VERSION"));
    println!("description: {}", env!("CARGO_PKG_DESCRIPTION"));
    println!("rust-version: {}", env!("CARGO_PKG_RUST_VERSION"));
}
```

執行 `cargo run`，輸出：

```text
   Compiling greeter v0.3.1 (/path/to/greeter)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.11s
     Running `target/debug/greeter`
name: greeter
version: 0.3.1
description: A tiny greeting tool
rust-version: 1.85
```

`Compiling` 行實際會印出專案的絕對路徑，這裡改寫成 `/path/to/greeter`；耗時會因機器而異。

## 相依套件

別人發佈在 [crates.io](https://crates.io) 的函式庫稱為 crate。把它列進 `[dependencies]`，Cargo 就會自動下載、編譯並連結。本頁以專門處理版本號的 `semver` crate（1.0.28）示範，它沒有其他相依，下載很快。

### cargo add：加入相依

手動編輯 `Cargo.toml` 也可以，但 `cargo add` 會自動查最新版本、寫入正確格式並更新 `Cargo.lock`（Rust 1.62 起內建）。`--dev` 會加到只在測試與範例使用的 `[dev-dependencies]`。

範例（在 `greeter/` 目錄執行）：

```text
$ cargo add semver
```

輸出：

```text
    Updating crates.io index
      Adding semver v1.0.28 to dependencies
             Features:
             + std
             - serde
    Updating crates.io index
     Locking 1 package to highest Rust 1.85 compatible version
      Adding semver v1.0.28
```

之後 `Cargo.toml` 的最後兩行變成：

```toml
[dependencies]
semver = "1.0.28"
```

`Features` 底下 `+` 是預設啟用的功能、`-` 是可選但未啟用的功能（見本頁最後一節）。`Locking ... Rust 1.85 compatible` 表示 Cargo 會挑「支援 `rust-version` 的最新版本」，這是 Rust 1.84 起的 resolver 3 行為，在 2024 版次預設啟用。實際加入的版本取決於執行當下 crates.io 上的最新版。

### 版本需求的寫法

`semver = "1.0.28"` 的意思不是「只要 1.0.28」，而是「與 1.0.28 相容的任何版本」。Cargo 採用語意化版本（Semantic Versioning）：主版號不變就視為相容；主版號是 0 時，次版號改變就視為不相容。

| 寫法 | 意思 |
| --- | --- |
| `"1.2.3"` 或 `"^1.2.3"` | `>=1.2.3, <2.0.0` |
| `"^0.4.1"` | `>=0.4.1, <0.5.0` |
| `"~1.2.3"` | `>=1.2.3, <1.3.0`，只接受修訂版 |
| `"=1.2.3"` | 只要 1.2.3 |
| `">=1.2, <1.5"` | 自訂範圍 |
| `"*"` | 任何版本，發佈到 crates.io 時不允許 |

下面的程式用 `semver` crate 實際比對這些規則，`src/main.rs` 改成：

```rust
use semver::{Version, VersionReq};

fn main() {
    let reqs = ["1.2.3", "^0.4.1", "~1.2.3", "=1.2.3", ">=1.2, <1.5", "*"];
    let versions = ["1.2.3", "1.2.9", "1.3.0", "2.0.0", "0.4.7", "0.5.0"];

    for r in reqs {
        let req = VersionReq::parse(r).unwrap();
        let ok: Vec<&str> = versions
            .iter()
            .filter(|v| req.matches(&Version::parse(v).unwrap()))
            .copied()
            .collect();
        println!("{:<12} -> {:?}", r, ok);
    }
}
```

執行 `cargo run`，第一次會先下載並編譯相依，輸出：

```text
 Downloading crates ...
  Downloaded semver v1.0.28
   Compiling semver v1.0.28
   Compiling greeter v0.3.1 (/path/to/greeter)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.57s
     Running `target/debug/greeter`
1.2.3        -> ["1.2.3", "1.2.9", "1.3.0"]
^0.4.1       -> ["0.4.7"]
~1.2.3       -> ["1.2.3", "1.2.9"]
=1.2.3       -> ["1.2.3"]
>=1.2, <1.5  -> ["1.2.3", "1.2.9", "1.3.0"]
*            -> ["1.2.3", "1.2.9", "1.3.0", "2.0.0", "0.4.7", "0.5.0"]
```

注意：`VersionReq::parse` 與 `Version::parse` 回傳 `Result`，這裡的字串都是寫死的合法值才用 `unwrap`；處理使用者輸入時要改用 `match` 或 `?`，見 [Result](/errors-result)。

## Cargo.lock

### 鎖定確切版本與 cargo update

版本需求是一個範圍，但每次建置都該用同一組版本，否則今天能編譯、明天上游發新版就壞了。第一次解析相依時，Cargo 把選中的確切版本與檢查碼寫進 `Cargo.lock`，之後的建置都照它來。

`Cargo.lock`：

```toml
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "greeter"
version = "0.3.1"
dependencies = [
 "semver",
]

[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
```

不要手動改這個檔案。要換版本時用 `cargo update`：不帶參數會把所有相依升到範圍內最新；`-p 名稱 --precise 版本` 則指定某個套件的確切版本。下面先把 `Cargo.toml` 的需求放寬成 `semver = "1.0"`，再降版、升版：

```text
$ cargo update -p semver --precise 1.0.20
$ cargo update
```

輸出：

```text
    Updating crates.io index
 Downgrading semver v1.0.28 -> v1.0.20
    Updating crates.io index
     Locking 1 package to highest Rust 1.85 compatible version
    Updating semver v1.0.20 -> v1.0.28
```

`--precise` 指定的版本必須落在 `Cargo.toml` 的需求範圍內；需求是 `"1.0.28"` 時要求 1.0.20 會得到 `failed to select a version for the requirement` 錯誤。`cargo update` 升到的版本取決於當下 crates.io 的最新版。

`Cargo.lock` 應該跟著程式碼一起提交到版本控制，讓團隊成員與 CI 建出完全相同的結果。

## features

feature 是套件提供的可選功能開關，用來把不是人人需要的程式碼（與它帶來的相依）排除在編譯之外。

### 定義自己的 features

在 `[features]` 宣告名稱，`default` 列出預設啟用的項目。程式裡用 `#[cfg(feature = "名稱")]` 讓一段程式只在啟用時編譯，或用 `cfg!(feature = "名稱")` 得到一個 `bool`。

| 指令 | 啟用的 features |
| --- | --- |
| `cargo run` | `default` 裡的 `color` |
| `cargo run --features emoji` | `color`、`emoji` |
| `cargo run --no-default-features` | 無 |
| `cargo run --no-default-features --features emoji` | `emoji` |

`Cargo.toml`：

```toml
[package]
name = "badge"
version = "0.1.0"
edition = "2024"

[features]
default = ["color"]
color = []
emoji = []

[dependencies]
```

`src/main.rs`：

```rust
fn render(text: &str) -> String {
    let mut out = text.to_string();
    if cfg!(feature = "color") {
        out = format!("[green]{}[/green]", out);
    }
    #[cfg(feature = "emoji")]
    {
        out.push_str(" *");
    }
    out
}

fn main() {
    println!("{}", render("build passing"));
}
```

依表格順序執行四個指令（加上 `-q` 省略 `Compiling` 等訊息），輸出：

```text
[green]build passing[/green]
[green]build passing[/green] *
build passing
build passing *
```

注意：`--features` 指定不存在的名稱會直接失敗：`error: the package 'badge' does not contain this feature: rainbow`。feature 應該只「增加」功能，不要設計成啟用後移除或改變既有行為，因為同一個相依被多處使用時，所有人要求的 features 會合併啟用。

### 啟用相依套件的 features

相依套件也有自己的 features。`cargo add 名稱 --features 功能` 會寫成表格形式的相依宣告；`default-features = false` 則關掉對方的預設功能。下面在 `semver = "1.0"` 的 `greeter` 專案中啟用 `serde` 支援，再用 `cargo tree -e features` 看實際啟用了哪些功能（`cargo tree` 見 [開發工具](/modules-tools)）：

```text
$ cargo add semver --features serde
$ cargo tree -e features
```

輸出：

```text
    Updating crates.io index
      Adding semver v1.0 to dependencies
             Features as of v1.0.0:
             + serde
             + std
    Updating crates.io index
     Locking 7 packages to highest Rust 1.85 compatible versions
      Adding proc-macro2 v1.0.107
      Adding quote v1.0.47
      Adding serde v1.0.229
      Adding serde_core v1.0.229
      Adding serde_derive v1.0.229
      Adding syn v3.0.10
      Adding unicode-ident v1.0.27
 Downloading crates ...
  Downloaded serde_core v1.0.229
greeter v0.3.1 (/path/to/greeter)
├── semver feature "default"
│   ├── semver v1.0.28
│   │   └── serde_core v1.0.229
│   └── semver feature "std"
│       └── semver v1.0.28 (*)
└── semver feature "serde"
    └── semver v1.0.28 (*)
```

`Cargo.toml` 中的宣告變成：

```toml
semver = { version = "1.0", features = ["serde"] }
```

`Cargo.lock` 會記下相依可能用到的所有套件（7 個），但實際編譯的只有啟用的部分，所以 `cargo tree` 只多出 `serde_core`。各套件的版本號取決於執行當下 crates.io 的最新版。

## 重點整理

- `[package]` 描述套件本身，`name`、`version`、`edition` 是必要欄位，`rust-version` 宣告最低支援版本
- 用 `cargo add` 加相依，`--dev` 加到 `[dev-dependencies]`
- `"1.2.3"` 代表「相容於 1.2.3」的範圍，主版號 0 時次版號變動即不相容
- `Cargo.lock` 鎖住確切版本，交給 `cargo update` 修改，並提交到版本控制
- `[features]` 定義可選功能，程式用 `#[cfg(feature = "...")]` 切換；相依的 features 寫在相依宣告的 `features` 陣列

## 資料來源

- [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/)
