視頻地址
頭條地址:https://www.ixigua.com/i6775861706447913485
B站地址:https://www.bilibili.com/video/av81202308/
講解內(nèi)容
編寫有用的文檔注釋
(1)在基礎(chǔ)部分,我們講解了代碼注釋腕侄,通過//來注釋敛劝;
(2)Rust也有特定的用于文檔的注釋類型,通常稱為文檔注釋辽旋,它們會(huì)生成HTML文檔。它們通過///來注釋。
例子: 通過cargo new mylib --lib 創(chuàng)建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
}
運(yùn)行cargo doc會(huì)生成這個(gè)文檔注釋的HTML文檔忧勿。
運(yùn)行cargo doc --open會(huì)構(gòu)建當(dāng)前crate文檔的HTML并在瀏覽器中打開。
(3)哪些通常需要注釋
- Panics:這個(gè)函數(shù)可能會(huì)panic瞻讽!的場景鸳吸;
- Errors:如果該函數(shù)返回Result類型,此部分會(huì)描述會(huì)出現(xiàn)哪些錯(cuò)誤速勇;
- Safety:如果這個(gè)函數(shù)使用unsafe代碼晌砾,則應(yīng)該說明。
(4)文檔注釋作為測(cè)試
cargo test也會(huì)像文檔中的示例代碼那樣進(jìn)行測(cè)試烦磁。
運(yùn)行方式為:cargo test
src/lib.rs
/// Adds one to the number given
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, mylib::add_one(5)); //運(yùn)行cargo test养匈,會(huì)進(jìn)行此測(cè)試
/// ```
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