W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
既然我們對函數(shù)有了一定了解之后,那么學(xué)習(xí)下如何寫注釋是不錯的。注釋的作用在于它能夠幫助其他的程序員更好的理解你的代碼。而編譯期通常會忽視他們。
Rust 中有兩種你應(yīng)該學(xué)習(xí)的注釋方式:行注釋和文檔注釋。
// Line comments are anything after ‘//’ and extend to the end of the line.
let x = 5; // this is also a line comment.
// If you have a long explanation for something, you can put line comments next
// to each other. Put a space between the // and your comment so that it’s
// more readable.
另一種注釋是文檔注釋。文檔注釋使用 /// 而不是 //,并且在該注釋部分中支持 markdown 注解文法:
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let five = 5;
///
/// assert_eq!(6, add_one(5));
/// ```
fn add_one(x: i32) -> i32 {
x + 1
}
在編寫文檔注釋時提供一些程序使用的例子是非常有用的。你會注意到在這里我們使用了一個新的宏: assert_eq!。它將兩個值進(jìn)行比較,如果兩個值不相等就會調(diào)用 panic!。這是非常有用的文檔說明。還有另一個宏,assert!,如果它的參數(shù)值是 false,那么同樣會觸發(fā) panic! 的執(zhí)行。
您可以使用 rustdoc 工具從這些文檔注釋生成HTML文檔,并運(yùn)行測試代碼來嘗試一下!
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: