Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > fdedb3cf2140df9b6d419a2338ab1caa > files > 480

rust-doc-1.25.0-1.mga6.x86_64.rpm

<!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">
        <meta name="theme-color" content="#ffffff" />

        <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 href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" 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">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme -->
        

        

        <!-- Fetch Clipboard.js from CDN but have a local fallback -->
        <script src="https://cdn.jsdelivr.net/clipboard.js/1.6.1/clipboard.min.js"></script>
        <script>
            if (typeof Clipboard == 'undefined') {
                document.write(unescape("%3Cscript src='clipboard.min.js'%3E%3C/script%3E"));
            }
        </script>

    </head>
    <body class="light">
        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = 'light'; }
            document.body.className = theme;
            document.querySelector('html').className = theme;
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            document.querySelector('html').classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong aria-hidden="true">1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong aria-hidden="true">2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong aria-hidden="true">3.</strong> Syntax and Semantics</a></li><li><ol class="section"><li><a href="variable-bindings.html"><strong aria-hidden="true">3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong aria-hidden="true">3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong aria-hidden="true">3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong aria-hidden="true">3.4.</strong> Comments</a></li><li><a href="if.html"><strong aria-hidden="true">3.5.</strong> if</a></li><li><a href="loops.html"><strong aria-hidden="true">3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong aria-hidden="true">3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong aria-hidden="true">3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong aria-hidden="true">3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong aria-hidden="true">3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong aria-hidden="true">3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong aria-hidden="true">3.12.</strong> Structs</a></li><li><a href="enums.html"><strong aria-hidden="true">3.13.</strong> Enums</a></li><li><a href="match.html"><strong aria-hidden="true">3.14.</strong> Match</a></li><li><a href="patterns.html"><strong aria-hidden="true">3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong aria-hidden="true">3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong aria-hidden="true">3.17.</strong> Strings</a></li><li><a href="generics.html"><strong aria-hidden="true">3.18.</strong> Generics</a></li><li><a href="traits.html"><strong aria-hidden="true">3.19.</strong> Traits</a></li><li><a href="drop.html"><strong aria-hidden="true">3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong aria-hidden="true">3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong aria-hidden="true">3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong aria-hidden="true">3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong aria-hidden="true">3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong aria-hidden="true">3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong aria-hidden="true">3.26.</strong> const and static</a></li><li><a href="attributes.html"><strong aria-hidden="true">3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong aria-hidden="true">3.28.</strong> type aliases</a></li><li><a href="casting-between-types.html"><strong aria-hidden="true">3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong aria-hidden="true">3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong aria-hidden="true">3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong aria-hidden="true">3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong aria-hidden="true">3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong aria-hidden="true">3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong aria-hidden="true">3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong aria-hidden="true">3.36.</strong> unsafe</a></li></ol></li><li><a href="effective-rust.html"><strong aria-hidden="true">4.</strong> Effective Rust</a></li><li><ol class="section"><li><a href="the-stack-and-the-heap.html"><strong aria-hidden="true">4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong aria-hidden="true">4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong aria-hidden="true">4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html" class="active"><strong aria-hidden="true">4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong aria-hidden="true">4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong aria-hidden="true">4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong aria-hidden="true">4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong aria-hidden="true">4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong aria-hidden="true">4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong aria-hidden="true">4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong aria-hidden="true">4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong aria-hidden="true">4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">4.13.</strong> Procedural Macros (and custom derive)</a></li></ol></li><li><a href="glossary.html"><strong aria-hidden="true">5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong aria-hidden="true">6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong aria-hidden="true">7.</strong> Bibliography</a></li></ol>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                
                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                                <i class="fa fa-paint-brush"></i>
                            </button>
                            <ul id="theme-list" class="theme-popup" aria-label="submenu">
                                <li><button class="theme" id="light">Light <span class="default">(default)</span></button></li>
                                <li><button class="theme" id="rust">Rust</button></li>
                                <li><button class="theme" id="coal">Coal</button></li>
                                <li><button class="theme" id="navy">Navy</button></li>
                                <li><button class="theme" id="ayu">Ayu</button></li>
                            </ul>
                        </div>

                        <h1 class="menu-title">The Rust Programming Language</h1>

                        <div class="right-buttons">
                            <a href="print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <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&lt;T&gt;`.
///
/// # Examples
///
/// ```
/// use std::rc::Rc;
///
/// let five = Rc::new(5);
/// ```
pub fn new(value: T) -&gt; Rc&lt;T&gt; {
    // 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&lt;T&gt; {
    /// 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&lt;T&gt; {
    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&lt;T&gt;`.
# 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&lt;T&gt;`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&lt;T, E&gt;</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 `&amp;str` patterns:
///
/// ```
/// let v: Vec&lt;&amp;str&gt; = &quot;Mary had a little lamb&quot;.split(' ').collect();
/// assert_eq!(v, vec![&quot;Mary&quot;, &quot;had&quot;, &quot;a&quot;, &quot;little&quot;, &quot;lamb&quot;]);
/// ```
///
/// More complex patterns with a lambda:
///
/// ```
/// let v: Vec&lt;&amp;str&gt; = &quot;abc1def2ghi&quot;.split(|c: char| c.is_numeric()).collect();
/// assert_eq!(v, vec![&quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;]);
/// ```
# 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!(&quot;Hello, world&quot;);
/// ```
# 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!(&quot;Hello, world&quot;);
/// ```
# 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 &lt;mycrate&gt;;</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!(&quot;{}&quot;, 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!(&quot;{}&quot;, 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!(&quot;{}&quot;, 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!(&quot;{}&quot;, 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!(&quot;{}&quot;, x + y);
    ```

    Next, we set `y` to six:

    ```rust
    # let x = 5;
    let y = 6;
    # println!(&quot;{}&quot;, x + y);
    ```

    Finally, we print the sum of `x` and `y`:

    ```rust
    # let x = 5;
    # let y = 6;
    println!(&quot;{}&quot;, 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),+) =&gt; ({ 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(&amp;mut input));
</code></pre>
<p>The problem is that <code>try!</code> returns a <code>Result&lt;T, E&gt;</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() -&gt; io::Result&lt;()&gt; {
/// let mut input = String::new();
/// try!(io::stdin().read_line(&amp;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&lt;T, E&gt;</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!(&quot;Hello, world&quot;);
/// }
/// ```
# 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 &quot;Here's how to retrieve a web page,&quot;
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=&quot;this&quot;]
# 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=&quot;this&quot;]
#}</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 = &quot;https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png&quot;,
       html_favicon_url = &quot;https://www.rust-lang.org/favicon.ico&quot;,
       html_root_url = &quot;https://doc.rust-lang.org/&quot;)]
</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)]
#![doc(test(attr(allow(unused_variables), deny(warnings))))]
#fn main() {
#}</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>&lt;head&gt;...&lt;/head&gt;</code> section.</li>
<li><code>--html-before-content FILE</code>: includes the contents of FILE directly after
<code>&lt;body&gt;</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() {
/// &lt;script&gt;alert(document.cookie)&lt;/script&gt;
# fn foo() {}
#}</code></pre></pre>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="conditional-compilation.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="iterators.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a href="conditional-compilation.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="iterators.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if (getComputedStyle(document.querySelector(".fa")).fontFamily !== "FontAwesome") {
                var link = document.createElement('link');
                link.rel = 'stylesheet';
                link.type = 'text/css';
                link.href = '_FontAwesome/css/font-awesome.css';
                document.head.insertBefore(link, document.head.firstChild)
            }
        </script>

        

        

        

        

        <script src="highlight.js"></script>
        <script src="book.js"></script>

        <!-- Custom JS script -->
        

    </body>
</html>