註解與文件註解
最後更新
Rust 有給讀程式的人看的一般註解(
//、/* */),也有會被轉成 HTML 文件、還能當測試執行的文件註解(///、//!)。一般註解
註解(comment)是編譯器會忽略的文字,用來說明程式「為什麼這樣寫」。好的註解解釋意圖與限制,而不是把程式碼逐行翻成中文。
// 行註解
// 之後到行尾都是註解,可以獨立一行,也可以接在程式碼後面。暫時停用某行程式時,也常把它註解掉。Rust 社群慣例以 // 為主。範例:
- fn main() {
- // 運費門檻:滿 500 免運
- let threshold = 500;
- let total = 620; // 購物車總額
- // 下面這行暫時停用,改用固定運費
- // let fee = calculate_fee(total);
- let fee = if total >= threshold { 0 } else { 60 };
- println!("運費 {fee}");
- }
輸出:
- 運費 0
被註解掉的
calculate_fee 根本不存在,但因為編譯器忽略註解,程式仍能編譯。/* */ 區塊註解可以巢狀
/* 與 */ 之間的內容都是註解,可以跨多行,也能夾在一行中間。和 C、Java 不同,Rust 的區塊註解可以巢狀:要停用一段本來就含有 /* */ 的程式碼,直接外面再包一層即可,不會提早結束。範例:
- fn main() {
- let a = 10;
- /* 區塊註解可以跨越
- 多行文字 */
- let b = /* 也能放在一行中間 */ 20;
- /*
- let c = 30;
- /* 巢狀的區塊註解也沒問題 */
- println!("{c}");
- */
- println!("{}", a + b);
- }
輸出:
- 30
文件註解
文件註解(doc comment)是寫給「使用你程式碼的人」看的。內容用 Markdown 撰寫,
rustdoc 工具會把它轉成 HTML 文件;標準庫在 doc.rust-lang.org 上的文件,就是這樣從原始碼產生的。| 語法 | 描述的對象 | 放在哪裡 |
|---|---|---|
/// | 緊接在下方的項目(函式、結構體、列舉、trait、模組...) | 項目上方 |
//! | 包住它的項目,通常是整個 crate 或模組 | 檔案開頭 |
/** */ 與 /*! */ 是對應的區塊寫法,實務上很少用。/// 描述下一個項目
以下是一個用
cargo new --lib textkit 建立的函式庫專案。src/lib.rs 的完整內容:- //! textkit:處理中文文字的小工具。
- //!
- //! 主要功能是 [`word_count`] 與 [`truncate`]。
- /// 計算字串中的字元數(不含空白)。
- ///
- /// 中文字、英文字母、標點都各算一個字元。
- ///
- /// # Examples
- ///
- /// ```
- /// let n = textkit::word_count("你好 Rust");
- /// assert_eq!(n, 6);
- /// ```
- pub fn word_count(text: &str) -> usize {
- text.chars().filter(|c| !c.is_whitespace()).count()
- }
- /// 只保留前 `max` 個字元,超過時在結尾加上 `...`。
- ///
- /// 和 [`word_count`] 不同,這裡的空白也算一個字元。
- ///
- /// # Examples
- ///
- /// ```
- /// use textkit::truncate;
- ///
- /// assert_eq!(truncate("今天天氣很好", 4), "今天天氣...");
- /// assert_eq!(truncate("短句", 4), "短句");
- /// ```
- pub fn truncate(text: &str, max: usize) -> String {
- if text.chars().count() <= max {
- return text.to_string();
- }
- let head: String = text.chars().take(max).collect();
- format!("{head}...")
- }
寫法慣例:
- 第一段是一句話摘要,會出現在模組的項目清單裡
- 用
# Examples、# Panics、# Errors、# Safety等標題分段:會 panic 的函式寫明何時 panic,回傳Result的寫明何時回傳Err - 用反引號標示程式碼,例如
`max`
範例:
- cargo test
輸出:
- Compiling textkit v0.1.0 (/tmp/textkit)
- Finished `test` profile [unoptimized + debuginfo] target(s) in 0.15s
- Running unittests src/lib.rs (target/debug/build/textkit/1c07bb9ad8f35e9f/out/textkit-1c07bb9ad8f35e9f)
- running 0 tests
- test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
- Doc-tests textkit
- running 2 tests
- test src/lib.rs - truncate (line 25) ... ok
- test src/lib.rs - word_count (line 11) ... ok
- test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
- all doctests ran in 0.35s; merged doctests compilation took 0.13s
Doc-tests 那段就是文件註解中的兩個 ``` 範例:cargo 把它們當成獨立程式編譯執行,範例和實作對不上時測試就會失敗,文件因此不會過期。範例要以 crate 名稱存取(textkit::word_count 或先 use textkit::truncate),因為它是從外部使用者的角度執行的。2024 edition(Rust 1.85 起)會把多個文件測試合併編譯,所以多了最後一行的耗時統計;路徑、雜湊與耗時因機器而異。隱藏行、no_run 等進階標記見 文件測試。//! 描述整個 crate 或模組
上例檔案開頭的三行
//! 是 crate 層級的說明,會成為文件首頁的內容。寫在 mod 檔案(例如 src/parser.rs)開頭時,描述的就是那個模組。[word_count] 這種寫法是文件內連結(intra-doc link,Rust 1.48 起),rustdoc 會依名稱找到對應項目並產生超連結。連結的名稱打錯時,
cargo doc 會發出警告。把 truncate 說明中的 [`word_count`] 誤寫成 [`count_words`]:範例:
- cargo doc
輸出:
- Documenting textkit v0.1.0 (/tmp/textkit)
- warning: unresolved link to `count_words`
- --> src/lib.rs:21:9
- |
- 21 | /// 和 [`count_words`] 不同,這裡的空白也算一個字元。
- | ^^^^^^^^^^^ no item named `count_words` in scope
- |
- = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
- = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default
- warning: `textkit` (lib doc) generated 1 warning
注意:一般
// 註解裡寫錯名稱不會有任何提示,文件註解則會被工具檢查。也因此公開 API 的說明應該寫在 /// 裡。rustdoc 與 cargo doc
產生並瀏覽文件
cargo doc 呼叫 rustdoc 產生整個專案(含相依套件)的 HTML 文件,放在 target/doc/;加 --open 直接用瀏覽器開啟。每個公開函式各有一個頁面,左側欄與搜尋框都自動建好。預設只產生 pub 項目的文件,因為那才是使用者看得到的 API;可見性的規則見 模組系統。範例:
- cargo doc
- ls target/doc/textkit
輸出:
- Documenting textkit v0.1.0 (/tmp/textkit)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
- Generated /tmp/textkit/target/doc/textkit/index.html
- all.html
- fn.truncate.html
- fn.word_count.html
- index.html
- sidebar-items.js
rustup doc --std 可以離線開啟本機工具鏈附帶的標準庫文件,例如想查 std::string 時不必連網。其他 cargo 指令見 cargo 指令總覽。重點整理
//是行註解,/* */是區塊註解,而且區塊註解可以巢狀///說明下一個項目,//!說明所在的 crate 或模組,內容是 Markdown- 第一段寫一句話摘要,再用
# Examples、# Panics、# Errors等標題分段 - 文件中的程式碼範例會被
cargo test當成測試執行,範例因此不會過期 [`名稱`]是文件內連結,名稱打錯時cargo doc會警告cargo doc --open產生並開啟文件,rustup doc --std離線查標準庫