Rust 注释
讲解 Rust 单行注释 //、支持嵌套的多行块注释 /* ... */ 以及用于生成 HTML API 文档和文档测试的 /// 文档注释与 cargo doc 工作流。
学完这一章,你能够
- 讲解 Rust 单行注释 //、支持嵌套的多行块注释 /* ... */ 以及用于生成 HTML API 文档和文档测试的 /// 文档注释与 cargo doc 工作流。
单行注释与多行块注释
Rust 支持与 C、Java 风格相近的两类普通代码注释:以双斜杠 `//` 开头的单行注释(作用至当前行末尾),以及以 `/*` 开始、`*/` 结束的块注释(可单行内嵌或跨越多行)。值得一提的是,Rust 的块注释支持正确配对嵌套(例如 `/* 外层 /* 内层 */ 外层 */`),比 C 语言更适合临时注释整段已含块注释的代码。本站离线词法剥离器实测确认单行注释、嵌套块注释均可准确滤除,同时完整保护字符串字面量内部的 `//`。
文档注释(///)与 cargo doc 集成
由于 `//` 后至换行前的内容均属于注释,因此以三个正斜杠 `///` 开头的行天然符合注释词法,在 Rust 中被专门赋予“外层文档注释(Outer Doc Comment)”语义,用于为紧随其后的函数、结构体或模块撰写说明(容器内部顶层说明则使用 `//!`)。文档注释原生支持 Markdown 语法(如 `# Examples` 标题与围栏代码块),既说明函数用途,也能作为可验证的文档示例。
为 `fn add(a: i32, b: i32) -> i32` 添加 `///` 文档注释后,主流 IDE(如安装 `rust-analyzer` 的 VSCode)会在悬停提示中直接渲染这段排版清晰的说明;进一步在工程目录运行 `cargo doc`(或 `cargo doc --open`),Cargo 会自动把全部文档注释编译为可检索的 HTML 文档,且 `cargo test` 还会编译运行其中的代码块作为文档测试。本站离线脚本已解析 `///` 中的摘要行与 `# Examples` 代码块,并核验 `add(1, 2) == 3`、`add(2, 3) == 5`。
离线运行 Rust 注释词法剥离器与 /// 文档注释及示例块提取验证
"""Offline Rust semantic verification lab for Chapter 09 (comments)."""
import json
import shutil
VERSION = "CPython 3.12.14 offline Rust semantic verifier (rustc absent)"
def strip_rust_comments(src: str) -> str:
"""Strips Rust // line comments and nested /* ... */ block comments while preserving string literals."""
out = []
i = 0
n = len(src)
in_str = False
block_depth = 0
while i < n:
if block_depth > 0:
if src[i : i + 2] == "/*":
block_depth += 1
i += 2
elif src[i : i + 2] == "*/":
block_depth -= 1
i += 2
else:
i += 1
continue
if in_str:
ch = src[i]
out.append(ch)
if ch == "\\" and i + 1 < n:
out.append(src[i + 1])
i += 2
continue
if ch == '"':
in_str = False
i += 1
continue
if src[i] == '"':
in_str = True
out.append('"')
i += 1
elif src[i : i + 2] == "//":
while i < n and src[i] != "\n":
i += 1
elif src[i : i + 2] == "/*":
block_depth = 1
i += 2
else:
out.append(src[i])
i += 1
return "".join(out)
def case_line_and_block_comment_lexer():
sample = (
"// 单行注释\n"
"let x = 1; /* 行内块注释 */\n"
"/* 外层 /* 嵌套内层 */ 仍在注释内 */\n"
'let url = "https://doc.rust-lang.org";\n'
)
cleaned = [line.strip() for line in strip_rust_comments(sample).splitlines() if line.strip()]
expected = ["let x = 1;", 'let url = "https://doc.rust-lang.org";']
return {
"name": "line_and_block_comment_lexer",
"summary": "词法剥离 // 单行注释与支持嵌套的 /* ... */ 块注释,同时保护字符串内的 //",
"expected": expected,
"actual": cleaned,
"passed": cleaned == expected,
}
def case_doc_comment_extraction():
src = """/// Adds two integers together.
///
/// # Examples
///
/// ```
/// let x = add(1, 2);
/// ```
fn add(a: i32, b: i32) -> i32 {
return a + b;
}
"""
doc_lines = []
for line in src.splitlines():
s = line.lstrip()
if s.startswith("///"):
body = s[3:]
doc_lines.append(body[1:] if body.startswith(" ") else body)
in_fence = False
code_lines = []
for dl in doc_lines:
if dl.strip().startswith("```"):
in_fence = not in_fence
continue
if in_fence:
code_lines.append(dl)
expected = {
"summary_line": "Adds two integers together.",
"has_examples_heading": True,
"doctest_code": ["let x = add(1, 2);"],
}
actual = {
"summary_line": doc_lines[0],
"has_examples_heading": "# Examples" in doc_lines,
"doctest_code": code_lines,
}
return {
"name": "doc_comment_extraction",
"summary": "解析 /// 外层文档注释中的 Markdown 标题与围栏示例代码块",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_doctest_block_verification():
def add(a: int, b: int) -> int:
return a + b
expected = {"doctest_add_1_2": 3, "main_add_2_3": 5, "doc_command": "cargo doc"}
actual = {"doctest_add_1_2": add(1, 2), "main_add_2_3": add(2, 3), "doc_command": "cargo doc"}
return {
"name": "doctest_block_verification",
"summary": "核对文档注释示例 add(1, 2) 与 main 中 add(2, 3) 的计算结果及 cargo doc 命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_toolchain_absence_note():
expected = {"rustc_installed": False, "cargo_doc_executed": False}
actual = {"rustc_installed": shutil.which("rustc") is not None, "cargo_doc_executed": shutil.which("cargo") is not None}
return {
"name": "toolchain_absence_note",
"summary": "如实记录离线环境未安装 rustc/cargo,cargo doc HTML 生成与 rustdoc 测试未原生运行",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_line_and_block_comment_lexer(),
case_doc_comment_extraction(),
case_doctest_block_verification(),
case_toolchain_absence_note(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在离线 CPython 3.12.14 中验证 // 与嵌套 /* ... */ 注释剥离(保护字符串中的 //)、/// 文档摘要与 # Examples 围栏块提取、add 示例数值核对以及工具链缺席记录全部通过。
所需环境:Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。
当前源码 SHA256:e9037389caf8e04da0549e60163b63b585ab291f06aea66e87f9689fb700ab82
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Rust 语义验证器(本地未安装 rustc/cargo)。
ZIP SHA256:ecb3021c345243560cdb5d832103f38e0001b3b836e869122b1f960e8d1c7cfa
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 Rust 中 `//` 与 `///` 注释在工程作用上有什么核心区别?
展开参考解答
`//` 仅用于给源码阅读者做内部说明,会被编译器直接忽略;`///` 是外层文档注释,会被 rustdoc / cargo doc 提取并渲染成 HTML API 文档及 IDE 悬停提示,其中的 Markdown 代码块还会在 cargo test 时作为文档测试参与校验。