注釋

2018-08-12 22:03 更新

注釋

既然我們對函數(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)行測試代碼來嘗試一下!

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號