You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust多二进制项目中如何为各二进制添加独立文档头部注释

问题

我有一个包含两个共享同一库的二进制源文件的Rust项目,项目配置如下:

Cargo.toml:

<...>

[[bin]]
name = "quoter_xml"
path = "src/quoter_xml.rs"

[[bin]]
name = "quoter"
path = "src/quoter.rs"

<...>

src/quoter_xml.rs、src/quoter.rs均包含main函数,src/lib.rs包含公共模块。编译后得到quoter_xml和quoter两个二进制文件,使用cargo doc生成文档后,会得到各自独立的文档文件doc/quoter_xml/index.html和doc/quoter/index.html。

我希望为这些文档页面的顶部添加描述文本,尝试在二进制源文件中添加//!类型注释:

src/quoter_xml.rs:

use <...>

//! quoter_xml - this binary is for <..>

fn main() {
    <...>
}

但编译时出现错误:

error[E0753]: expected outer doc comment
  --> src/quoter_xml.rs:10:1
   |
10 | //! quoter_xml - this binary is for <..>
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: inner doc comments like this (starting with `//!` or `/*!`) can only appear before items
help: you might have meant to write a regular comment
   |
10 - //! quoter_xml - this binary is for <..>
10 + // quoter_xml - this binary is for <..>
   | 

编译器建议使用普通注释,但我需要能显示在文档页面顶部的注释。此前查询到的方案是将此类注释放在src/lib.rs中,但这不符合我的需求,我希望为每个二进制文件的文档添加独立的顶部描述文本,请问有什么解决办法?

解决方案

有两种可行的方式为每个二进制目标添加独立的文档头部:

方法一:使用外部文档注释放在文件最开头

直接在二进制源文件的最顶部使用外部文档注释(/*! ... */),这种注释会被cargo doc识别为该二进制目标的文档描述:

/*!
quoter_xml - this binary is for <..>
可以在这里添加多行描述文本,支持Markdown格式
*/

use <...>

fn main() {
    <...>
}

注意必须把这个注释放在文件的最开始位置,不能在use语句之后。

方法二:将二进制代码包裹在模块中,给模块添加内部文档注释

把整个二进制的代码(包括main函数)包裹在一个模块里,然后给这个模块添加//!注释,这样注释会显示在文档页面顶部:

//! quoter_xml - this binary is for <..>
//! 这里可以添加更多关于该工具的说明

mod quoter_xml_bin {
    use <...>

    pub fn main() {
        <...>
    }
}

fn main() {
    quoter_xml_bin::main();
}

这种方式下,模块的文档注释会被当作该二进制目标的文档内容,同时需要把原来的main函数包装后再对外暴露一个新的main入口。

两种方法都能实现为每个二进制文件生成独立的文档头部描述,可根据习惯选择。

内容的提问来源于stack exchange,提问作者Ivan Olshansky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 02:06:35