Rust 程式設計視訊教程(進階)——007_2 文件註釋

linghuyichong發表於2020-01-21

頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/

編寫有用的文件註釋
(1)在基礎部分,我們講解了程式碼註釋,通過//來註釋;

(2)Rust也有特定的用於文件的註釋型別,通常稱為文件註釋,它們會生成HTML文件。它們通過///來註釋。
例子: 通過cargo new mylib --lib 建立src/lib.rs

src/lib.rs
/// Adds one to the number given
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, mylib::add_one(5));
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

執行cargo doc會生成這個文件註釋的HTML文件。
執行cargo doc --open會構建當前crate文件的HTML並在瀏覽器中開啟。

(3)哪些通常需要註釋

  • Panics:這個函式可能會panic!的場景;
  • Errors:如果該函式返回Result型別,此部分會描述會出現哪些錯誤;
  • Safety:如果這個函式使用unsafe程式碼,則應該說明。

(4)文件註釋作為測試
cargo test也會像文件中的示例程式碼那樣進行測試。
執行方式為:cargo test

src/lib.rs
/// Adds one to the number given
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, mylib::add_one(5)); //執行cargo test,會進行此測試
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

(5)為crate或者模組整體提供文件的註釋://!
例子:src/lib.rs

//! My Crate
//!
//! 'my_crate' is a collection of utilites to make performing certain calculations more convenient
//!
/// Adds one to the number given
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, mylib::add_one(5));
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

檢視效果:

cargo doc --open
本作品採用《CC 協議》,轉載必須註明作者和本文連結

令狐一衝

相關文章