Rust rustup cargo Hello World

[Rust] 環境建置

Rust 不像直譯語言裝個 runtime 就能開跑,它是「編譯器 + 套件管理 + 工具鏈」一整套。這篇把 Windows 上的安裝、第一支程式、cargo 必懂指令一次串完,後面所有 Rust 篇都假設環境已經就緒。

Rust 工具鏈組成

下面這幾個名詞後面會反覆出現,先把分工釐清:

工具角色
rustup工具鏈管理器,負責安裝、更新、切換 Rust 版本
rustc編譯器本體
cargo套件管理 + 建置 + 測試一站式工具
rustfmt程式碼格式化
clippy靜態分析 / lint

實務上幾乎不會直接呼叫 rustc所有事情都交給 cargo,它背後會自己叫 rustc

在 Windows 安裝

rustup.rs 下載 rustup-init.exe,雙擊執行,看到選單時選 1(預設安裝)

安裝過程會提示你裝 Visual Studio Build Tools(C++ 工具鏈,連結器要用)。還沒裝的話照提示走 Visual Studio Installer,勾「使用 C++ 的桌面開發」即可。

裝完關掉舊的 PowerShell / cmd,開新視窗驗證:

rustc --version
# rustc 1.86.0 (xxxxxxxxx 2026-xx-xx)

cargo --version
# cargo 1.86.0 (xxxxxxxxx 2026-xx-xx)

兩個指令都吐版本號就 OK。

日後升級用 rustup update;要在 stable / nightly 之間切就 rustup default stablerustup default nightly。Rust 採滾動發行,每六週一個 stable,跟著升不會出事。

VS Code 設定

只要兩個 extension:

  1. rust-analyzer — 官方 LSP,補全、跳轉、即時錯誤都靠它
  2. CodeLLDB — 偵錯器(要設斷點再裝)

不要裝舊的那個叫 Rust 的 extension,已經被 rust-analyzer 取代。兩個一起裝會打架。

第一個專案:cargo new

裝好後第一件事不是寫 code,是讓 cargo 幫你開專案:

cargo new hello_rust
cd hello_rust

這會生出一個標準骨架:

hello_rust/
├── Cargo.toml      # 專案描述(角色類似 package.json)
├── .gitignore
└── src/
    └── main.rs     # 程式進入點

Cargo.toml

[package]
name = "hello_rust"
version = "0.1.0"
edition = "2024"

[dependencies]

src/main.rs

fn main() {
    println!("Hello, world!");
}

fn main() 是程式進入點,這跟 C / Java / Go 都一樣。

跑起來:cargo run

cargo run

cargo run 做三件事:

  1. 編譯 src/main.rs → 產生 target/debug/hello_rust.exe
  2. 執行那支 exe
  3. stdout 看到 Hello, world!

只想編譯不執行:

cargo build              # debug 版(含偵錯資訊,較大)
cargo build --release    # release 版(最佳化,較快、較小)

只想做型別檢查、不產生 binary:

cargo check

日常開發其實 cargo check 跑最多——它跳過 LLVM 的程式碼產生階段,比 cargo build 快很多。先確認程式碼合法,編譯細節留給最後一次 build

println! 為什麼有驚嘆號

第一支程式裡的 println! 不是函式,是巨集(macro)。Rust 規定「以 ! 結尾的呼叫都是巨集」,看到 ! 就知道這是編譯期展開的東西,不是普通呼叫。

為什麼需要巨集?Rust 的函式參數數量、型別都必須固定,而 println! 要吃任意數量參數的格式化字串,只有編譯期展開的巨集做得到。

fn main() {
    let name = "Jeremy";
    let age = 30;
    println!("{} is {} years old", name, age);

    // 具名插值(Rust 2021+)
    println!("{name} is {age} years old");

    // 印出除錯格式(後面會用來看 Vec、struct 等)
    let v = vec![1, 2, 3];
    println!("{:?}", v);   // [1, 2, 3]
    println!("{:#?}", v);  // 多行 pretty-print
}

{:?} 對應 Debug trait,{} 對應 Display trait——這兩個 trait 留到 trait 篇細講,現在只要記得「{} 印給人看、{:?} 印給 debug 用」。

常用 cargo 指令速查

整個 Rust 系列你會反覆用到的就這些:

cargo new <name>           # 新建 binary 專案
cargo new <name> --lib     # 新建 library 專案
cargo run                  # 編譯並執行
cargo build                # 編譯
cargo check                # 只做型別檢查(最快)
cargo test                 # 跑測試
cargo fmt                  # 格式化
cargo clippy               # lint 檢查
cargo add <crate>          # 新增依賴(會更新 Cargo.toml)
cargo doc --open           # 產生並打開文件

裝完工具鏈、跑得起 cargo run、看得懂 Cargo.tomlmain.rs 的角色就算就緒。下一篇進變數、可變性與基本型別,這裡的 cargo run 會從頭用到尾。

Latest Updates

  • 2026.06.11 Content updated