本文 AI 產出,尚未審核

Rust 入門與環境設置:安裝 Rust(rustup、cargo)

簡介

在學習任何程式語言之前,先把開發環境安裝好是最基本也是最重要的一步。Rust 以安全、效能與現代化的語法著稱,官方提供的安裝工具 rustup 能一次管理多個 toolchain、更新與跨平台支援,讓開發者無需手動處理繁雜的相依性。
同時,Rust 的套件管理與建置系統 Cargo 已經成為業界標準。只要掌握 rustup 與 Cargo 的安裝與基本指令,就能快速建立、編譯、測試與發佈 Rust 專案,為後續的程式設計學習奠定穩固基礎。

本文將一步步說明如何在 Windows、macOS 與 Linux 上安裝 rustup、設定 Cargo,並提供實用的程式碼範例與最佳實踐,幫助 初學者 甚至 中級開發者 快速上手。


核心概念

1. rustup:Rust 的版本管理器

  • rustup 是官方推薦的安裝與管理工具,類似於 Node.js 的 nvm、Python 的 pyenv。
  • 它可以同時安裝 stable、beta、nightly 三條主要的 toolchain,並支援跨平台的 cross‑compilation
  • 安裝完成後,rustc(編譯器)與 cargo(套件管理工具)會自動加入系統 PATH,讓你在任何終端機都能直接呼叫。

安裝指令(跨平台通用)

# 以官方腳本方式安裝 rustup(macOS / Linux)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Windows 使用 PowerShell
# 以管理員身分執行
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force
iwr https://win.rustup.rs -UseBasicParsing | iex

⚠️ 小提醒:安裝過程會詢問是否將 ~/.cargo/bin 加入 PATH,建議直接選 Yes,避免之後手動調整。

檢查安裝是否成功

rustc --version   # 顯示類似 rustc 1.78.0 (2024‑03‑15)
cargo --version   # 顯示類似 cargo 1.78.0 (2024‑03‑15)
rustup --version  # 顯示 rustup 1.27.0 (2024‑03‑15)

2. Cargo:Rust 的建置與套件管理系統

  • Cargo 讓你只需要一條指令就能完成 專案初始化、依賴下載、編譯、測試、產生文件 等工作。
  • Cargo 會自動產生 Cargo.toml(類似 npm 的 package.json)與 Cargo.lock,確保所有開發者使用相同的相依版本。

建立第一個專案

# 在當前目錄下建立名為 hello_rust 的專案
cargo new hello_rust --bin
cd hello_rust

目錄結構說明

hello_rust/
├─ Cargo.toml          # 專案設定與依賴描述
└─ src/
   └─ main.rs         # 程式入口

編譯與執行

cargo build           # 只編譯,產生的執行檔在 target/debug/
cargo run             # 先編譯再執行,等同於 ./target/debug/hello_rust

3. 常用 Cargo 指令

指令 功能說明
cargo check 快速檢查語法與型別(不產生 binary),適合開發時使用
cargo test 執行 tests 模組與 #[test] 標記的單元測試
cargo doc --open 產生 API 文件並在瀏覽器開啟
cargo update 更新 Cargo.lock 中的相依套件至最新符合版本範圍的版本
cargo clean 移除 target/ 目錄,釋放磁碟空間

4. 程式碼範例

範例 1:使用外部 Crate(rand)產生隨機數

// Cargo.toml
[dependencies]
rand = "0.8"   // 加入 rand 套件

// src/main.rs
use rand::Rng;   // 引入 trait

fn main() {
    // 建立隨機數產生器
    let mut rng = rand::thread_rng();
    // 產生 1~100 的隨機整數
    let n: u32 = rng.gen_range(1..=100);
    println!("隨機數字: {}", n);
}

說明cargo build 時會自動下載 randcargo run 即可看到隨機結果。

範例 2:建立自訂 Library 並在 Binary 中使用

# 建立 library 專案
cargo new my_math --lib
cd my_math
// my_math/src/lib.rs
/// 計算兩個整數的最大公因數 (GCD)
pub fn gcd(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        let r = a % b;
        a = b;
        b = r;
    }
    a
}
# 在同一工作區加入 binary
cargo new my_app --bin
cd my_app
# 編輯 Cargo.toml,加入 my_math 為路徑依賴
[dependencies]
my_math = { path = "../my_math" }
// my_app/src/main.rs
use my_math::gcd;

fn main() {
    let (x, y) = (48, 18);
    println!("GCD of {} and {} is {}", x, y, gcd(x, y));
}

說明:透過 workspace 或相對路徑,你可以在同一倉庫內管理多個 crate,提升程式碼重用性。

範例 3:使用 Cargo 設定多目標交叉編譯(Windows → Linux)

# 安裝目標平台的 toolchain
rustup target add x86_64-unknown-linux-gnu

# 編譯成 Linux 可執行檔(在 Windows 上執行)
cargo build --release --target x86_64-unknown-linux-gnu

產生的檔案位於 target/x86_64-unknown-linux-gnu/release/your_binary,可直接在 Linux 系統上執行。

範例 4:自動化測試與 CI(GitHub Actions)

# .github/workflows/rust.yml
name: Rust CI

on:
  push:
    branches: [ main ]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Rust toolchain
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          override: true
      - name: Cargo build
        run: cargo build --verbose
      - name: Cargo test
        run: cargo test --verbose

說明:只要把程式碼 push 到 GitHub,CI 就會自動編譯、測試,確保每次提交都是可編譯且通過測試的。

範例 5:產生文件並自訂主題

# 產生 API 文件
cargo doc --no-deps --document-private-items

# 開啟瀏覽器預覽
cargo doc --open

Cargo.toml 中加入:

[package.metadata.docs.rs]
all-features = true

即可在 docs.rs 上自動顯示完整文件。


常見陷阱與最佳實踐

陷阱 可能原因 解決方式
cargo: command not found PATH 未正確加入 ~/.cargo/bin(或 %USERPROFILE%\.cargo\bin 重新開啟終端機或手動將路徑加入環境變數
rustup update 失敗,顯示 SSL 錯誤 系統缺少根憑證或使用代理 安裝或更新 ca-certificates,或在 ~/.cargo/config.toml 設定 http.proxy
依賴版本衝突(semver 不相容) 多個 crate 依賴不同的次要版本 使用 cargo update -p <crate> 鎖定特定版本,或在 Cargo.toml 加上 patch
交叉編譯失敗找不到系統庫 目標平台需要外部 C 函式庫(例如 OpenSSL) 安裝對應平台的開發套件(apt-get install libssl-devbrew install openssl
cargo test 無法執行異步測試 測試函式忘記加上 #[tokio::test]async-std::test 確認使用的 async 執行時與測試屬性相符

最佳實踐

  1. 使用 rustup default stable:除非特別需要新特性,保持在 stable 版可獲得最穩定的生產環境。
  2. Cargo.lock 版控:對於 binary 專案(非 library)務必提交 Cargo.lock,確保每次建置使用相同相依版本。
  3. 定期執行 cargo fmtcargo clippy:自動格式化與 lint 能提前發現潛在問題。
  4. 分離開發與發佈環境:在 CI 中使用 --release 產生最佳化的二進位檔,避免在本機 debug 時產生過大檔案。
  5. 善用 workspaces:大型專案或多套件庫時,使用 Cargo.toml[workspace] 能統一管理相依、加速編譯。

實際應用場景

場景 為什麼需要 rustup & Cargo 具體操作
嵌入式開發(ARM Cortex‑M) 需要交叉編譯到 thumbv7em-none-eabihf 等目標 rustup target add thumbv7em-none-eabihf + cargo build --release --target thumbv7em-none-eabihf
WebAssembly 前端 產出 .wasm 模組供 JavaScript 呼叫 rustup target add wasm32-unknown-unknowncargo build --target wasm32-unknown-unknown --release
微服務(Docker) Dockerfile 中直接使用 rustup 安裝,確保映像檔一致 FROM rust:1.78-slimCOPY . .RUN cargo build --release
資料科學(Python 互操作) 使用 pyo3 建立 Rust 擴充套件 Cargo.toml 加入 pyo3,使用 maturinsetuptools-rust 產生 wheel
CI/CD(GitHub Actions、GitLab CI) 只要在 workflow 裡呼叫 actions-rs/toolchain 即可自動安裝最新 stable 如前面範例的 rust.yml,不需自行安裝 rustup

總結

  • rustup 是 Rust 生態系統的核心入口,負責安裝、更新、切換不同的 toolchain,讓開發者可以輕鬆在 stable、beta、nightly 之間切換。
  • Cargo 則是「一站式」的建置、套件管理與測試工具,從 cargo newcargo buildcargo publish,全部只需一條指令。
  • 只要掌握上述安裝步驟與常用指令,你就能在任何平台快速建立、測試、部署 Rust 程式,並且藉由 工作區(workspace)交叉編譯CI 整合,在實務專案中發揮最大效益。

下一步:完成環境設置後,建議立即嘗試「Hello, world!」以外的範例(如 randserdetokio),體驗 Cargo 的依賴管理與測試流程,為日後開發更大型的系統打下堅實基礎。祝你在 Rust 的旅程中 安全、快速、快樂