问题
This section of the Rust book seems to imply that it is possible to keep Rust documentation in separate .md files, but it does not say how these .md files can then be included back. How does this work?
回答1:
It doesn't. That section on describing the functionality of rustdoc
is saying that it can process individual .md
files. The third paragraph touches on this:
Documentation can be generated in two ways: from source code, and from standalone Markdown files.
Insofar as I am aware, there is no extant way to put code documentation in external files. It would be theoretically possible to do so using a procedural derive macro, but I'm not aware of any crate that actually does this.
回答2:
It is possible to keep Rust module documentation in external .md files! But for now that feature is unstable and you will need to build your crate's documentation using a nightly compiler.
The external doc feature is described in this page of The Unstable Book and stabilization is being tracked in rust-lang/rust#44732.
For external module documentation you would use:
#![feature(external_doc)]
#![doc(include = "my-module-doc.md")]
/* content of the module */
回答3:
In stable Rust, you can mimic the unstable external-doc feature through clever macros.
An easy way to do this is to use the doc-comment crate:
#[macro_use]
extern crate doc_comment;
// If you want to test examples in your README file.
doctest!("../README.md");
// If you want to document an item:
doc_comment!(include_str!("another_file.md"), pub struct Foo {});
You can see a complicated version of this in my crate SNAFU, where I use it for the user's guide.
The "by-hand" version involves passing the thing to be documented along with the included markdown:
macro_rules! inner {
($text:expr, $($rest: tt)*) => {
#[doc = $text]
$($rest)*
};
}
inner! {
include_str!("/etc/hosts"),
mod dummy {}
}
See also:
- Is it possible to emit Rust attributes from within macros?
- How to embed a Rust macro variable into documentation?
- Generating documentation in macros
来源:https://stackoverflow.com/questions/48980028/how-is-it-possible-to-keep-rust-module-documentation-in-separate-markdown-files