注释
词法分析器
LINE_COMMENT
//(~[/!\n] |//) ~\n*
|//BLOCK_COMMENT
/*(~[*!] |**| BlockCommentOrDoc) (BlockCommentOrDoc | ~*/)**/
|/**/
|/***/INNER_LINE_DOC
//!~[\nIsolatedCR]*INNER_BLOCK_DOC
/*!( BlockCommentOrDoc | ~[*/IsolatedCR] )**/OUTER_LINE_DOC
///(~/~[\nIsolatedCR]*)?OUTER_BLOCK_DOC
/**(~*| BlockCommentOrDoc ) (BlockCommentOrDoc | ~[*/IsolatedCR])**/BlockCommentOrDoc :
BLOCK_COMMENT
| OUTER_BLOCK_DOC
| INNER_BLOCK_DOCIsolatedCR :
\r
非文档注释
注释遵循通用的 C++ 风格,包括行注释 (//) 和块注释 (/* ... */)。支持嵌套块注释。
非文档注释被解释为一种空白(whitespace)形式。
文档注释
以恰好三个斜杠 (///) 开头的行文档注释,以及块文档注释 (/** ... */),这两种外部文档注释,都被解释为 doc 属性 的特殊语法。
也就是说,它们等价于在注释体周围写 #[doc="..."]。例如,/// Foo 会变成 #[doc="Foo"],而 /** Bar */ 会变成 #[doc="Bar"]。因此,它们必须出现在接受外部属性的项之前。
以 //! 开头的行注释和 /*! ... */ 块注释是应用于注释的父项而非其后项的文档注释。
也就是说,它们等价于在注释体周围写 #![doc="..."]。//! 注释通常用于文档化占据整个源文件的模块。
字符 U+000D (CR) 不允许出现在文档注释中。
注意
按照惯例,文档注释中包含 Markdown 内容,这是
rustdoc所期望的。然而,注释语法本身并不识别内部的 Markdown 标记。例如,/** `glob = "*/*.rs";` */会在第一个*/处终止注释,剩余的代码将导致语法错误。这使得块文档注释的内容相比行文档注释受到一些限制。
注意
序列
U+000D(CR) 紧跟U+000A(LF) 会被预先转换成一个单独的U+000A(LF)。
示例
#![allow(unused)] fn main() { //! A doc comment that applies to the implicit anonymous module of this crate pub mod outer_module { //! - Inner line doc //!! - Still an inner line doc (but with a bang at the beginning) /*! - Inner block doc */ /*!! - Still an inner block doc (but with a bang at the beginning) */ // - Only a comment /// - Outer line doc (exactly 3 slashes) //// - Only a comment /* - Only a comment */ /** - Outer block doc (exactly) 2 asterisks */ /*** - Only a comment */ pub mod inner_module {} pub mod nested_comments { /* In Rust /* we can /* nest comments */ */ */ // All three types of block comments can contain or be nested inside // any other type: /* /* */ /** */ /*! */ */ /*! /* */ /** */ /*! */ */ /** /* */ /** */ /*! */ */ pub mod dummy_item {} } pub mod degenerate_cases { // empty inner line doc //! // empty inner block doc /*!*/ // empty line comment // // empty outer line doc /// // empty block comment /**/ pub mod dummy_item {} // empty 2-asterisk block isn't a doc block, it is a block comment /***/ } /* The next one isn't allowed because outer doc comments require an item that will receive the doc */ /// Where is my item? mod boo {} } }