第一個 Rust 程式

最後更新


從一行 println! 開始,學會用 rustc 直接編譯單一檔案、用 cargo 建立與執行專案、切換 release 模式,以及用 rustfmt 統一排版。

最小的 Rust 程式


先確認已經裝好工具鏈,見 安裝 Rust 與開發環境。

fn main 與 println!


Rust 程式從 main 函式開始執行。fn 宣告函式,main 沒有參數也沒有回傳值。println! 把文字印到終端機並換行。每個陳述式以分號結尾,縮排慣例是 4 個空白。
建立 main.rs:
範例:
  1. fn main() {
  2. println!("Hello, Rust!");
  3. }

在同一個目錄執行:
  1. rustc --edition 2024 main.rs
  2. ./main

輸出:
  1. Hello, Rust!

Windows 上產生的是 main.exe,執行時輸入 .\main.exe。

println! 是巨集,不是函式


名稱後面的 ! 表示這是巨集(macro)。巨集在編譯期展開成程式碼,所以能做到一般函式做不到的事:參數數量不固定、在編譯期檢查格式字串。{} 是佔位符,依序填入後面的參數;{lang} 直接印出同名變數(Rust 1.58 起)。
巨集用途
println!印到標準輸出並換行
print!印到標準輸出,不換行
eprintln!印到標準錯誤(stderr),用於錯誤訊息

範例:
  1. fn main() {
  2. let lang = "Rust";
  3. let year = 2015;
  4. print!("{lang} 1.0 ");
  5. println!("發布於 {year} 年");
  6. println!("{} + {} = {}", 1, 2, 1 + 2);
  7. eprintln!("這行寫到標準錯誤");
  8. }

輸出:
  1. Rust 1.0 發布於 2015 年
  2. 1 + 2 = 3
  3. 這行寫到標準錯誤

用 ./main 2>/dev/null 丟掉標準錯誤時,最後一行就不會出現。格式語法的完整說明見 std::fmt,變數的寫法見 變數、可變性與遮蔽。

用 rustc 編譯


編譯與執行是兩個步驟


Rust 是編譯式語言(compiled language):rustc 先把原始碼編譯成獨立的可執行檔,之後執行這個檔案就好,不需要 Rust 環境,也不需要直譯器。這和 Python、JavaScript 邊讀邊執行不同。
--edition 2024 指定語言版本(edition)。直接用 rustc 時,不指定會用最舊的 2015 edition,所以單檔練習建議都加上;用 cargo 時則由 Cargo.toml 決定。edition 的意義見 Edition 與語言演進。
範例:
  1. rustc --edition 2024 main.rs
  2. ls
  3. ./main

輸出:
  1. main
  2. main.rs
  3. Hello, Rust!

看懂第一個編譯錯誤


忘了寫 ! 是新手最常見的錯誤之一。Rust 的錯誤訊息會標出位置,並在 help 給修正建議。這段無法編譯:
  1. fn main() {
  2. println("Hello, Rust!");
  3. }

輸出:
  1. error[E0423]: cannot find function `println` in this scope
  2. --> main.rs:2:5
  3. |
  4. 2 | println("Hello, Rust!");
  5. | ^^^^^^^ not found in this scope
  6. |
  7. = note: a macro named `println` exists in another namespace
  8. help: use `!` to invoke the macro
  9. |
  10. 2 | println!("Hello, Rust!");
  11. | +

E0423 是錯誤代碼,rustc --explain E0423 可以看到這類錯誤的詳細說明與範例。--> main.rs:2:5 表示第 2 行第 5 個字元。

用 cargo 建立專案


rustc 適合單一檔案;真正的專案會有多個檔案、相依套件、測試,這時用 Rust 的建置工具兼套件管理員 cargo。實務上幾乎不會直接呼叫 rustc。

cargo new


cargo new 名稱 建立新的執行檔專案:Cargo.toml 是專案設定(名稱、版本、edition、相依套件),src/main.rs 是程式入口。如果目前目錄不在 git 儲存庫裡,cargo 也會順便執行 git init 並產生 .gitignore。
範例:
  1. cargo new hello_cargo
  2. cat hello_cargo/Cargo.toml
  3. cat hello_cargo/src/main.rs

輸出:
  1. Creating binary (application) `hello_cargo` package
  2. note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
  3. [package]
  4. name = "hello_cargo"
  5. version = "0.1.0"
  6. edition = "2024"
  7. [dependencies]
  8. fn main() {
  9. println!("Hello, world!");
  10. }

Cargo.toml 各欄位的意思見 Cargo.toml 與相依套件。

cargo run 與 cargo build


cargo build 編譯專案,產物放在 target/debug/;cargo run 會先編譯(有需要的話)再執行。原始碼沒變時第二次不會重新編譯,所以很快。
範例:
  1. cd hello_cargo
  2. cargo run
  3. cargo build
  4. ls target/debug

輸出:
  1. Compiling hello_cargo v0.1.0 (/tmp/hello_cargo)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.15s
  3. Running `target/debug/hello_cargo`
  4. Hello, world!
  5. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
  6. build
  7. examples
  8. hello_cargo
  9. hello_cargo.d
  10. incremental

Compiling 後面的路徑與耗時會因機器而異。cargo 的狀態訊息(Compiling、Finished)寫在標準錯誤,程式本身的輸出才在標準輸出;加 -q 可以只看程式輸出。

release 模式


預設的 dev profile 不做最佳化、保留除錯資訊,編譯快、方便除錯。要發布或測量效能時加 --release:開啟最佳化,編譯較慢但執行快很多,產物在 target/release/。
範例:
  1. cargo build --release
  2. ./target/release/hello_cargo
  3. ls target

輸出:
  1. Compiling hello_cargo v0.1.0 (/tmp/hello_cargo)
  2. Finished `release` profile [optimized] target(s) in 0.11s
  3. Hello, world!
  4. CACHEDIR.TAG
  5. debug
  6. release

cargo buildcargo build --release
profiledevrelease
最佳化無有
產物位置target/debug/target/release/
整數溢位panic環繞(wrap around)
適合開發、除錯發布、效能測量

注意:兩種模式對整數溢位的處理不同,詳見 整數。用 debug 版量效能會嚴重低估 Rust 的速度。

rustfmt:自動排版


Rust 有官方的排版工具 rustfmt,整個社群都用同一套風格,不必爭論大括號放哪。cargo fmt 會排版整個專案;cargo fmt --check 只檢查不修改,有差異時以結束碼 1 結束,適合放在 CI。若尚未安裝,執行 rustup component add rustfmt。

cargo fmt


把 src/main.rs 改成一段擠在一起的程式碼:
  1. fn main(){
  2. let name="Rust";let n=3;
  3. if n>2{println!("{name} x {n}");}
  4. }

範例:
  1. cargo fmt
  2. cat src/main.rs
  3. cargo run -q

輸出:
  1. fn main() {
  2. let name = "Rust";
  3. let n = 3;
  4. if n > 2 {
  5. println!("{name} x {n}");
  6. }
  7. }
  8. Rust x 3

多數編輯器可以設定存檔時自動執行 rustfmt。其他 cargo 子指令見 cargo 指令總覽。

重點整理


  • 程式從 fn main() 開始;println! 的 ! 代表巨集
  • rustc --edition 2024 main.rs 編譯單一檔案,產生可直接執行的檔案
  • 實際專案用 cargo new 建立、cargo run 編譯並執行
  • 預設是未最佳化的 dev profile;發布或量效能時用 --release
  • 錯誤訊息的 help 通常就是修法,rustc --explain 代碼 看詳細說明
  • cargo fmt 套用官方排版風格,--check 用於 CI 檢查

資料來源