# 注釋
> [comments.md](https://github.com/rust-lang/rust/blob/master/src/doc/book/comments.md)
commit 024aa9a345e92aa1926517c4d9b16bd83e74c10d
現在我們寫了一些函數,是時候學習一下注釋了。注釋是你幫助其他程序員理解你的代碼的備注。編譯器基本上會忽略它們。
Rust有兩種需要你了解的注釋格式:*行注釋*(*line comments*)和*文檔注釋*(*doc comments*)。
~~~
// 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
/// # }
/// ```
fn add_one(x: i32) -> i32 {
x + 1
}
~~~
有另外一種風格的文檔注釋,`//!`,用來注釋包含它的項(也就是說,crate,模塊或者函數),而不是位于它之后的項。它經常用在crate根文件(lib.rs)或者模塊根文件(mod.rs):
~~~
//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
~~~
當書寫文檔注釋時,加上參數和返回值部分并提供一些用例將是非常,非常有幫助的。你會注意到我們在這里用了一個新的宏:`assert_eq!`。它比較兩個值,并當它們不相等時`panic!`。這在文檔中是非常有幫助的。還有一個宏,`assert!`,它在傳遞給它的值是`false`的時候`panic!`。
你可以使用[rustdoc](#)工具來將文檔注釋生成為HTML文檔,也可以將代碼示例作為測試運行!
- 前言
- 貢獻者
- 1.介紹
- 2.準備
- 3.學習 Rust
- 3.1.猜猜看
- 3.2.哲學家就餐問題
- 3.3.其它語言中的 Rust
- 4.語法和語義
- 4.1.變量綁定
- 4.2.函數
- 4.3.原生類型
- 4.4.注釋
- 4.5.If語句
- 4.6.循環
- 4.7.所有權
- 4.8.引用和借用
- 4.9.生命周期
- 4.10.可變性
- 4.11.結構體
- 4.12.枚舉
- 4.13.匹配
- 4.14.模式
- 4.15.方法語法
- 4.16.Vectors
- 4.17.字符串
- 4.18.泛型
- 4.19.Traits
- 4.20.Drop
- 4.21.if let
- 4.22.trait 對象
- 4.23.閉包
- 4.24.通用函數調用語法
- 4.25.crate 和模塊
- 4.26.const和static
- 4.27.屬性
- 4.28.type別名
- 4.29.類型轉換
- 4.30.關聯類型
- 4.31.不定長類型
- 4.32.運算符和重載
- 4.33.Deref強制多態
- 4.34.宏
- 4.35.裸指針
- 4.36.不安全代碼
- 5.高效 Rust
- 5.1.棧和堆
- 5.2.測試
- 5.3.條件編譯
- 5.4.文檔
- 5.5.迭代器
- 5.6.并發
- 5.7.錯誤處理
- 5.8.選擇你的保證
- 5.9.外部函數接口
- 5.10.Borrow 和 AsRef
- 5.11.發布途徑
- 5.12.不使用標準庫
- 6.Rust 開發版
- 6.1.編譯器插件
- 6.2.內聯匯編
- 6.4.固有功能
- 6.5.語言項
- 6.6.鏈接進階
- 6.7.基準測試
- 6.8.裝箱語法和模式
- 6.9.切片模式
- 6.10.關聯常量
- 6.11.自定義內存分配器
- 7.詞匯表
- 8.語法索引
- 9.參考文獻
- 附錄:名詞中英文對照