第一個 Rust 程式
最後更新
從一行
println! 開始,學會用 rustc 直接編譯單一檔案、用 cargo 建立與執行專案、切換 release 模式,以及用 rustfmt 統一排版。最小的 Rust 程式
先確認已經裝好工具鏈,見 安裝 Rust 與開發環境。
fn main 與 println!
Rust 程式從
main 函式開始執行。fn 宣告函式,main 沒有參數也沒有回傳值。println! 把文字印到終端機並換行。每個陳述式以分號結尾,縮排慣例是 4 個空白。建立
main.rs:範例:
- fn main() {
- println!("Hello, Rust!");
- }
在同一個目錄執行:
- rustc --edition 2024 main.rs
- ./main
輸出:
- Hello, Rust!
Windows 上產生的是
main.exe,執行時輸入 .\main.exe。println! 是巨集,不是函式
名稱後面的
! 表示這是巨集(macro)。巨集在編譯期展開成程式碼,所以能做到一般函式做不到的事:參數數量不固定、在編譯期檢查格式字串。{} 是佔位符,依序填入後面的參數;{lang} 直接印出同名變數(Rust 1.58 起)。| 巨集 | 用途 |
|---|---|
println! | 印到標準輸出並換行 |
print! | 印到標準輸出,不換行 |
eprintln! | 印到標準錯誤(stderr),用於錯誤訊息 |
範例:
- fn main() {
- let lang = "Rust";
- let year = 2015;
- print!("{lang} 1.0 ");
- println!("發布於 {year} 年");
- println!("{} + {} = {}", 1, 2, 1 + 2);
- eprintln!("這行寫到標準錯誤");
- }
輸出:
- Rust 1.0 發布於 2015 年
- 1 + 2 = 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 與語言演進。範例:
- rustc --edition 2024 main.rs
- ls
- ./main
輸出:
- main
- main.rs
- Hello, Rust!
看懂第一個編譯錯誤
忘了寫
! 是新手最常見的錯誤之一。Rust 的錯誤訊息會標出位置,並在 help 給修正建議。這段無法編譯:- fn main() {
- println("Hello, Rust!");
- }
輸出:
- error[E0423]: cannot find function `println` in this scope
- --> main.rs:2:5
- |
- 2 | println("Hello, Rust!");
- | ^^^^^^^ not found in this scope
- |
- = note: a macro named `println` exists in another namespace
- help: use `!` to invoke the macro
- |
- 2 | println!("Hello, Rust!");
- | +
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。範例:
- cargo new hello_cargo
- cat hello_cargo/Cargo.toml
- cat hello_cargo/src/main.rs
輸出:
- Creating binary (application) `hello_cargo` package
- note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
- [package]
- name = "hello_cargo"
- version = "0.1.0"
- edition = "2024"
- [dependencies]
- fn main() {
- println!("Hello, world!");
- }
Cargo.toml 各欄位的意思見 Cargo.toml 與相依套件。cargo run 與 cargo build
cargo build 編譯專案,產物放在 target/debug/;cargo run 會先編譯(有需要的話)再執行。原始碼沒變時第二次不會重新編譯,所以很快。範例:
- cd hello_cargo
- cargo run
- cargo build
- ls target/debug
輸出:
- Compiling hello_cargo v0.1.0 (/tmp/hello_cargo)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.15s
- Running `target/debug/hello_cargo`
- Hello, world!
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
- build
- examples
- hello_cargo
- hello_cargo.d
- incremental
Compiling 後面的路徑與耗時會因機器而異。cargo 的狀態訊息(Compiling、Finished)寫在標準錯誤,程式本身的輸出才在標準輸出;加 -q 可以只看程式輸出。release 模式
預設的
dev profile 不做最佳化、保留除錯資訊,編譯快、方便除錯。要發布或測量效能時加 --release:開啟最佳化,編譯較慢但執行快很多,產物在 target/release/。範例:
- cargo build --release
- ./target/release/hello_cargo
- ls target
輸出:
- Compiling hello_cargo v0.1.0 (/tmp/hello_cargo)
- Finished `release` profile [optimized] target(s) in 0.11s
- Hello, world!
- CACHEDIR.TAG
- debug
- release
cargo build | cargo build --release | |
|---|---|---|
| profile | dev | release |
| 最佳化 | 無 | 有 |
| 產物位置 | 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 改成一段擠在一起的程式碼:- fn main(){
- let name="Rust";let n=3;
- if n>2{println!("{name} x {n}");}
- }
範例:
- cargo fmt
- cat src/main.rs
- cargo run -q
輸出:
- fn main() {
- let name = "Rust";
- let n = 3;
- if n > 2 {
- println!("{name} x {n}");
- }
- }
- Rust x 3
多數編輯器可以設定存檔時自動執行 rustfmt。其他 cargo 子指令見 cargo 指令總覽。
重點整理
- 程式從
fn main()開始;println!的!代表巨集 rustc --edition 2024 main.rs編譯單一檔案,產生可直接執行的檔案- 實際專案用
cargo new建立、cargo run編譯並執行 - 預設是未最佳化的
devprofile;發布或量效能時用--release - 錯誤訊息的
help通常就是修法,rustc --explain 代碼看詳細說明 cargo fmt套用官方排版風格,--check用於 CI 檢查