註解與文件註解

最後更新


Rust 有給讀程式的人看的一般註解(//、/* */),也有會被轉成 HTML 文件、還能當測試執行的文件註解(///、//!)。

一般註解


註解(comment)是編譯器會忽略的文字,用來說明程式「為什麼這樣寫」。好的註解解釋意圖與限制,而不是把程式碼逐行翻成中文。

// 行註解


// 之後到行尾都是註解,可以獨立一行,也可以接在程式碼後面。暫時停用某行程式時,也常把它註解掉。Rust 社群慣例以 // 為主。
範例:
  1. fn main() {
  2. // 運費門檻:滿 500 免運
  3. let threshold = 500;
  4. let total = 620; // 購物車總額
  5. // 下面這行暫時停用,改用固定運費
  6. // let fee = calculate_fee(total);
  7. let fee = if total >= threshold { 0 } else { 60 };
  8. println!("運費 {fee}");
  9. }

輸出:
  1. 運費 0

被註解掉的 calculate_fee 根本不存在,但因為編譯器忽略註解,程式仍能編譯。

/* */ 區塊註解可以巢狀


/* 與 */ 之間的內容都是註解,可以跨多行,也能夾在一行中間。和 C、Java 不同,Rust 的區塊註解可以巢狀:要停用一段本來就含有 /* */ 的程式碼,直接外面再包一層即可,不會提早結束。
範例:
  1. fn main() {
  2. let a = 10;
  3. /* 區塊註解可以跨越
  4. 多行文字 */
  5. let b = /* 也能放在一行中間 */ 20;
  6. /*
  7. let c = 30;
  8. /* 巢狀的區塊註解也沒問題 */
  9. println!("{c}");
  10. */
  11. println!("{}", a + b);
  12. }

輸出:
  1. 30

文件註解


文件註解(doc comment)是寫給「使用你程式碼的人」看的。內容用 Markdown 撰寫,rustdoc 工具會把它轉成 HTML 文件;標準庫在 doc.rust-lang.org 上的文件,就是這樣從原始碼產生的。
語法描述的對象放在哪裡
///緊接在下方的項目(函式、結構體、列舉、trait、模組...)項目上方
//!包住它的項目,通常是整個 crate 或模組檔案開頭

/** */ 與 /*! */ 是對應的區塊寫法,實務上很少用。

/// 描述下一個項目


以下是一個用 cargo new --lib textkit 建立的函式庫專案。src/lib.rs 的完整內容:
  1. //! textkit:處理中文文字的小工具。
  2. //!
  3. //! 主要功能是 [`word_count`] 與 [`truncate`]。
  4. /// 計算字串中的字元數(不含空白)。
  5. ///
  6. /// 中文字、英文字母、標點都各算一個字元。
  7. ///
  8. /// # Examples
  9. ///
  10. /// ```
  11. /// let n = textkit::word_count("你好 Rust");
  12. /// assert_eq!(n, 6);
  13. /// ```
  14. pub fn word_count(text: &str) -> usize {
  15. text.chars().filter(|c| !c.is_whitespace()).count()
  16. }
  17. /// 只保留前 `max` 個字元,超過時在結尾加上 `...`。
  18. ///
  19. /// 和 [`word_count`] 不同,這裡的空白也算一個字元。
  20. ///
  21. /// # Examples
  22. ///
  23. /// ```
  24. /// use textkit::truncate;
  25. ///
  26. /// assert_eq!(truncate("今天天氣很好", 4), "今天天氣...");
  27. /// assert_eq!(truncate("短句", 4), "短句");
  28. /// ```
  29. pub fn truncate(text: &str, max: usize) -> String {
  30. if text.chars().count() <= max {
  31. return text.to_string();
  32. }
  33. let head: String = text.chars().take(max).collect();
  34. format!("{head}...")
  35. }

寫法慣例:
  • 第一段是一句話摘要,會出現在模組的項目清單裡
  • 用 # Examples、# Panics、# Errors、# Safety 等標題分段:會 panic 的函式寫明何時 panic,回傳 Result 的寫明何時回傳 Err
  • 用反引號標示程式碼,例如 `max`

範例:
  1. cargo test

輸出:
  1. Compiling textkit v0.1.0 (/tmp/textkit)
  2. Finished `test` profile [unoptimized + debuginfo] target(s) in 0.15s
  3. Running unittests src/lib.rs (target/debug/build/textkit/1c07bb9ad8f35e9f/out/textkit-1c07bb9ad8f35e9f)
  4. running 0 tests
  5. test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  6. Doc-tests textkit
  7. running 2 tests
  8. test src/lib.rs - truncate (line 25) ... ok
  9. test src/lib.rs - word_count (line 11) ... ok
  10. test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
  11. 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`]:
範例:
  1. cargo doc

輸出:
  1. Documenting textkit v0.1.0 (/tmp/textkit)
  2. warning: unresolved link to `count_words`
  3. --> src/lib.rs:21:9
  4. |
  5. 21 | /// 和 [`count_words`] 不同,這裡的空白也算一個字元。
  6. | ^^^^^^^^^^^ no item named `count_words` in scope
  7. |
  8. = help: to escape `[` and `]` characters, add '\' before them like `\[` or `\]`
  9. = note: `#[warn(rustdoc::broken_intra_doc_links)]` on by default
  10. warning: `textkit` (lib doc) generated 1 warning

注意:一般 // 註解裡寫錯名稱不會有任何提示,文件註解則會被工具檢查。也因此公開 API 的說明應該寫在 /// 裡。

rustdoc 與 cargo doc


產生並瀏覽文件


cargo doc 呼叫 rustdoc 產生整個專案(含相依套件)的 HTML 文件,放在 target/doc/;加 --open 直接用瀏覽器開啟。每個公開函式各有一個頁面,左側欄與搜尋框都自動建好。預設只產生 pub 項目的文件,因為那才是使用者看得到的 API;可見性的規則見 模組系統。
範例:
  1. cargo doc
  2. ls target/doc/textkit

輸出:
  1. Documenting textkit v0.1.0 (/tmp/textkit)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
  3. Generated /tmp/textkit/target/doc/textkit/index.html
  4. all.html
  5. fn.truncate.html
  6. fn.word_count.html
  7. index.html
  8. 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 離線查標準庫

資料來源