mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:14:32 -06:00
704 lines
32 KiB
HTML
704 lines
32 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title>Documentation - The Rust Programming Language</title>
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
|
||
<base href="">
|
||
|
||
<link rel="stylesheet" href="book.css">
|
||
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
|
||
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
|
||
<!-- Font Awesome -->
|
||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
|
||
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
|
||
<!-- MathJax -->
|
||
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
|
||
|
||
<!-- Fetch JQuery from CDN but have a local fallback -->
|
||
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
|
||
<script>
|
||
if (typeof jQuery == 'undefined') {
|
||
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
|
||
}
|
||
</script>
|
||
</head>
|
||
<body class="light">
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme = localStorage.getItem('theme');
|
||
if (theme == null) { theme = 'light'; }
|
||
$('body').removeClass().addClass(theme);
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var sidebar = localStorage.getItem('sidebar');
|
||
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
|
||
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
|
||
</script>
|
||
|
||
<div id="sidebar" class="sidebar">
|
||
<ul class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong>1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong>2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong>3.</strong> Syntax and Semantics</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> if</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong>3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong>3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong>3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong>3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong>3.12.</strong> Structs</a></li><li><a href="enums.html"><strong>3.13.</strong> Enums</a></li><li><a href="match.html"><strong>3.14.</strong> Match</a></li><li><a href="patterns.html"><strong>3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong>3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong>3.17.</strong> Strings</a></li><li><a href="generics.html"><strong>3.18.</strong> Generics</a></li><li><a href="traits.html"><strong>3.19.</strong> Traits</a></li><li><a href="drop.html"><strong>3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong>3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong>3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong>3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong>3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong>3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong>3.26.</strong> <code>const</code> and <code>static</code></a></li><li><a href="attributes.html"><strong>3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong>3.28.</strong> <code>type</code> aliases</a></li><li><a href="casting-between-types.html"><strong>3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong>3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong>3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong>3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong>3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong>3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong>3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong>3.36.</strong> <code>unsafe</code></a></li></ul></li><li><a href="effective-rust.html"><strong>4.</strong> Effective Rust</a></li><li><ul class="section"><li><a href="the-stack-and-the-heap.html"><strong>4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong>4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong>4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html" class="active"><strong>4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong>4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong>4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong>4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong>4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong>4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong>4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong>4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong>4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong>4.13.</strong> Procedural Macros (and custom derive)</a></li></ul></li><li><a href="glossary.html"><strong>5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong>6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong>7.</strong> Bibliography</a></li></ul>
|
||
</div>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar" class="menu-bar">
|
||
<div class="left-buttons">
|
||
<i id="sidebar-toggle" class="fa fa-bars"></i>
|
||
<i id="theme-toggle" class="fa fa-paint-brush"></i>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Rust Programming Language</h1>
|
||
|
||
<div class="right-buttons">
|
||
<i id="print-button" class="fa fa-print" title="Print this book"></i>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="content" class="content">
|
||
<a class="header" href="documentation.html#documentation" id="documentation"><h1>Documentation</h1></a>
|
||
<p>Documentation is an important part of any software project, and it's
|
||
first-class in Rust. Let's talk about the tooling Rust gives you to
|
||
document your project.</p>
|
||
<a class="header" href="documentation.html#about-rustdoc" id="about-rustdoc"><h2>About <code>rustdoc</code></h2></a>
|
||
<p>The Rust distribution includes a tool, <code>rustdoc</code>, that generates documentation.
|
||
<code>rustdoc</code> is also used by Cargo through <code>cargo doc</code>.</p>
|
||
<p>Documentation can be generated in two ways: from source code, and from
|
||
standalone Markdown files.</p>
|
||
<a class="header" href="documentation.html#documenting-source-code" id="documenting-source-code"><h2>Documenting source code</h2></a>
|
||
<p>The primary way of documenting a Rust project is through annotating the source
|
||
code. You can use documentation comments for this purpose:</p>
|
||
<pre><code class="language-rust ignore">/// Constructs a new `Rc<T>`.
|
||
///
|
||
/// # Examples
|
||
///
|
||
/// ```
|
||
/// use std::rc::Rc;
|
||
///
|
||
/// let five = Rc::new(5);
|
||
/// ```
|
||
pub fn new(value: T) -> Rc<T> {
|
||
// Implementation goes here.
|
||
}
|
||
</code></pre>
|
||
<p>This code generates documentation that looks <a href="../../std/rc/struct.Rc.html#method.new">like this</a>. I've left the
|
||
implementation out, with a regular comment in its place.</p>
|
||
<p>The first thing to notice about this annotation is that it uses
|
||
<code>///</code> instead of <code>//</code>. The triple slash
|
||
indicates a documentation comment.</p>
|
||
<p>Documentation comments are written in Markdown.</p>
|
||
<p>Rust keeps track of these comments, and uses them when generating
|
||
documentation. This is important when documenting things like enums:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// The `Option` type. See [the module level documentation](index.html) for more.
|
||
enum Option<T> {
|
||
/// No value
|
||
None,
|
||
/// Some value `T`
|
||
Some(T),
|
||
}
|
||
|
||
#}</code></pre></pre>
|
||
<p>The above works, but this does not:</p>
|
||
<pre><code class="language-rust ignore">/// The `Option` type. See [the module level documentation](index.html) for more.
|
||
enum Option<T> {
|
||
None, /// No value
|
||
Some(T), /// Some value `T`
|
||
}
|
||
</code></pre>
|
||
<p>You'll get an error:</p>
|
||
<pre><code class="language-text">hello.rs:4:1: 4:2 error: expected ident, found `}`
|
||
hello.rs:4 }
|
||
^
|
||
</code></pre>
|
||
<p>This <a href="https://github.com/rust-lang/rust/issues/22547">unfortunate error</a> is
|
||
correct; documentation comments apply to the thing after them, and there's
|
||
nothing after that last comment.</p>
|
||
<a class="header" href="documentation.html#writing-documentation-comments" id="writing-documentation-comments"><h3>Writing documentation comments</h3></a>
|
||
<p>Anyway, let's cover each part of this comment in detail:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// Constructs a new `Rc<T>`.
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>The first line of a documentation comment should be a short summary of its
|
||
functionality. One sentence. Just the basics. High level.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
///
|
||
/// Other details about constructing `Rc<T>`s, maybe describing complicated
|
||
/// semantics, maybe additional options, all kinds of stuff.
|
||
///
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>Our original example had just a summary line, but if we had more things to say,
|
||
we could have added more explanation in a new paragraph.</p>
|
||
<a class="header" href="documentation.html#special-sections" id="special-sections"><h4>Special sections</h4></a>
|
||
<p>Next, are special sections. These are indicated with a header, <code>#</code>. There
|
||
are four kinds of headers that are commonly used. They aren't special syntax,
|
||
just convention, for now.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// # Panics
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>Unrecoverable misuses of a function (i.e. programming errors) in Rust are
|
||
usually indicated by panics, which kill the whole current thread at the very
|
||
least. If your function has a non-trivial contract like this, that is
|
||
detected/enforced by panics, documenting it is very important.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// # Errors
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>If your function or method returns a <code>Result<T, E></code>, then describing the
|
||
conditions under which it returns <code>Err(E)</code> is a nice thing to do. This is
|
||
slightly less important than <code>Panics</code>, because failure is encoded into the type
|
||
system, but it's still a good thing to do.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// # Safety
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>If your function is <code>unsafe</code>, you should explain which invariants the caller is
|
||
responsible for upholding.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// # Examples
|
||
///
|
||
/// ```
|
||
/// use std::rc::Rc;
|
||
///
|
||
/// let five = Rc::new(5);
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>Fourth, <code>Examples</code>. Include one or more examples of using your function or
|
||
method, and your users will love you for it. These examples go inside of
|
||
code block annotations, which we'll talk about in a moment, and can have
|
||
more than one section:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// # Examples
|
||
///
|
||
/// Simple `&str` patterns:
|
||
///
|
||
/// ```
|
||
/// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
|
||
/// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]);
|
||
/// ```
|
||
///
|
||
/// More complex patterns with a lambda:
|
||
///
|
||
/// ```
|
||
/// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
|
||
/// assert_eq!(v, vec!["abc", "def", "ghi"]);
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<a class="header" href="documentation.html#code-block-annotations" id="code-block-annotations"><h4>Code block annotations</h4></a>
|
||
<p>To write some Rust code in a comment, use the triple graves:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// ```
|
||
/// println!("Hello, world");
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>This will add code highlighting. If you are only showing plain text, put <code>text</code>
|
||
instead of <code>rust</code> after the triple graves (see below).</p>
|
||
<a class="header" href="documentation.html#documentation-as-tests" id="documentation-as-tests"><h2>Documentation as tests</h2></a>
|
||
<p>Let's discuss our sample example documentation:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// ```
|
||
/// println!("Hello, world");
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>You'll notice that you don't need a <code>fn main()</code> or anything here. <code>rustdoc</code> will
|
||
automatically add a <code>main()</code> wrapper around your code, using heuristics to attempt
|
||
to put it in the right place. For example:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// ```
|
||
/// use std::rc::Rc;
|
||
///
|
||
/// let five = Rc::new(5);
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>This will end up testing:</p>
|
||
<pre><pre class="playpen"><code class="language-rust">fn main() {
|
||
use std::rc::Rc;
|
||
let five = Rc::new(5);
|
||
}
|
||
</code></pre></pre>
|
||
<p>Here's the full algorithm rustdoc uses to preprocess examples:</p>
|
||
<ol>
|
||
<li>Any leading <code>#![foo]</code> attributes are left intact as crate attributes.</li>
|
||
<li>Some common <code>allow</code> attributes are inserted, including
|
||
<code>unused_variables</code>, <code>unused_assignments</code>, <code>unused_mut</code>,
|
||
<code>unused_attributes</code>, and <code>dead_code</code>. Small examples often trigger
|
||
these lints.</li>
|
||
<li>If the example does not contain <code>extern crate</code>, then <code>extern crate <mycrate>;</code> is inserted (note the lack of <code>#[macro_use]</code>).</li>
|
||
<li>Finally, if the example does not contain <code>fn main</code>, the remainder of the
|
||
text is wrapped in <code>fn main() { your_code }</code>.</li>
|
||
</ol>
|
||
<p>This generated <code>fn main</code> can be a problem! If you have <code>extern crate</code> or a <code>mod</code>
|
||
statements in the example code that are referred to by <code>use</code> statements, they will
|
||
fail to resolve unless you include at least <code>fn main() {}</code> to inhibit step 4.
|
||
<code>#[macro_use] extern crate</code> also does not work except at the crate root, so when
|
||
testing macros an explicit <code>main</code> is always required. It doesn't have to clutter
|
||
up your docs, though -- keep reading!</p>
|
||
<p>Sometimes this algorithm isn't enough, though. For example, all of these code samples
|
||
with <code>///</code> we've been talking about? The raw text:</p>
|
||
<pre><code class="language-text">/// Some documentation.
|
||
# fn foo() {}
|
||
</code></pre>
|
||
<p>looks different than the output:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// Some documentation.
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>Yes, that's right: you can add lines that start with <code>#</code>, and they will
|
||
be hidden from the output, but will be used when compiling your code. You
|
||
can use this to your advantage. In this case, documentation comments need
|
||
to apply to some kind of function, so if I want to show you just a
|
||
documentation comment, I need to add a little function definition below
|
||
it. At the same time, it's only there to satisfy the compiler, so hiding
|
||
it makes the example more clear. You can use this technique to explain
|
||
longer examples in detail, while still preserving the testability of your
|
||
documentation.</p>
|
||
<p>For example, imagine that we wanted to document this code:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
let x = 5;
|
||
let y = 6;
|
||
println!("{}", x + y);
|
||
|
||
#}</code></pre></pre>
|
||
<p>We might want the documentation to end up looking like this:</p>
|
||
<blockquote>
|
||
<p>First, we set <code>x</code> to five:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
let x = 5;
|
||
# let y = 6;
|
||
# println!("{}", x + y);
|
||
|
||
#}</code></pre></pre>
|
||
<p>Next, we set <code>y</code> to six:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
# let x = 5;
|
||
let y = 6;
|
||
# println!("{}", x + y);
|
||
|
||
#}</code></pre></pre>
|
||
<p>Finally, we print the sum of <code>x</code> and <code>y</code>:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
# let x = 5;
|
||
# let y = 6;
|
||
println!("{}", x + y);
|
||
|
||
#}</code></pre></pre>
|
||
</blockquote>
|
||
<p>To keep each code block testable, we want the whole program in each block, but
|
||
we don't want the reader to see every line every time. Here's what we put in
|
||
our source code:</p>
|
||
<pre><code class="language-text"> First, we set `x` to five:
|
||
|
||
```rust
|
||
let x = 5;
|
||
# let y = 6;
|
||
# println!("{}", x + y);
|
||
```
|
||
|
||
Next, we set `y` to six:
|
||
|
||
```rust
|
||
# let x = 5;
|
||
let y = 6;
|
||
# println!("{}", x + y);
|
||
```
|
||
|
||
Finally, we print the sum of `x` and `y`:
|
||
|
||
```rust
|
||
# let x = 5;
|
||
# let y = 6;
|
||
println!("{}", x + y);
|
||
```
|
||
</code></pre>
|
||
<p>By repeating all parts of the example, you can ensure that your example still
|
||
compiles, while only showing the parts that are relevant to that part of your
|
||
explanation.</p>
|
||
<a class="header" href="documentation.html#documenting-macros" id="documenting-macros"><h3>Documenting macros</h3></a>
|
||
<p>Here’s an example of documenting a macro:</p>
|
||
<pre><pre class="playpen"><code class="language-rust">/// Panic with a given message unless an expression evaluates to true.
|
||
///
|
||
/// # Examples
|
||
///
|
||
/// ```
|
||
/// # #[macro_use] extern crate foo;
|
||
/// # fn main() {
|
||
/// panic_unless!(1 + 1 == 2, “Math is broken.”);
|
||
/// # }
|
||
/// ```
|
||
///
|
||
/// ```rust,should_panic
|
||
/// # #[macro_use] extern crate foo;
|
||
/// # fn main() {
|
||
/// panic_unless!(true == false, “I’m broken.”);
|
||
/// # }
|
||
/// ```
|
||
#[macro_export]
|
||
macro_rules! panic_unless {
|
||
($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
|
||
}
|
||
# fn main() {}
|
||
</code></pre></pre>
|
||
<p>You’ll note three things: we need to add our own <code>extern crate</code> line, so that
|
||
we can add the <code>#[macro_use]</code> attribute. Second, we’ll need to add our own
|
||
<code>main()</code> as well (for reasons discussed above). Finally, a judicious use of
|
||
<code>#</code> to comment out those two things, so they don’t show up in the output.</p>
|
||
<p>Another case where the use of <code>#</code> is handy is when you want to ignore
|
||
error handling. Lets say you want the following,</p>
|
||
<pre><code class="language-rust ignore">/// use std::io;
|
||
/// let mut input = String::new();
|
||
/// try!(io::stdin().read_line(&mut input));
|
||
</code></pre>
|
||
<p>The problem is that <code>try!</code> returns a <code>Result<T, E></code> and test functions
|
||
don't return anything so this will give a mismatched types error.</p>
|
||
<pre><code class="language-rust ignore">/// A doc test using try!
|
||
///
|
||
/// ```
|
||
/// use std::io;
|
||
/// # fn foo() -> io::Result<()> {
|
||
/// let mut input = String::new();
|
||
/// try!(io::stdin().read_line(&mut input));
|
||
/// # Ok(())
|
||
/// # }
|
||
/// ```
|
||
# fn foo() {}
|
||
</code></pre>
|
||
<p>You can get around this by wrapping the code in a function. This catches
|
||
and swallows the <code>Result<T, E></code> when running tests on the docs. This
|
||
pattern appears regularly in the standard library.</p>
|
||
<a class="header" href="documentation.html#running-documentation-tests" id="running-documentation-tests"><h3>Running documentation tests</h3></a>
|
||
<p>To run the tests, either:</p>
|
||
<pre><code class="language-bash">$ rustdoc --test path/to/my/crate/root.rs
|
||
# or
|
||
$ cargo test
|
||
</code></pre>
|
||
<p>That's right, <code>cargo test</code> tests embedded documentation too. <strong>However,
|
||
<code>cargo test</code> will not test binary crates, only library ones.</strong> This is
|
||
due to the way <code>rustdoc</code> works: it links against the library to be tested,
|
||
but with a binary, there’s nothing to link to.</p>
|
||
<p>There are a few more annotations that are useful to help <code>rustdoc</code> do the right
|
||
thing when testing your code:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// ```rust,ignore
|
||
/// fn foo() {
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>The <code>ignore</code> directive tells Rust to ignore your code. This is almost never
|
||
what you want, as it's the most generic. Instead, consider annotating it
|
||
with <code>text</code> if it's not code, or using <code>#</code>s to get a working example that
|
||
only shows the part you care about.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// ```rust,should_panic
|
||
/// assert!(false);
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p><code>should_panic</code> tells <code>rustdoc</code> that the code should compile correctly, but
|
||
not actually pass as a test.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// ```rust,no_run
|
||
/// loop {
|
||
/// println!("Hello, world");
|
||
/// }
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>The <code>no_run</code> attribute will compile your code, but not run it. This is
|
||
important for examples such as "Here's how to retrieve a web page,"
|
||
which you would want to ensure compiles, but might be run in a test
|
||
environment that has no network access.</p>
|
||
<a class="header" href="documentation.html#documenting-modules" id="documenting-modules"><h3>Documenting modules</h3></a>
|
||
<p>Rust has another kind of doc comment, <code>//!</code>. This comment doesn't document the next item, but the enclosing item. In other words:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
mod foo {
|
||
//! This is documentation for the `foo` module.
|
||
//!
|
||
//! # Examples
|
||
|
||
// ...
|
||
}
|
||
|
||
#}</code></pre></pre>
|
||
<p>This is where you'll see <code>//!</code> used most often: for module documentation. If
|
||
you have a module in <code>foo.rs</code>, you'll often open its code and see this:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
//! A module for using `foo`s.
|
||
//!
|
||
//! The `foo` module contains a lot of useful functionality blah blah blah...
|
||
|
||
#}</code></pre></pre>
|
||
<a class="header" href="documentation.html#crate-documentation" id="crate-documentation"><h3>Crate documentation</h3></a>
|
||
<p>Crates can be documented by placing an inner doc comment (<code>//!</code>) at the
|
||
beginning of the crate root, aka <code>lib.rs</code>:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
//! This is documentation for the `foo` crate.
|
||
//!
|
||
//! The foo crate is meant to be used for bar.
|
||
|
||
#}</code></pre></pre>
|
||
<a class="header" href="documentation.html#documentation-comment-style" id="documentation-comment-style"><h3>Documentation comment style</h3></a>
|
||
<p>Check out <a href="https://github.com/rust-lang/rfcs/blob/master/text/0505-api-comment-conventions.md">RFC 505</a> for full conventions around the style and format of
|
||
documentation.</p>
|
||
<a class="header" href="documentation.html#other-documentation" id="other-documentation"><h2>Other documentation</h2></a>
|
||
<p>All of this behavior works in non-Rust source files too. Because comments
|
||
are written in Markdown, they're often <code>.md</code> files.</p>
|
||
<p>When you write documentation in Markdown files, you don't need to prefix
|
||
the documentation with comments. For example:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// # Examples
|
||
///
|
||
/// ```
|
||
/// use std::rc::Rc;
|
||
///
|
||
/// let five = Rc::new(5);
|
||
/// ```
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>is:</p>
|
||
<pre><code class="language-markdown"># Examples
|
||
|
||
```
|
||
use std::rc::Rc;
|
||
|
||
let five = Rc::new(5);
|
||
```
|
||
</code></pre>
|
||
<p>when it's in a Markdown file. There is one wrinkle though: Markdown files need
|
||
to have a title like this:</p>
|
||
<pre><code class="language-markdown">% The title
|
||
|
||
This is the example documentation.
|
||
</code></pre>
|
||
<p>This <code>%</code> line needs to be the very first line of the file.</p>
|
||
<a class="header" href="documentation.html#doc-attributes" id="doc-attributes"><h2><code>doc</code> attributes</h2></a>
|
||
<p>At a deeper level, documentation comments are syntactic sugar for documentation
|
||
attributes:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// this
|
||
# fn foo() {}
|
||
|
||
#[doc="this"]
|
||
# fn bar() {}
|
||
|
||
#}</code></pre></pre>
|
||
<p>are the same, as are these:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
//! this
|
||
|
||
#![doc="this"]
|
||
|
||
#}</code></pre></pre>
|
||
<p>You won't often see this attribute used for writing documentation, but it
|
||
can be useful when changing some options, or when writing a macro.</p>
|
||
<a class="header" href="documentation.html#re-exports" id="re-exports"><h3>Re-exports</h3></a>
|
||
<p><code>rustdoc</code> will show the documentation for a public re-export in both places:</p>
|
||
<pre><code class="language-rust ignore">extern crate foo;
|
||
|
||
pub use foo::bar;
|
||
</code></pre>
|
||
<p>This will create documentation for <code>bar</code> both inside the documentation for the
|
||
crate <code>foo</code>, as well as the documentation for your crate. It will use the same
|
||
documentation in both places.</p>
|
||
<p>This behavior can be suppressed with <code>no_inline</code>:</p>
|
||
<pre><code class="language-rust ignore">extern crate foo;
|
||
|
||
#[doc(no_inline)]
|
||
pub use foo::bar;
|
||
</code></pre>
|
||
<a class="header" href="documentation.html#missing-documentation" id="missing-documentation"><h2>Missing documentation</h2></a>
|
||
<p>Sometimes you want to make sure that every single public thing in your project
|
||
is documented, especially when you are working on a library. Rust allows you to
|
||
to generate warnings or errors, when an item is missing documentation.
|
||
To generate warnings you use <code>warn</code>:</p>
|
||
<pre><code class="language-rust ignore">#![warn(missing_docs)]
|
||
</code></pre>
|
||
<p>And to generate errors you use <code>deny</code>:</p>
|
||
<pre><code class="language-rust ignore">#![deny(missing_docs)]
|
||
</code></pre>
|
||
<p>There are cases where you want to disable these warnings/errors to explicitly
|
||
leave something undocumented. This is done by using <code>allow</code>:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
#[allow(missing_docs)]
|
||
struct Undocumented;
|
||
|
||
#}</code></pre></pre>
|
||
<p>You might even want to hide items from the documentation completely:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
#[doc(hidden)]
|
||
struct Hidden;
|
||
|
||
#}</code></pre></pre>
|
||
<a class="header" href="documentation.html#controlling-html" id="controlling-html"><h3>Controlling HTML</h3></a>
|
||
<p>You can control a few aspects of the HTML that <code>rustdoc</code> generates through the
|
||
<code>#![doc]</code> version of the attribute:</p>
|
||
<pre><code class="language-rust ignore">#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
|
||
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
|
||
html_root_url = "https://doc.rust-lang.org/")]
|
||
</code></pre>
|
||
<p>This sets a few different options, with a logo, favicon, and a root URL.</p>
|
||
<a class="header" href="documentation.html#configuring-documentation-tests" id="configuring-documentation-tests"><h3>Configuring documentation tests</h3></a>
|
||
<p>You can also configure the way that <code>rustdoc</code> tests your documentation examples
|
||
through the <code>#![doc(test(..))]</code> attribute.</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
#![doc(test(attr(allow(unused_variables), deny(warnings))))]
|
||
|
||
#}</code></pre></pre>
|
||
<p>This allows unused variables within the examples, but will fail the test for any
|
||
other lint warning thrown.</p>
|
||
<a class="header" href="documentation.html#generation-options" id="generation-options"><h2>Generation options</h2></a>
|
||
<p><code>rustdoc</code> also contains a few other options on the command line, for further customization:</p>
|
||
<ul>
|
||
<li><code>--html-in-header FILE</code>: includes the contents of FILE at the end of the
|
||
<code><head>...</head></code> section.</li>
|
||
<li><code>--html-before-content FILE</code>: includes the contents of FILE directly after
|
||
<code><body></code>, before the rendered content (including the search bar).</li>
|
||
<li><code>--html-after-content FILE</code>: includes the contents of FILE after all the rendered content.</li>
|
||
</ul>
|
||
<a class="header" href="documentation.html#security-note" id="security-note"><h2>Security note</h2></a>
|
||
<p>The Markdown in documentation comments is placed without processing into
|
||
the final webpage. Be careful with literal HTML:</p>
|
||
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
|
||
#
|
||
#fn main() {
|
||
/// <script>alert(document.cookie)</script>
|
||
# fn foo() {}
|
||
|
||
#}</code></pre></pre>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="conditional-compilation.html" class="mobile-nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="iterators.html" class="mobile-nav-chapters next">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<a href="conditional-compilation.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="iterators.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
|
||
<i class="fa fa-angle-right"></i>
|
||
</a>
|
||
|
||
|
||
</div>
|
||
|
||
|
||
<!-- Local fallback for Font Awesome -->
|
||
<script>
|
||
if ($(".fa").css("font-family") !== "FontAwesome") {
|
||
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
|
||
}
|
||
</script>
|
||
|
||
<!-- Livereload script (if served using the cli tool) -->
|
||
|
||
|
||
<script src="highlight.js"></script>
|
||
<script src="book.js"></script>
|
||
</body>
|
||
</html>
|