Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 4e2dbb669434a7691662cb2f0ad38972 > files > 11140

rust-doc-1.28.0-1.mga6.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>The Rust Reference</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="_FontAwesome/css/font-awesome.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        
        <link rel="stylesheet" href="src/theme/reference.css">
        

        

    </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 + ' js';
        </script>

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

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li class="affix"><a href="introduction.html">Introduction</a></li><li><a href="notation.html"><strong aria-hidden="true">1.</strong> Notation</a></li><li><a href="lexical-structure.html"><strong aria-hidden="true">2.</strong> Lexical structure</a></li><li><ol class="section"><li><a href="input-format.html"><strong aria-hidden="true">2.1.</strong> Input format</a></li><li><a href="keywords.html"><strong aria-hidden="true">2.2.</strong> Keywords</a></li><li><a href="identifiers.html"><strong aria-hidden="true">2.3.</strong> Identifiers</a></li><li><a href="comments.html"><strong aria-hidden="true">2.4.</strong> Comments</a></li><li><a href="whitespace.html"><strong aria-hidden="true">2.5.</strong> Whitespace</a></li><li><a href="tokens.html"><strong aria-hidden="true">2.6.</strong> Tokens</a></li><li><a href="paths.html"><strong aria-hidden="true">2.7.</strong> Paths</a></li></ol></li><li><a href="macros.html"><strong aria-hidden="true">3.</strong> Macros</a></li><li><ol class="section"><li><a href="macros-by-example.html"><strong aria-hidden="true">3.1.</strong> Macros By Example</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">3.2.</strong> Procedural Macros</a></li></ol></li><li><a href="crates-and-source-files.html"><strong aria-hidden="true">4.</strong> Crates and source files</a></li><li><a href="items-and-attributes.html"><strong aria-hidden="true">5.</strong> Items and attributes</a></li><li><ol class="section"><li><a href="items.html"><strong aria-hidden="true">5.1.</strong> Items</a></li><li><ol class="section"><li><a href="items/modules.html"><strong aria-hidden="true">5.1.1.</strong> Modules</a></li><li><a href="items/extern-crates.html"><strong aria-hidden="true">5.1.2.</strong> Extern crates</a></li><li><a href="items/use-declarations.html"><strong aria-hidden="true">5.1.3.</strong> Use declarations</a></li><li><a href="items/functions.html"><strong aria-hidden="true">5.1.4.</strong> Functions</a></li><li><a href="items/type-aliases.html"><strong aria-hidden="true">5.1.5.</strong> Type aliases</a></li><li><a href="items/structs.html"><strong aria-hidden="true">5.1.6.</strong> Structs</a></li><li><a href="items/enumerations.html"><strong aria-hidden="true">5.1.7.</strong> Enumerations</a></li><li><a href="items/unions.html"><strong aria-hidden="true">5.1.8.</strong> Unions</a></li><li><a href="items/constant-items.html"><strong aria-hidden="true">5.1.9.</strong> Constant items</a></li><li><a href="items/static-items.html"><strong aria-hidden="true">5.1.10.</strong> Static items</a></li><li><a href="items/traits.html"><strong aria-hidden="true">5.1.11.</strong> Traits</a></li><li><a href="items/implementations.html"><strong aria-hidden="true">5.1.12.</strong> Implementations</a></li><li><a href="items/external-blocks.html"><strong aria-hidden="true">5.1.13.</strong> External blocks</a></li></ol></li><li><a href="items/generics.html"><strong aria-hidden="true">5.2.</strong> Type and lifetime parameters</a></li><li><a href="items/associated-items.html"><strong aria-hidden="true">5.3.</strong> Associated Items</a></li><li><a href="visibility-and-privacy.html"><strong aria-hidden="true">5.4.</strong> Visibility and Privacy</a></li><li><a href="attributes.html"><strong aria-hidden="true">5.5.</strong> Attributes</a></li></ol></li><li><a href="statements-and-expressions.html"><strong aria-hidden="true">6.</strong> Statements and expressions</a></li><li><ol class="section"><li><a href="statements.html"><strong aria-hidden="true">6.1.</strong> Statements</a></li><li><a href="expressions.html"><strong aria-hidden="true">6.2.</strong> Expressions</a></li><li><ol class="section"><li><a href="expressions/literal-expr.html"><strong aria-hidden="true">6.2.1.</strong> Literal expressions</a></li><li><a href="expressions/path-expr.html"><strong aria-hidden="true">6.2.2.</strong> Path expressions</a></li><li><a href="expressions/block-expr.html"><strong aria-hidden="true">6.2.3.</strong> Block expressions</a></li><li><a href="expressions/operator-expr.html"><strong aria-hidden="true">6.2.4.</strong> Operator expressions</a></li><li><a href="expressions/grouped-expr.html"><strong aria-hidden="true">6.2.5.</strong> Grouped expressions</a></li><li><a href="expressions/array-expr.html"><strong aria-hidden="true">6.2.6.</strong> Array and index expressions</a></li><li><a href="expressions/tuple-expr.html"><strong aria-hidden="true">6.2.7.</strong> Tuple and index expressions</a></li><li><a href="expressions/struct-expr.html"><strong aria-hidden="true">6.2.8.</strong> Struct expressions</a></li><li><a href="expressions/enum-variant-expr.html"><strong aria-hidden="true">6.2.9.</strong> Enum variant expressions</a></li><li><a href="expressions/call-expr.html"><strong aria-hidden="true">6.2.10.</strong> Call expressions</a></li><li><a href="expressions/method-call-expr.html"><strong aria-hidden="true">6.2.11.</strong> Method call expressions</a></li><li><a href="expressions/field-expr.html"><strong aria-hidden="true">6.2.12.</strong> Field access expressions</a></li><li><a href="expressions/closure-expr.html"><strong aria-hidden="true">6.2.13.</strong> Closure expressions</a></li><li><a href="expressions/loop-expr.html"><strong aria-hidden="true">6.2.14.</strong> Loop expressions</a></li><li><a href="expressions/range-expr.html"><strong aria-hidden="true">6.2.15.</strong> Range expressions</a></li><li><a href="expressions/if-expr.html"><strong aria-hidden="true">6.2.16.</strong> If and if let expressions</a></li><li><a href="expressions/match-expr.html"><strong aria-hidden="true">6.2.17.</strong> Match expressions</a></li><li><a href="expressions/return-expr.html"><strong aria-hidden="true">6.2.18.</strong> Return expressions</a></li></ol></li></ol></li><li><a href="type-system.html"><strong aria-hidden="true">7.</strong> Type system</a></li><li><ol class="section"><li><a href="types.html"><strong aria-hidden="true">7.1.</strong> Types</a></li><li><a href="dynamically-sized-types.html"><strong aria-hidden="true">7.2.</strong> Dynamically Sized Types</a></li><li><a href="type-layout.html"><strong aria-hidden="true">7.3.</strong> Type layout</a></li><li><a href="interior-mutability.html"><strong aria-hidden="true">7.4.</strong> Interior mutability</a></li><li><a href="subtyping.html"><strong aria-hidden="true">7.5.</strong> Subtyping and Variance</a></li><li><a href="trait-bounds.html"><strong aria-hidden="true">7.6.</strong> Trait and lifetime bounds</a></li><li><a href="type-coercions.html"><strong aria-hidden="true">7.7.</strong> Type coercions</a></li><li><a href="destructors.html"><strong aria-hidden="true">7.8.</strong> Destructors</a></li><li><a href="lifetime-elision.html"><strong aria-hidden="true">7.9.</strong> Lifetime elision</a></li></ol></li><li><a href="special-types-and-traits.html"><strong aria-hidden="true">8.</strong> Special types and traits</a></li><li><a href="memory-model.html"><strong aria-hidden="true">9.</strong> Memory model</a></li><li><ol class="section"><li><a href="memory-allocation-and-lifetime.html"><strong aria-hidden="true">9.1.</strong> Memory allocation and lifetime</a></li><li><a href="memory-ownership.html"><strong aria-hidden="true">9.2.</strong> Memory ownership</a></li><li><a href="variables.html"><strong aria-hidden="true">9.3.</strong> Variables</a></li></ol></li><li><a href="linkage.html"><strong aria-hidden="true">10.</strong> Linkage</a></li><li><a href="unsafety.html"><strong aria-hidden="true">11.</strong> Unsafety</a></li><li><ol class="section"><li><a href="unsafe-functions.html"><strong aria-hidden="true">11.1.</strong> Unsafe functions</a></li><li><a href="unsafe-blocks.html"><strong aria-hidden="true">11.2.</strong> Unsafe blocks</a></li><li><a href="behavior-considered-undefined.html"><strong aria-hidden="true">11.3.</strong> Behavior considered undefined</a></li><li><a href="behavior-not-considered-unsafe.html"><strong aria-hidden="true">11.4.</strong> Behavior not considered unsafe</a></li></ol></li><li><a href="influences.html">Appendix: Influences</a></li><li class="affix"><a href="undocumented.html">Appendix: As-yet-undocumented Features</a></li><li class="affix"><a href="glossary.html">Appendix: Glossary</a></li></ol>
        </nav>

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

            <div class="page">
                <header><p class="warning">
    For now, this reference is a best-effort document. We strive for validity
    and completeness, but are not yet there. In the future, the docs and lang
    teams will work together to figure out how best to do this. Until then, this
    is a best-effort attempt. If you find something wrong or missing, file an
    <a href="https://github.com/rust-lang-nursery/reference/issues">issue</a> or
    send in a pull request.
</p></header>
                <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="Themes" role="menu">
                                <li role="none"><button role="menuitem" class="theme" id="light">Light <span class="default">(default)</span></button></li>
                                <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                            </ul>
                            
                            <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                                <i class="fa fa-search"></i>
                            </button>
                            
                        </div>

                        <h1 class="menu-title">The Rust Reference</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>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </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="print.html#introduction" id="introduction"><h1>Introduction</h1></a>
<p>This document is the primary reference for the Rust programming language. It
provides three kinds of material:</p>
<ul>
<li>Chapters that informally describe each language construct and their use.</li>
<li>Chapters that informally describe the memory model, concurrency model,
runtime services, linkage model and debugging facilities.</li>
<li>Appendix chapters providing rationale and references to languages that
influenced the design.</li>
</ul>
<p>This document does not serve as an introduction to the language. Background
familiarity with the language is assumed. A separate <a href="../book/index.html">book</a> is available to
help acquire such background familiarity.</p>
<p>This document also does not serve as a reference to the <a href="../std/index.html">standard</a> library
included in the language distribution. Those libraries are documented
separately by extracting documentation attributes from their source code. Many
of the features that one might expect to be language features are library
features in Rust, so what you're looking for may be there, not here.</p>
<p>This document also only serves as a reference to what is available in stable
Rust. For unstable features being worked on, see the <a href="https://doc.rust-lang.org/nightly/unstable-book/">Unstable Book</a>. This was
a recent change in scope, so unstable features are still documented, but are
in the process of being removed.</p>
<p>Finally, this document is not normative. It may include details that are
specific to <code>rustc</code> itself, and should not be taken as a specification for
the Rust language. We intend to produce such a document someday, but this
is what we have for now.</p>
<p>You may also be interested in the <a href="../grammar.html">grammar</a>.</p>
<p>You can contribute to this document by opening an issue or sending a pull
request to <a href="https://github.com/rust-lang-nursery/reference/">the Rust Reference repository</a>.</p>
<p>N. B. This document may be incomplete. Documenting everything might take a
while. We have a <a href="https://github.com/rust-lang-nursery/reference/issues/9">big issue</a> to track documentation for every Rust feature,
so check that out if you can't find something here.</p>
<a class="header" href="print.html#notation" id="notation"><h1>Notation</h1></a>
<a class="header" href="print.html#unicode-productions" id="unicode-productions"><h2>Unicode productions</h2></a>
<p>A few productions in Rust's grammar permit Unicode code points outside the
ASCII range. We define these productions in terms of character properties
specified in the Unicode standard, rather than in terms of ASCII-range code
points. The grammar has a <a href="../grammar.html#special-unicode-productions">Special Unicode Productions</a> section that lists these
productions.</p>
<a class="header" href="print.html#string-table-productions" id="string-table-productions"><h2>String table productions</h2></a>
<p>Some rules in the grammar — notably <a href="expressions/operator-expr.html#borrow-operators">unary operators</a>, <a href="expressions/operator-expr.html#arithmetic-and-logical-binary-operators">binary
operators</a>, and <a href="keywords.html">keywords</a> — are given in a simplified form: as a listing
of printable strings. These cases form a subset of the rules regarding the
<a href="tokens.html">token</a> rule, and are assumed to be the result of a lexical-analysis
phase feeding the parser, driven by a <abbr title="Deterministic Finite
Automaton">DFA</abbr>, operating over the disjunction of all such string table
entries.</p>
<p>When such a string in <code>monospace</code> font occurs inside the grammar,
it is an implicit reference to a single member of such a string table
production. See <a href="tokens.html">tokens</a> for more information.</p>
<a class="header" href="print.html#lexical-structure" id="lexical-structure"><h1>Lexical structure</h1></a>
<a class="header" href="print.html#input-format" id="input-format"><h1>Input format</h1></a>
<p>Rust input is interpreted as a sequence of Unicode code points encoded in UTF-8.
Most Rust grammar rules are defined in terms of printable ASCII-range
code points, but a small number are defined in terms of Unicode properties or
explicit code point lists. <sup class="footnote-reference"><a href="print.html#inputformat">1</a></sup></p>
<div class="footnote-definition" id="inputformat"><sup class="footnote-definition-label">1</sup>
<p>Substitute definitions for the special Unicode productions are
provided to the grammar verifier, restricted to ASCII range, when verifying the
grammar in this document.</p>
</div>
<a class="header" href="print.html#keywords" id="keywords"><h1>Keywords</h1></a>
<p>Rust divides keywords into three categories:</p>
<ul>
<li><a href="print.html#strict-keywords">strict</a></li>
<li><a href="print.html#reserved-keywords">reserved</a></li>
<li><a href="print.html#weak-keywords">weak</a></li>
</ul>
<a class="header" href="print.html#strict-keywords" id="strict-keywords"><h2>Strict keywords</h2></a>
<p>These keywords can only be used in their correct contexts. They cannot
be used as the names of:</p>
<ul>
<li><a href="items.html">Items</a></li>
<li><a href="variables.html">Variables</a> and function parameters</li>
<li>Fields and <a href="items/enumerations.html">variants</a></li>
<li><a href="types.html#type-parameters">Type parameters</a></li>
<li>Lifetime parameters or <a href="expressions/loop-expr.html#loop-labels">loop labels</a></li>
<li><a href="macros.html">Macros</a> or <a href="attributes.html">attributes</a></li>
<li>[Macro placeholders]</li>
<li><a href="crates-and-source-files.html">Crates</a></li>
</ul>
<blockquote>
<p><strong><sup>Lexer:<sup></strong><br />
KW_AS             : <code>as</code><br />
KW_BREAK          : <code>break</code><br />
KW_CONST          : <code>const</code><br />
KW_CONTINUE       : <code>continue</code><br />
KW_CRATE          : <code>crate</code><br />
KW_ELSE           : <code>else</code><br />
KW_ENUM           : <code>enum</code><br />
KW_EXTERN         : <code>extern</code><br />
KW_FALSE          : <code>false</code><br />
KW_FN             : <code>fn</code><br />
KW_FOR            : <code>for</code><br />
KW_IF             : <code>if</code><br />
KW_IMPL           : <code>impl</code><br />
KW_IN             : <code>in</code><br />
KW_LET            : <code>let</code><br />
KW_LOOP           : <code>loop</code><br />
KW_MATCH          : <code>match</code><br />
KW_MOD            : <code>mod</code><br />
KW_MOVE           : <code>move</code><br />
KW_MUT            : <code>mut</code><br />
KW_PUB            : <code>pub</code><br />
KW_REF            : <code>ref</code><br />
KW_RETURN         : <code>return</code><br />
KW_SELFVALUE      : <code>self</code><br />
KW_SELFTYPE       : <code>Self</code><br />
KW_STATIC         : <code>static</code><br />
KW_STRUCT         : <code>struct</code><br />
KW_SUPER          : <code>super</code><br />
KW_TRAIT          : <code>trait</code><br />
KW_TRUE           : <code>true</code><br />
KW_TYPE           : <code>type</code><br />
KW_UNSAFE         : <code>unsafe</code><br />
KW_USE            : <code>use</code><br />
KW_WHERE          : <code>where</code><br />
KW_WHILE          : <code>while</code></p>
</blockquote>
<a class="header" href="print.html#reserved-keywords" id="reserved-keywords"><h2>Reserved keywords</h2></a>
<p>These keywords aren't used yet, but they are reserved for future use. They have
the same restrictions as strict keywords. The reasoning behind this is to make
current programs forward compatible with future versions of Rust by forbidding
them to use these keywords.</p>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
KW_ABSTRACT       : <code>abstract</code><br />
KW_BECOME         : <code>become</code><br />
KW_BOX            : <code>box</code><br />
KW_DO             : <code>do</code><br />
KW_FINAL          : <code>final</code><br />
KW_MACRO          : <code>macro</code><br />
KW_OVERRIDE       : <code>override</code><br />
KW_PRIV           : <code>priv</code><br />
KW_TYPEOF         : <code>typeof</code><br />
KW_UNSIZED        : <code>unsized</code><br />
KW_VIRTUAL        : <code>virtual</code><br />
KW_YIELD          : <code>yield</code></p>
</blockquote>
<a class="header" href="print.html#weak-keywords" id="weak-keywords"><h2>Weak keywords</h2></a>
<p>These keywords have special meaning only in certain contexts. For example, it
is possible to declare a variable or method with the name <code>union</code>.</p>
<ul>
<li>
<p><code>union</code> is used to declare a <a href="items/unions.html">union</a> and is only a keyword when used in a
union declaration.</p>
</li>
<li>
<p><code>'static</code> is used for the static lifetime and cannot be used as a generic
lifetime parameter</p>
<pre><code class="language-compile_fail">// error[E0262]: invalid lifetime parameter name: `'static`
fn invalid_lifetime_parameter&lt;'static&gt;(s: &amp;'static str) -&gt; &amp;'static str { s }
</code></pre>
</li>
<li>
<p><code>dyn</code> denotes a <a href="types.html#trait-objects">trait object</a> and is a keyword when used in a type position
followed by a path that does not start with <code>::</code>.</p>
</li>
</ul>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
KW_UNION          : <code>union</code>
KW_STATICLIFETIME : <code>'static</code>
KW_DYN            : <code>dyn</code></p>
</blockquote>
<a class="header" href="print.html#identifiers" id="identifiers"><h1>Identifiers</h1></a>
<blockquote>
<p><strong><sup>Lexer:<sup></strong><br />
IDENTIFIER_OR_KEYWORD :<br />
      [<code>a</code>-<code>z</code> <code>A</code>-<code>Z</code>] [<code>a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_</code>]<sup>*</sup><br />
   | <code>_</code> [<code>a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_</code>]<sup>+</sup></p>
<p>IDENTIFIER :<br />
IDENTIFIER_OR_KEYWORD <sub><em>Except a <a href="keywords.html#strict-keywords">strict</a> or <a href="keywords.html#reserved-keywords">reserved</a> keyword</em></sub></p>
</blockquote>
<p>An identifier is any nonempty ASCII string of the following form:</p>
<p>Either</p>
<ul>
<li>The first character is a letter.</li>
<li>The remaining characters are alphanumeric or <code>_</code>.</li>
</ul>
<p>Or</p>
<ul>
<li>The first character is <code>_</code>.</li>
<li>The identifier is more than one character. <code>_</code> alone is not an identifier.</li>
<li>The remaining characters are alphanumeric or <code>_</code>.</li>
</ul>
<a class="header" href="print.html#comments" id="comments"><h1>Comments</h1></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
LINE_COMMENT :<br />
      <code>//</code> (~[<code>/</code> <code>!</code>] | <code>//</code>) ~<code>\n</code><sup>*</sup><br />
   | <code>//</code></p>
<p>BLOCK_COMMENT :<br />
      <code>/*</code> (~[<code>*</code> <code>!</code>] | <code>**</code> | <em>BlockCommentOrDoc</em>)
(<em>BlockCommentOrDoc</em> | ~<code>*/</code>)<sup>*</sup> <code>*/</code><br />
   | <code>/**/</code><br />
   | <code>/***/</code></p>
<p>INNER_LINE_DOC :<br />
   <code>//!</code> ~[<code>\n</code> <em>IsolatedCR</em>]<sup>*</sup></p>
<p>INNER_BLOCK_DOC :<br />
   <code>/*!</code> ( <em>BlockCommentOrDoc</em> | ~[<code>*/</code> <em>IsolatedCR</em>] )<sup>*</sup> <code>*/</code></p>
<p>OUTER_LINE_DOC :<br />
   <code>///</code> (~<code>/</code> ~[<code>\n</code> <em>IsolatedCR</em>]<sup>*</sup>)<sup>?</sup></p>
<p>OUTER_BLOCK_DOC :<br />
   <code>/**</code> (~<code>*</code> | <em>BlockCommentOrDoc</em> )
(<em>BlockCommentOrDoc</em> | ~[<code>*/</code> <em>IsolatedCR</em>])<sup>*</sup> <code>*/</code></p>
<p><em>BlockCommentOrDoc</em> :<br />
      BLOCK_COMMENT<br />
   | OUTER_BLOCK_DOC<br />
   | INNER_BLOCK_DOC</p>
<p><em>IsolatedCR</em> :<br />
   <em>A <code>\r</code> not followed by a <code>\n</code></em></p>
</blockquote>
<a class="header" href="print.html#non-doc-comments" id="non-doc-comments"><h2>Non-doc comments</h2></a>
<p>Comments in Rust code follow the general C++ style of line (<code>//</code>) and
block (<code>/* ... */</code>) comment forms. Nested block comments are supported.</p>
<p>Non-doc comments are interpreted as a form of whitespace.</p>
<a class="header" href="print.html#doc-comments" id="doc-comments"><h2>Doc comments</h2></a>
<p>Line doc comments beginning with exactly <em>three</em> slashes (<code>///</code>), and block
doc comments (<code>/** ... */</code>), both inner doc comments, are interpreted as a
special syntax for <code>doc</code> <a href="attributes.html">attributes</a>. That is, they are equivalent to writing
<code>#[doc=&quot;...&quot;]</code> around the body of the comment, i.e., <code>/// Foo</code> turns into
<code>#[doc=&quot;Foo&quot;]</code> and <code>/** Bar */</code> turns into <code>#[doc=&quot;Bar&quot;]</code>.</p>
<p>Line comments beginning with <code>//!</code> and block comments <code>/*! ... */</code> are
doc comments that apply to the parent of the comment, rather than the item
that follows.  That is, they are equivalent to writing <code>#![doc=&quot;...&quot;]</code> around
the body of the comment. <code>//!</code> comments are usually used to document
modules that occupy a source file.</p>
<p>Isolated CRs (<code>\r</code>), i.e. not followed by LF (<code>\n</code>), are not allowed in doc
comments.</p>
<a class="header" href="print.html#examples" id="examples"><h2>Examples</h2></a>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
//! A doc comment that applies to the implicit anonymous module of this crate

pub mod outer_module {

    //!  - Inner line doc
    //!! - Still an inner line doc (but with a bang at the beginning)

    /*!  - Inner block doc */
    /*!! - Still an inner block doc (but with a bang at the beginning) */

    //   - Only a comment
    ///  - Outer line doc (exactly 3 slashes)
    //// - Only a comment

    /*   - Only a comment */
    /**  - Outer block doc (exactly) 2 asterisks */
    /*** - Only a comment */

    pub mod inner_module {}

    pub mod nested_comments {
        /* In Rust /* we can /* nest comments */ */ */

        // All three types of block comments can contain or be nested inside
        // any other type:

        /*   /* */  /** */  /*! */  */
        /*!  /* */  /** */  /*! */  */
        /**  /* */  /** */  /*! */  */
        pub mod dummy_item {}
    }

    pub mod degenerate_cases {
        // empty inner line doc
        //!
    
        // empty inner block doc
        /*!*/

        // empty line comment
        //
        
        // empty outer line doc
        ///
        
        // empty block comment
        /**/

        pub mod dummy_item {}

        // empty 2-asterisk block isn't a doc block, it is a block comment
        /***/

    }

    /* The next one isn't allowed because outer doc comments
       require an item that will receive the doc */

    /// Where is my item?
#   mod boo {}
}
#}</code></pre></pre>
<a class="header" href="print.html#whitespace" id="whitespace"><h1>Whitespace</h1></a>
<p>Whitespace is any non-empty string containing only characters that have the
<code>Pattern_White_Space</code> Unicode property, namely:</p>
<ul>
<li><code>U+0009</code> (horizontal tab, <code>'\t'</code>)</li>
<li><code>U+000A</code> (line feed, <code>'\n'</code>)</li>
<li><code>U+000B</code> (vertical tab)</li>
<li><code>U+000C</code> (form feed)</li>
<li><code>U+000D</code> (carriage return, <code>'\r'</code>)</li>
<li><code>U+0020</code> (space, <code>' '</code>)</li>
<li><code>U+0085</code> (next line)</li>
<li><code>U+200E</code> (left-to-right mark)</li>
<li><code>U+200F</code> (right-to-left mark)</li>
<li><code>U+2028</code> (line separator)</li>
<li><code>U+2029</code> (paragraph separator)</li>
</ul>
<p>Rust is a &quot;free-form&quot; language, meaning that all forms of whitespace serve only
to separate <em>tokens</em> in the grammar, and have no semantic significance.</p>
<p>A Rust program has identical meaning if each whitespace element is replaced
with any other legal whitespace element, such as a single space character.</p>
<a class="header" href="print.html#tokens" id="tokens"><h1>Tokens</h1></a>
<p>Tokens are primitive productions in the grammar defined by regular
(non-recursive) languages. &quot;Simple&quot; tokens are given in <a href="notation.html#string-table-productions">string table
production</a> form, and occur in the rest of the
grammar in <code>monospace</code> font. Other tokens have exact rules given.</p>
<a class="header" href="print.html#literals" id="literals"><h2>Literals</h2></a>
<p>A literal is an expression consisting of a single token, rather than a sequence
of tokens, that immediately and directly denotes the value it evaluates to,
rather than referring to it by name or some other evaluation rule. A literal is
a form of <a href="expressions.html#constant-expressions">constant expression</a>, so is
evaluated (primarily) at compile time.</p>
<a class="header" href="print.html#examples-1" id="examples-1"><h3>Examples</h3></a>
<a class="header" href="print.html#characters-and-strings" id="characters-and-strings"><h4>Characters and strings</h4></a>
<table><thead><tr><th>                                              </th><th> Example         </th><th> <code>#</code> sets   </th><th> Characters  </th><th> Escapes             </th></tr></thead><tbody>
<tr><td> <a href="print.html#character-literals">Character</a>             </td><td> <code>'H'</code>           </td><td> 0           </td><td> All Unicode </td><td> <a href="print.html#quote-escapes">Quote</a> &amp; <a href="print.html#ascii-escapes">ASCII</a> &amp; <a href="print.html#unicode-escapes">Unicode</a> </td></tr>
<tr><td> <a href="print.html#string-literals">String</a>                   </td><td> <code>&quot;hello&quot;</code>       </td><td> 0           </td><td> All Unicode </td><td> <a href="print.html#quote-escapes">Quote</a> &amp; <a href="print.html#ascii-escapes">ASCII</a> &amp; <a href="print.html#unicode-escapes">Unicode</a> </td></tr>
<tr><td> <a href="print.html#raw-string-literals">Raw</a>                  </td><td> <code>r#&quot;hello&quot;#</code>    </td><td> 0 or more* </td><td> All Unicode </td><td> <code>N/A</code>                                                      </td></tr>
<tr><td> <a href="print.html#byte-literals">Byte</a>                       </td><td> <code>b'H'</code>          </td><td> 0           </td><td> All ASCII   </td><td> <a href="print.html#quote-escapes">Quote</a> &amp; <a href="print.html#byte-escapes">Byte</a>                               </td></tr>
<tr><td> <a href="print.html#byte-string-literals">Byte string</a>         </td><td> <code>b&quot;hello&quot;</code>      </td><td> 0           </td><td> All ASCII   </td><td> <a href="print.html#quote-escapes">Quote</a> &amp; <a href="print.html#byte-escapes">Byte</a>                               </td></tr>
<tr><td> <a href="print.html#raw-byte-string-literals">Raw byte string</a> </td><td> <code>br#&quot;hello&quot;#</code>   </td><td> 0 or more* </td><td> All ASCII   </td><td> <code>N/A</code>                                                      </td></tr>
</tbody></table>
<p>* The number of <code>#</code>s on each side of the same literal must be equivalent</p>
<a class="header" href="print.html#ascii-escapes" id="ascii-escapes"><h4>ASCII escapes</h4></a>
<table><thead><tr><th>   </th><th> Name </th></tr></thead><tbody>
<tr><td> <code>\x41</code> </td><td> 7-bit character code (exactly 2 digits, up to 0x7F) </td></tr>
<tr><td> <code>\n</code> </td><td> Newline </td></tr>
<tr><td> <code>\r</code> </td><td> Carriage return </td></tr>
<tr><td> <code>\t</code> </td><td> Tab </td></tr>
<tr><td> <code>\\</code> </td><td> Backslash </td></tr>
<tr><td> <code>\0</code> </td><td> Null </td></tr>
</tbody></table>
<a class="header" href="print.html#byte-escapes" id="byte-escapes"><h4>Byte escapes</h4></a>
<table><thead><tr><th>   </th><th> Name </th></tr></thead><tbody>
<tr><td> <code>\x7F</code> </td><td> 8-bit character code (exactly 2 digits) </td></tr>
<tr><td> <code>\n</code> </td><td> Newline </td></tr>
<tr><td> <code>\r</code> </td><td> Carriage return </td></tr>
<tr><td> <code>\t</code> </td><td> Tab </td></tr>
<tr><td> <code>\\</code> </td><td> Backslash </td></tr>
<tr><td> <code>\0</code> </td><td> Null </td></tr>
</tbody></table>
<a class="header" href="print.html#unicode-escapes" id="unicode-escapes"><h4>Unicode escapes</h4></a>
<table><thead><tr><th>   </th><th> Name </th></tr></thead><tbody>
<tr><td> <code>\u{7FFF}</code> </td><td> 24-bit Unicode character code (up to 6 digits) </td></tr>
</tbody></table>
<a class="header" href="print.html#quote-escapes" id="quote-escapes"><h4>Quote escapes</h4></a>
<table><thead><tr><th>   </th><th> Name </th></tr></thead><tbody>
<tr><td> <code>\'</code> </td><td> Single quote </td></tr>
<tr><td> <code>\&quot;</code> </td><td> Double quote </td></tr>
</tbody></table>
<a class="header" href="print.html#numbers" id="numbers"><h4>Numbers</h4></a>
<table><thead><tr><th> <a href="print.html#number-literals">Number literals</a><code>*</code> </th><th> Example </th><th> Exponentiation </th><th> Suffixes </th></tr></thead><tbody>
<tr><td> Decimal integer </td><td> <code>98_222</code> </td><td> <code>N/A</code> </td><td> Integer suffixes </td></tr>
<tr><td> Hex integer </td><td> <code>0xff</code> </td><td> <code>N/A</code> </td><td> Integer suffixes </td></tr>
<tr><td> Octal integer </td><td> <code>0o77</code> </td><td> <code>N/A</code> </td><td> Integer suffixes </td></tr>
<tr><td> Binary integer </td><td> <code>0b1111_0000</code> </td><td> <code>N/A</code> </td><td> Integer suffixes </td></tr>
<tr><td> Floating-point </td><td> <code>123.0E+77</code> </td><td> <code>Optional</code> </td><td> Floating-point suffixes </td></tr>
</tbody></table>
<p><code>*</code> All number literals allow <code>_</code> as a visual separator: <code>1_234.0E+18f64</code></p>
<a class="header" href="print.html#suffixes" id="suffixes"><h4>Suffixes</h4></a>
<table><thead><tr><th> Integer </th><th> Floating-point </th></tr></thead><tbody>
<tr><td> <code>u8</code>, <code>i8</code>, <code>u16</code>, <code>i16</code>, <code>u32</code>, <code>i32</code>, <code>u64</code>, <code>i64</code>, <code>u128</code>, <code>i128</code>, <code>usize</code>, <code>isize</code> </td><td> <code>f32</code>, <code>f64</code> </td></tr>
</tbody></table>
<a class="header" href="print.html#character-and-string-literals" id="character-and-string-literals"><h3>Character and string literals</h3></a>
<a class="header" href="print.html#character-literals" id="character-literals"><h4>Character literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
CHAR_LITERAL :<br />
   <code>'</code> ( ~[<code>'</code> <code>\</code> \n \r \t] | QUOTE_ESCAPE | ASCII_ESCAPE | UNICODE_ESCAPE ) <code>'</code></p>
<p>QUOTE_ESCAPE :<br />
   <code>\'</code> | <code>\&quot;</code></p>
<p>ASCII_ESCAPE :<br />
      <code>\x</code> OCT_DIGIT HEX_DIGIT<br />
   | <code>\n</code> | <code>\r</code> | <code>\t</code> | <code>\\</code> | <code>\0</code></p>
<p>UNICODE_ESCAPE :<br />
   <code>\u{</code> ( HEX_DIGIT <code>_</code><sup>*</sup> )<sup>1..6</sup> <code>}</code></p>
</blockquote>
<p>A <em>character literal</em> is a single Unicode character enclosed within two
<code>U+0027</code> (single-quote) characters, with the exception of <code>U+0027</code> itself,
which must be <em>escaped</em> by a preceding <code>U+005C</code> character (<code>\</code>).</p>
<a class="header" href="print.html#string-literals" id="string-literals"><h4>String literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
STRING_LITERAL :<br />
   <code>&quot;</code> (<br />
      ~[<code>&quot;</code> <code>\</code> <em>IsolatedCR</em>]<br />
      | QUOTE_ESCAPE<br />
      | ASCII_ESCAPE<br />
      | UNICODE_ESCAPE<br />
      | STRING_CONTINUE<br />
   )<sup>*</sup> <code>&quot;</code></p>
<p>STRING_CONTINUE :<br />
   <code>\</code> <em>followed by</em> \n</p>
</blockquote>
<p>A <em>string literal</em> is a sequence of any Unicode characters enclosed within two
<code>U+0022</code> (double-quote) characters, with the exception of <code>U+0022</code> itself,
which must be <em>escaped</em> by a preceding <code>U+005C</code> character (<code>\</code>).</p>
<p>Line-break characters are allowed in string literals. Normally they represent
themselves (i.e. no translation), but as a special exception, when an unescaped
<code>U+005C</code> character (<code>\</code>) occurs immediately before the newline (<code>U+000A</code>), the
<code>U+005C</code> character, the newline, and all whitespace at the beginning of the
next line are ignored. Thus <code>a</code> and <code>b</code> are equal:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let a = &quot;foobar&quot;;
let b = &quot;foo\
         bar&quot;;

assert_eq!(a,b);
#}</code></pre></pre>
<a class="header" href="print.html#character-escapes" id="character-escapes"><h4>Character escapes</h4></a>
<p>Some additional <em>escapes</em> are available in either character or non-raw string
literals. An escape starts with a <code>U+005C</code> (<code>\</code>) and continues with one of the
following forms:</p>
<ul>
<li>A <em>7-bit code point escape</em> starts with <code>U+0078</code> (<code>x</code>) and is
followed by exactly two <em>hex digits</em> with value up to <code>0x7F</code>. It denotes the
ASCII character with value equal to the provided hex value. Higher values are
not permitted because it is ambiguous whether they mean Unicode code points or
byte values.</li>
<li>A <em>24-bit code point escape</em> starts with <code>U+0075</code> (<code>u</code>) and is followed
by up to six <em>hex digits</em> surrounded by braces <code>U+007B</code> (<code>{</code>) and <code>U+007D</code>
(<code>}</code>). It denotes the Unicode code point equal to the provided hex value.</li>
<li>A <em>whitespace escape</em> is one of the characters <code>U+006E</code> (<code>n</code>), <code>U+0072</code>
(<code>r</code>), or <code>U+0074</code> (<code>t</code>), denoting the Unicode values <code>U+000A</code> (LF),
<code>U+000D</code> (CR) or <code>U+0009</code> (HT) respectively.</li>
<li>The <em>null escape</em> is the character <code>U+0030</code> (<code>0</code>) and denotes the Unicode
value <code>U+0000</code> (NUL).</li>
<li>The <em>backslash escape</em> is the character <code>U+005C</code> (<code>\</code>) which must be
escaped in order to denote itself.</li>
</ul>
<a class="header" href="print.html#raw-string-literals" id="raw-string-literals"><h4>Raw string literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
RAW_STRING_LITERAL :<br />
   <code>r</code> RAW_STRING_CONTENT</p>
<p>RAW_STRING_CONTENT :<br />
      <code>&quot;</code> ( ~ <em>IsolatedCR</em> )<sup>* (non-greedy)</sup> <code>&quot;</code><br />
   | <code>#</code> RAW_STRING_CONTENT <code>#</code></p>
</blockquote>
<p>Raw string literals do not process any escapes. They start with the character
<code>U+0072</code> (<code>r</code>), followed by zero or more of the character <code>U+0023</code> (<code>#</code>) and a
<code>U+0022</code> (double-quote) character. The <em>raw string body</em> can contain any sequence
of Unicode characters and is terminated only by another <code>U+0022</code> (double-quote)
character, followed by the same number of <code>U+0023</code> (<code>#</code>) characters that preceded
the opening <code>U+0022</code> (double-quote) character.</p>
<p>All Unicode characters contained in the raw string body represent themselves,
the characters <code>U+0022</code> (double-quote) (except when followed by at least as
many <code>U+0023</code> (<code>#</code>) characters as were used to start the raw string literal) or
<code>U+005C</code> (<code>\</code>) do not have any special meaning.</p>
<p>Examples for string literals:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
&quot;foo&quot;; r&quot;foo&quot;;                     // foo
&quot;\&quot;foo\&quot;&quot;; r#&quot;&quot;foo&quot;&quot;#;             // &quot;foo&quot;

&quot;foo #\&quot;# bar&quot;;
r##&quot;foo #&quot;# bar&quot;##;                // foo #&quot;# bar

&quot;\x52&quot;; &quot;R&quot;; r&quot;R&quot;;                 // R
&quot;\\x52&quot;; r&quot;\x52&quot;;                  // \x52
#}</code></pre></pre>
<a class="header" href="print.html#byte-and-byte-string-literals" id="byte-and-byte-string-literals"><h3>Byte and byte string literals</h3></a>
<a class="header" href="print.html#byte-literals" id="byte-literals"><h4>Byte literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
BYTE_LITERAL :<br />
   <code>b'</code> ( ASCII_FOR_CHAR | BYTE_ESCAPE )  <code>'</code></p>
<p>ASCII_FOR_CHAR :<br />
   <em>any ASCII (i.e. 0x00 to 0x7F), except</em> <code>'</code>, <code>\</code>, \n, \r or \t</p>
<p>BYTE_ESCAPE :<br />
      <code>\x</code> HEX_DIGIT HEX_DIGIT<br />
   | <code>\n</code> | <code>\r</code> | <code>\t</code> | <code>\\</code> | <code>\0</code></p>
</blockquote>
<p>A <em>byte literal</em> is a single ASCII character (in the <code>U+0000</code> to <code>U+007F</code>
range) or a single <em>escape</em> preceded by the characters <code>U+0062</code> (<code>b</code>) and
<code>U+0027</code> (single-quote), and followed by the character <code>U+0027</code>. If the character
<code>U+0027</code> is present within the literal, it must be <em>escaped</em> by a preceding
<code>U+005C</code> (<code>\</code>) character. It is equivalent to a <code>u8</code> unsigned 8-bit integer
<em>number literal</em>.</p>
<a class="header" href="print.html#byte-string-literals" id="byte-string-literals"><h4>Byte string literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
BYTE_STRING_LITERAL :<br />
   <code>b&quot;</code> ( ASCII_FOR_STRING | BYTE_ESCAPE | STRING_CONTINUE )<sup>*</sup> <code>&quot;</code></p>
<p>ASCII_FOR_STRING :<br />
   <em>any ASCII (i.e 0x00 to 0x7F), except</em> <code>&quot;</code>, <code>\</code> <em>and IsolatedCR</em></p>
</blockquote>
<p>A non-raw <em>byte string literal</em> is a sequence of ASCII characters and <em>escapes</em>,
preceded by the characters <code>U+0062</code> (<code>b</code>) and <code>U+0022</code> (double-quote), and
followed by the character <code>U+0022</code>. If the character <code>U+0022</code> is present within
the literal, it must be <em>escaped</em> by a preceding <code>U+005C</code> (<code>\</code>) character.
Alternatively, a byte string literal can be a <em>raw byte string literal</em>, defined
below. The type of a byte string literal of length <code>n</code> is <code>&amp;'static [u8; n]</code>.</p>
<p>Some additional <em>escapes</em> are available in either byte or non-raw byte string
literals. An escape starts with a <code>U+005C</code> (<code>\</code>) and continues with one of the
following forms:</p>
<ul>
<li>A <em>byte escape</em> escape starts with <code>U+0078</code> (<code>x</code>) and is
followed by exactly two <em>hex digits</em>. It denotes the byte
equal to the provided hex value.</li>
<li>A <em>whitespace escape</em> is one of the characters <code>U+006E</code> (<code>n</code>), <code>U+0072</code>
(<code>r</code>), or <code>U+0074</code> (<code>t</code>), denoting the bytes values <code>0x0A</code> (ASCII LF),
<code>0x0D</code> (ASCII CR) or <code>0x09</code> (ASCII HT) respectively.</li>
<li>The <em>null escape</em> is the character <code>U+0030</code> (<code>0</code>) and denotes the byte
value <code>0x00</code> (ASCII NUL).</li>
<li>The <em>backslash escape</em> is the character <code>U+005C</code> (<code>\</code>) which must be
escaped in order to denote its ASCII encoding <code>0x5C</code>.</li>
</ul>
<a class="header" href="print.html#raw-byte-string-literals" id="raw-byte-string-literals"><h4>Raw byte string literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
RAW_BYTE_STRING_LITERAL :<br />
   <code>br</code> RAW_BYTE_STRING_CONTENT</p>
<p>RAW_BYTE_STRING_CONTENT :<br />
      <code>&quot;</code> ASCII<sup>* (non-greedy)</sup> <code>&quot;</code><br />
   | <code>#</code> RAW_STRING_CONTENT <code>#</code></p>
<p>ASCII :<br />
   <em>any ASCII (i.e. 0x00 to 0x7F)</em></p>
</blockquote>
<p>Raw byte string literals do not process any escapes. They start with the
character <code>U+0062</code> (<code>b</code>), followed by <code>U+0072</code> (<code>r</code>), followed by zero or more
of the character <code>U+0023</code> (<code>#</code>), and a <code>U+0022</code> (double-quote) character. The
<em>raw string body</em> can contain any sequence of ASCII characters and is terminated
only by another <code>U+0022</code> (double-quote) character, followed by the same number of
<code>U+0023</code> (<code>#</code>) characters that preceded the opening <code>U+0022</code> (double-quote)
character. A raw byte string literal can not contain any non-ASCII byte.</p>
<p>All characters contained in the raw string body represent their ASCII encoding,
the characters <code>U+0022</code> (double-quote) (except when followed by at least as
many <code>U+0023</code> (<code>#</code>) characters as were used to start the raw string literal) or
<code>U+005C</code> (<code>\</code>) do not have any special meaning.</p>
<p>Examples for byte string literals:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
b&quot;foo&quot;; br&quot;foo&quot;;                     // foo
b&quot;\&quot;foo\&quot;&quot;; br#&quot;&quot;foo&quot;&quot;#;             // &quot;foo&quot;

b&quot;foo #\&quot;# bar&quot;;
br##&quot;foo #&quot;# bar&quot;##;                 // foo #&quot;# bar

b&quot;\x52&quot;; b&quot;R&quot;; br&quot;R&quot;;                // R
b&quot;\\x52&quot;; br&quot;\x52&quot;;                  // \x52
#}</code></pre></pre>
<a class="header" href="print.html#number-literals" id="number-literals"><h3>Number literals</h3></a>
<p>A <em>number literal</em> is either an <em>integer literal</em> or a <em>floating-point
literal</em>. The grammar for recognizing the two kinds of literals is mixed.</p>
<a class="header" href="print.html#integer-literals" id="integer-literals"><h4>Integer literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
INTEGER_LITERAL :<br />
   ( DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL )
INTEGER_SUFFIX<sup>?</sup></p>
<p>DEC_LITERAL :<br />
   DEC_DIGIT (DEC_DIGIT|<code>_</code>)<sup>*</sup></p>
<p>TUPLE_INDEX :<br />
      <code>0</code>
   | NON_ZERO_DEC_DIGIT DEC_DIGIT<sup>*</sup></p>
<p>BIN_LITERAL :<br />
   <code>0b</code> (BIN_DIGIT|<code>_</code>)<sup>*</sup> BIN_DIGIT (BIN_DIGIT|<code>_</code>)<sup>*</sup></p>
<p>OCT_LITERAL :<br />
   <code>0o</code> (OCT_DIGIT|<code>_</code>)<sup>*</sup> OCT_DIGIT (OCT_DIGIT|<code>_</code>)<sup>*</sup></p>
<p>HEX_LITERAL :<br />
   <code>0x</code> (HEX_DIGIT|<code>_</code>)<sup>*</sup> HEX_DIGIT (HEX_DIGIT|<code>_</code>)<sup>*</sup></p>
<p>BIN_DIGIT : [<code>0</code>-<code>1</code>]</p>
<p>OCT_DIGIT : [<code>0</code>-<code>7</code>]</p>
<p>DEC_DIGIT : [<code>0</code>-<code>9</code>]</p>
<p>NON_ZERO_DEC_DIGIT : [<code>1</code>-<code>9</code>]</p>
<p>HEX_DIGIT : [<code>0</code>-<code>9</code> <code>a</code>-<code>f</code> <code>A</code>-<code>F</code>]</p>
<p>INTEGER_SUFFIX :<br />
      <code>u8</code> | <code>u16</code> | <code>u32</code> | <code>u64</code> | <code>u128</code> | <code>usize</code><br />
   | <code>i8</code> | <code>i16</code> | <code>i32</code> | <code>i64</code> | <code>i128</code> | <code>isize</code></p>
</blockquote>
<p>An <em>integer literal</em> has one of four forms:</p>
<ul>
<li>A <em>decimal literal</em> starts with a <em>decimal digit</em> and continues with any
mixture of <em>decimal digits</em> and <em>underscores</em>.</li>
<li>A <em>tuple index</em> is either <code>0</code>, or starts with a <em>non-zero decimal digit</em> and
continues with zero or more decimal digits. Tuple indexes are used to refer
to the fields of <a href="types.html#tuple-types">tuples</a>, <a href="items/structs.html">tuple structs</a> and <a href="items/enumerations.html">tuple variants</a>.</li>
<li>A <em>hex literal</em> starts with the character sequence <code>U+0030</code> <code>U+0078</code>
(<code>0x</code>) and continues as any mixture (with at least one digit) of hex digits
and underscores.</li>
<li>An <em>octal literal</em> starts with the character sequence <code>U+0030</code> <code>U+006F</code>
(<code>0o</code>) and continues as any mixture (with at least one digit) of octal digits
and underscores.</li>
<li>A <em>binary literal</em> starts with the character sequence <code>U+0030</code> <code>U+0062</code>
(<code>0b</code>) and continues as any mixture (with at least one digit) of binary digits
and underscores.</li>
</ul>
<p>Like any literal, an integer literal may be followed (immediately,
without any spaces) by an <em>integer suffix</em>, which forcibly sets the
type of the literal. The integer suffix must be the name of one of the
integral types: <code>u8</code>, <code>i8</code>, <code>u16</code>, <code>i16</code>, <code>u32</code>, <code>i32</code>, <code>u64</code>, <code>i64</code>,
<code>u128</code>, <code>i128</code>, <code>usize</code>, or <code>isize</code>.</p>
<p>The type of an <em>unsuffixed</em> integer literal is determined by type inference:</p>
<ul>
<li>
<p>If an integer type can be <em>uniquely</em> determined from the surrounding
program context, the unsuffixed integer literal has that type.</p>
</li>
<li>
<p>If the program context under-constrains the type, it defaults to the
signed 32-bit integer <code>i32</code>.</p>
</li>
<li>
<p>If the program context over-constrains the type, it is considered a
static type error.</p>
</li>
</ul>
<p>Examples of integer literals of various forms:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
123;                               // type i32
123i32;                            // type i32
123u32;                            // type u32
123_u32;                           // type u32
let a: u64 = 123;                  // type u64

0xff;                              // type i32
0xff_u8;                           // type u8

0o70;                              // type i32
0o70_i16;                          // type i16

0b1111_1111_1001_0000;             // type i32
0b1111_1111_1001_0000i64;          // type i64
0b________1;                       // type i32

0usize;                            // type usize
#}</code></pre></pre>
<p>Examples of invalid integer literals:</p>
<pre><code class="language-rust ignore">// invalid suffixes

0invalidSuffix;

// uses numbers of the wrong base

123AFB43;
0b0102;
0o0581;

// integers too big for their type (they overflow)

128_i8;
256_u8;

// bin, hex and octal literals must have at least one digit

0b_;
0b____;
</code></pre>
<p>Note that the Rust syntax considers <code>-1i8</code> as an application of the <a href="expressions/operator-expr.html#negation-operators">unary minus
operator</a> to an integer literal <code>1i8</code>, rather than
a single integer literal.</p>
<a class="header" href="print.html#floating-point-literals" id="floating-point-literals"><h4>Floating-point literals</h4></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
FLOAT_LITERAL :<br />
      DEC_LITERAL <code>.</code>
<em>(not immediately followed by <code>.</code>, <code>_</code> or an <a href="identifiers.html">identifier</a></em>)<br />
   | DEC_LITERAL FLOAT_EXPONENT<br />
   | DEC_LITERAL <code>.</code> DEC_LITERAL FLOAT_EXPONENT<sup>?</sup><br />
   | DEC_LITERAL (<code>.</code> DEC_LITERAL)<sup>?</sup>
FLOAT_EXPONENT<sup>?</sup> FLOAT_SUFFIX</p>
<p>FLOAT_EXPONENT :<br />
   (<code>e</code>|<code>E</code>) (<code>+</code>|<code>-</code>)?
(DEC_DIGIT|<code>_</code>)<sup>*</sup> DEC_DIGIT (DEC_DIGIT|<code>_</code>)<sup>*</sup></p>
<p>FLOAT_SUFFIX :<br />
   <code>f32</code> | <code>f64</code></p>
</blockquote>
<p>A <em>floating-point literal</em> has one of two forms:</p>
<ul>
<li>A <em>decimal literal</em> followed by a period character <code>U+002E</code> (<code>.</code>). This is
optionally followed by another decimal literal, with an optional <em>exponent</em>.</li>
<li>A single <em>decimal literal</em> followed by an <em>exponent</em>.</li>
</ul>
<p>Like integer literals, a floating-point literal may be followed by a
suffix, so long as the pre-suffix part does not end with <code>U+002E</code> (<code>.</code>).
The suffix forcibly sets the type of the literal. There are two valid
<em>floating-point suffixes</em>, <code>f32</code> and <code>f64</code> (the 32-bit and 64-bit floating point
types), which explicitly determine the type of the literal.</p>
<p>The type of an <em>unsuffixed</em> floating-point literal is determined by
type inference:</p>
<ul>
<li>
<p>If a floating-point type can be <em>uniquely</em> determined from the
surrounding program context, the unsuffixed floating-point literal
has that type.</p>
</li>
<li>
<p>If the program context under-constrains the type, it defaults to <code>f64</code>.</p>
</li>
<li>
<p>If the program context over-constrains the type, it is considered a
static type error.</p>
</li>
</ul>
<p>Examples of floating-point literals of various forms:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
123.0f64;        // type f64
0.1f64;          // type f64
0.1f32;          // type f32
12E+99_f64;      // type f64
let x: f64 = 2.; // type f64
#}</code></pre></pre>
<p>This last example is different because it is not possible to use the suffix
syntax with a floating point literal ending in a period. <code>2.f64</code> would attempt
to call a method named <code>f64</code> on <code>2</code>.</p>
<p>The representation semantics of floating-point numbers are described in
<a href="types.html#machine-types">&quot;Machine Types&quot;</a>.</p>
<a class="header" href="print.html#boolean-literals" id="boolean-literals"><h3>Boolean literals</h3></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
BOOLEAN_LITERAL :<br />
      <code>true</code><br />
   | <code>false</code></p>
</blockquote>
<p>The two values of the boolean type are written <code>true</code> and <code>false</code>.</p>
<a class="header" href="print.html#lifetimes-and-loop-labels" id="lifetimes-and-loop-labels"><h2>Lifetimes and loop labels</h2></a>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
LIFETIME_TOKEN :<br />
      <code>'</code> <a href="identifiers.html">IDENTIFIER_OR_KEYWORD</a><br />
   | <code>'_</code></p>
<p>LIFETIME_OR_LABEL :<br />
      <code>'</code> <a href="identifiers.html">IDENTIFIER</a></p>
</blockquote>
<p>Lifetime parameters and <a href="expressions/loop-expr.html">loop labels</a> use LIFETIME_OR_LABEL tokens. Any
LIFETIME_TOKEN will be accepted by the lexer, and for example, can be used in
macros.</p>
<a class="header" href="print.html#symbols" id="symbols"><h2>Symbols</h2></a>
<p>Symbols are a general class of printable <a href="print.html#tokens">tokens</a> that play structural
roles in a variety of grammar productions. They are a
set of remaining miscellaneous printable tokens that do not
otherwise appear as <a href="expressions/operator-expr.html#borrow-operators">unary operators</a>, <a href="expressions/operator-expr.html#arithmetic-and-logical-binary-operators">binary
operators</a>, or <a href="keywords.html">keywords</a>.
They are catalogued in <a href="../grammar.html#symbols">the Symbols section</a> of the Grammar document.</p>
<a class="header" href="print.html#paths" id="paths"><h1>Paths</h1></a>
<p>A <em>path</em> is a sequence of one or more path components <em>logically</em> separated by
a namespace <span class="parenthetical">qualifier (<code>::</code>)</span>. If a path
consists of only one component, it refers to either an <a href="items.html">item</a> or a <a href="variables.html">variable</a> in
a local control scope. If a path has multiple components, it always refers to an
item.</p>
<p>Two examples of simple paths consisting of only identifier components:</p>
<pre><code class="language-rust ignore">x;
x::y::z;
</code></pre>
<p>Path components are usually <a href="identifiers.html">identifiers</a>, but they may also include
angle-bracket-enclosed lists of type arguments. In <a href="expressions.html">expression</a> context, the
type argument list is given after a <code>::</code> namespace qualifier in order to
disambiguate it from a relational expression involving the less-than
<span class="parenthetical">symbol (<code>&lt;</code>)</span>. In type expression context, the
final namespace qualifier is omitted.</p>
<p>Two examples of paths with type arguments:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct HashMap&lt;K, V&gt;(K,V);
# fn f() {
# fn id&lt;T&gt;(t: T) -&gt; T { t }
type T = HashMap&lt;i32,String&gt;; // Type arguments used in a type expression
let x  = id::&lt;i32&gt;(10);       // Type arguments used in a call expression
# }
#}</code></pre></pre>
<p>Paths can be denoted with various leading qualifiers to change the meaning of
how it is resolved:</p>
<ul>
<li>Paths starting with <code>::</code> are considered to be global paths where the
components of the path start being resolved from the crate root. Each
identifier in the path must resolve to an item.</li>
</ul>
<pre><pre class="playpen"><code class="language-rust">mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        ::a::foo(); // call a's foo function
    }
}
# fn main() {}
</code></pre></pre>
<ul>
<li>Paths starting with the keyword <code>super</code> begin resolution relative to the
parent module. Each further identifier must resolve to an item.</li>
</ul>
<pre><pre class="playpen"><code class="language-rust">mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        super::a::foo(); // call a's foo function
    }
}
# fn main() {}
</code></pre></pre>
<ul>
<li>Paths starting with the keyword <code>self</code> begin resolution relative to the
current module. Each further identifier must resolve to an item.</li>
</ul>
<pre><pre class="playpen"><code class="language-rust">fn foo() {}
fn bar() {
    self::foo();
}
# fn main() {}
</code></pre></pre>
<p>Additionally keyword <code>super</code> may be repeated several times after the first
<code>super</code> or <code>self</code> to refer to ancestor modules.</p>
<pre><pre class="playpen"><code class="language-rust">mod a {
    fn foo() {}

    mod b {
        mod c {
            fn foo() {
                super::super::foo(); // call a's foo function
                self::super::super::foo(); // call a's foo function
            }
        }
    }
}
# fn main() {}
</code></pre></pre>
<a class="header" href="print.html#canonical-paths" id="canonical-paths"><h2>Canonical paths</h2></a>
<p>Items defined in a module or implementation have a <em>canonical path</em> that
corresponds to where within its crate it is defined. All other paths to these
items are aliases. The canonical path is defined as a <em>path prefix</em> appended by
the path component the item itself defines.</p>
<p><a href="items/implementations.html">Implementations</a> and <a href="items/use-declarations.html">use declarations</a> do not have canonical paths, although
the items that implementations define do have them. Items defined in
block expressions do not have canonical paths. Items defined in a module that
does not have a canonical path do not have a canonical path. Associated items
defined in an implementation that refers to an item without a canonical path,
e.g. as the implementing type, the trait being implemented, a type parameter or
bound on a type parameter, do not have canonical paths.</p>
<p>The path prefix for modules is the canonical path to that module. For bare
implementations, it is the canonical path of the item being implemented
surrounded by <span class="parenthetical">angle (<code>&lt;&gt;</code>)</span> brackets. For
trait implementations, it is the canonical path of the item being implemented
followed by <code>as</code> followed by the canonical path to the trait all surrounded in
<span class="parenthetical">angle (<code>&lt;&gt;</code>)</span> brackets.</p>
<p>The canonical path is only meaningful within a given crate. There is no global
namespace across crates; an item's canonical path merely identifies it within
the crate.</p>
<pre><pre class="playpen"><code class="language-rust">// Comments show the canonical path of the item.

mod a { // ::a
    pub struct Struct; // ::a::Struct

    pub trait Trait { // ::a::Trait
        fn f(&amp;self); // a::Trait::f
    }

    impl Trait for Struct {
        fn f(&amp;self) {} // &lt;::a::Struct as ::a::Trait&gt;::f
    }

    impl Struct {
        fn g(&amp;self) {} // &lt;::a::Struct&gt;::g
    }
}

mod without { // ::without
    fn canonicals() { // ::without::canonicals
        struct OtherStruct; // None

        trait OtherTrait { // None
            fn g(&amp;self); // None
        }

        impl OtherTrait for OtherStruct {
            fn g(&amp;self) {} // None
        }

        impl OtherTrait for ::a::Struct {
            fn g(&amp;self) {} // None
        }

        impl ::a::Trait for OtherStruct {
            fn f(&amp;self) {} // None
        }
    }
}

# fn main() {}
</code></pre></pre>
<a class="header" href="print.html#macros" id="macros"><h1>Macros</h1></a>
<p>A number of minor features of Rust are not central enough to have their own
syntax, and yet are not implementable as functions. Instead, they are given
names, and invoked through a consistent syntax: <code>some_extension!(...)</code>.</p>
<p>There are two ways to define new macros:</p>
<ul>
<li><a href="macros-by-example.html">Macros by Example</a> define new syntax in a higher-level, declarative way.</li>
<li><a href="procedural-macros.html">Procedural Macros</a> can be used to implement custom derive.</li>
</ul>
<a class="header" href="print.html#macros-by-example" id="macros-by-example"><h1>Macros By Example</h1></a>
<p><code>macro_rules</code> allows users to define syntax extension in a declarative way.  We
call such extensions &quot;macros by example&quot; or simply &quot;macros&quot;.</p>
<p>Currently, macros can expand to expressions, statements, items, or patterns.</p>
<p>(A <code>sep_token</code> is any token other than <code>*</code> and <code>+</code>. A <code>non_special_token</code> is
any token other than a delimiter or <code>$</code>.)</p>
<p>The macro expander looks up macro invocations by name, and tries each macro
rule in turn. It transcribes the first successful match. Matching and
transcription are closely related to each other, and we will describe them
together.</p>
<p>The macro expander matches and transcribes every token that does not begin with
a <code>$</code> literally, including delimiters. For parsing reasons, delimiters must be
balanced, but they are otherwise not special.</p>
<p>In the matcher, <code>$</code> <em>name</em> <code>:</code> <em>designator</em> matches the nonterminal in the Rust
syntax named by <em>designator</em>. Valid designators are:</p>
<ul>
<li><code>item</code>: an <a href="items.html">item</a></li>
<li><code>block</code>: a <a href="expressions/block-expr.html">block</a></li>
<li><code>stmt</code>: a <a href="statements.html">statement</a></li>
<li><code>pat</code>: a <a href="expressions/match-expr.html">pattern</a></li>
<li><code>expr</code>: an <a href="expressions.html">expression</a></li>
<li><code>ty</code>: a <a href="types.html">type</a></li>
<li><code>ident</code>: an <a href="identifiers.html">identifier</a> or <a href="keywords.html">keyword</a></li>
<li><code>path</code>: a <a href="paths.html">path</a></li>
<li><code>tt</code>: a token tree (a single <a href="tokens.html">token</a> by matching <code>()</code>, <code>[]</code>, or <code>{}</code>)</li>
<li><code>meta</code>: the contents of an <a href="attributes.html">attribute</a></li>
<li><code>lifetime</code>: a lifetime. Examples: <code>'static</code>, <code>'a</code>.</li>
</ul>
<p>In the transcriber, the
designator is already known, and so only the name of a matched nonterminal comes
after the dollar sign.</p>
<p>In both the matcher and transcriber, the Kleene star-like operator indicates
repetition. The Kleene star operator consists of <code>$</code> and parentheses, optionally
followed by a separator token, followed by <code>*</code> or <code>+</code>. <code>*</code> means zero or more
repetitions, <code>+</code> means at least one repetition. The parentheses are not matched or
transcribed. On the matcher side, a name is bound to <em>all</em> of the names it
matches, in a structure that mimics the structure of the repetition encountered
on a successful match. The job of the transcriber is to sort that structure
out.</p>
<p>The rules for transcription of these repetitions are called &quot;Macro By Example&quot;.
Essentially, one &quot;layer&quot; of repetition is discharged at a time, and all of them
must be discharged by the time a name is transcribed. Therefore, <code>( $( $i:ident ),* ) =&gt; ( $i )</code> is an invalid macro, but <code>( $( $i:ident ),* ) =&gt; ( $( $i:ident ),* )</code> is acceptable (if trivial).</p>
<p>When Macro By Example encounters a repetition, it examines all of the <code>$</code>
<em>name</em> s that occur in its body. At the &quot;current layer&quot;, they all must repeat
the same number of times, so <code>( $( $i:ident ),* ; $( $j:ident ),* ) =&gt; ( $( ($i,$j) ),* )</code> is valid if given the argument <code>(a,b,c ; d,e,f)</code>, but not
<code>(a,b,c ; d,e)</code>. The repetition walks through the choices at that layer in
lockstep, so the former input transcribes to <code>(a,d), (b,e), (c,f)</code>.</p>
<p>Nested repetitions are allowed.</p>
<a class="header" href="print.html#parsing-limitations" id="parsing-limitations"><h3>Parsing limitations</h3></a>
<p>The parser used by the macro system is reasonably powerful, but the parsing of
Rust syntax is restricted in two ways:</p>
<ol>
<li>Macro definitions are required to include suitable separators after parsing
expressions and other bits of the Rust grammar. This implies that
a macro definition like <code>$i:expr [ , ]</code> is not legal, because <code>[</code> could be part
of an expression. A macro definition like <code>$i:expr,</code> or <code>$i:expr;</code> would be legal,
however, because <code>,</code> and <code>;</code> are legal separators. See <a href="https://github.com/rust-lang/rfcs/blob/master/text/0550-macro-future-proofing.md">RFC 550</a> for more information.</li>
<li>The parser must have eliminated all ambiguity by the time it reaches a <code>$</code>
<em>name</em> <code>:</code> <em>designator</em>. This requirement most often affects name-designator
pairs when they occur at the beginning of, or immediately after, a <code>$(...)*</code>;
requiring a distinctive token in front can solve the problem.</li>
</ol>
<a class="header" href="print.html#procedural-macros" id="procedural-macros"><h2>Procedural Macros</h2></a>
<p><em>Procedural macros</em> allow creating syntax extensions as execution of a function.
Procedural macros can be used to implement custom <a href="attributes.html#derive">derive</a> on your own
types. See <a href="../book/first-edition/procedural-macros.html">the book</a> for a tutorial.</p>
<p>Procedural macros involve a few different parts of the language and its
standard libraries. First is the <code>proc_macro</code> crate, included with Rust,
that defines an interface for building a procedural macro. The
<code>#[proc_macro_derive(Foo)]</code> attribute is used to mark the deriving
function. This function must have the type signature:</p>
<pre><code class="language-rust ignore">use proc_macro::TokenStream;

#[proc_macro_derive(Hello)]
pub fn hello_world(input: TokenStream) -&gt; TokenStream
</code></pre>
<p>Finally, procedural macros must be in their own crate, with the <code>proc-macro</code>
crate type.</p>
<a class="header" href="print.html#crates-and-source-files" id="crates-and-source-files"><h1>Crates and source files</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Crate</em> :<br />
   UTF8BOM<sup>?</sup><br />
   SHEBANG<sup>?</sup><br />
   <a href="attributes.html"><em>InnerAttribute</em></a><sup>*</sup><br />
   <a href="items.html"><em>Item</em></a><sup>*</sup></p>
</blockquote>
<blockquote>
<p><strong><sup>Lexer</sup></strong><br />
UTF8BOM : <code>\uFEFF</code><br />
SHEBANG : <code>#!</code> ~[<code>[</code> <code>\n</code>] ~<code>\n</code><sup>*</sup></p>
</blockquote>
<blockquote>
<p>Note: Although Rust, like any other language, can be implemented by an
interpreter as well as a compiler, the only existing implementation is a
compiler,and the language has always been designed to be compiled. For these
reasons, this section assumes a compiler.</p>
</blockquote>
<p>Rust's semantics obey a <em>phase distinction</em> between compile-time and
run-time.<sup class="footnote-reference"><a href="print.html#phase-distinction">1</a></sup> Semantic rules that have a <em>static
interpretation</em> govern the success or failure of compilation, while
semantic rules
that have a <em>dynamic interpretation</em> govern the behavior of the program at
run-time.</p>
<p>The compilation model centers on artifacts called <em>crates</em>. Each compilation
processes a single crate in source form, and if successful, produces a single
crate in binary form: either an executable or some sort of
library.<sup class="footnote-reference"><a href="print.html#cratesourcefile">2</a></sup></p>
<p>A <em>crate</em> is a unit of compilation and linking, as well as versioning,
distribution and runtime loading. A crate contains a <em>tree</em> of nested
<a href="items/modules.html">module</a> scopes. The top level of this tree is a module that is
anonymous (from the point of view of paths within the module) and any item
within a crate has a canonical <a href="paths.html">module path</a> denoting its location
within the crate's module tree.</p>
<p>The Rust compiler is always invoked with a single source file as input, and
always produces a single output crate. The processing of that source file may
result in other source files being loaded as modules. Source files have the
extension <code>.rs</code>.</p>
<p>A Rust source file describes a module, the name and location of which —
in the module tree of the current crate — are defined from outside the
source file: either by an explicit <code>mod_item</code> in a referencing source file, or
by the name of the crate itself. Every source file is a module, but not every
module needs its own source file: <a href="items/modules.html">module definitions</a> can be nested
within one file.</p>
<p>Each source file contains a sequence of zero or more <code>item</code> definitions, and
may optionally begin with any number of <a href="attributes.html">attributes</a>
that apply to the containing module, most of which influence the behavior of
the compiler. The anonymous crate module can have additional attributes that
apply to the crate as a whole.</p>
<pre><pre class="playpen"><code class="language-rust no_run">
# #![allow(unused_variables)]
#fn main() {
// Specify the crate name.
#![crate_name = &quot;projx&quot;]

// Specify the type of output artifact.
#![crate_type = &quot;lib&quot;]

// Turn on a warning.
// This can be done in any module, not just the anonymous crate module.
#![warn(non_camel_case_types)]
#}</code></pre></pre>
<p>A crate that contains a <code>main</code> <a href="items/functions.html">function</a> can be compiled to an executable. If a
<code>main</code> function is present, it must take no arguments, must not declare any
<a href="trait-bounds.html">trait or lifetime bounds</a>, must not have any [where clauses], and  its return
type must  be one of the following:</p>
<ul>
<li><code>()</code></li>
</ul>
<!-- * `!` -->
* `Result<T, E> where T: on this list, E: Error`
<blockquote>
<p>Note: The implementation of which return types are allowed is determined by
the unstable <a href="../std/process/trait.Termination.html"><code>Termination</code></a> trait.</p>
</blockquote>
<p>The optional <a href="https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8"><em>UTF8 byte order mark</em></a> (UTF8BOM production) indicates that the
file is encoded in UTF8. It can only occur at the beginning of the file and
is ignored by the compiler.</p>
<p>A source file can have a <a href="https://en.wikipedia.org/wiki/Shebang_(Unix)"><em>shebang</em></a> (SHEBANG production), which indicates
to the operating system what program to use to execute this file. It serves
essentially to treat the source file as an executable script. The shebang
can only occur at the beginning of the file (but after the optional
<em>UTF8BOM</em>). It is ignored by the compiler. For example:</p>
<pre><code class="language-text ignore">#!/usr/bin/env rustx

fn main() {
    println!(&quot;Hello!&quot;);
}
</code></pre>
<div class="footnote-definition" id="phase-distinction"><sup class="footnote-definition-label">1</sup>
<p>This distinction would also exist in an interpreter.
Static checks like syntactic analysis, type checking, and lints should
happen before the program is executed regardless of when it is executed.</p>
</div>
<div class="footnote-definition" id="cratesourcefile"><sup class="footnote-definition-label">2</sup>
<p>A crate is somewhat analogous to an <em>assembly</em> in the
ECMA-335 CLI model, a <em>library</em> in the SML/NJ Compilation Manager, a <em>unit</em>
in the Owens and Flatt module system, or a <em>configuration</em> in Mesa.</p>
</div>
<a class="header" href="print.html#items-and-attributes" id="items-and-attributes"><h1>Items and attributes</h1></a>
<p>Crates contain <a href="items.html">items</a>, each of which may have some number of
<a href="attributes.html">attributes</a> attached to it.</p>
<a class="header" href="print.html#items" id="items"><h1>Items</h1></a>
<p>An <em>item</em> is a component of a crate. Items are organized within a crate by a
nested set of <a href="items/modules.html">modules</a>. Every crate has a single &quot;outermost&quot; anonymous module;
all further items within the crate have <a href="paths.html">paths</a> within the module tree of the
crate.</p>
<p>Items are entirely determined at compile-time, generally remain fixed during
execution, and may reside in read-only memory.</p>
<p>There are several kinds of items:</p>
<ul>
<li><a href="items/modules.html">modules</a></li>
<li><a href="items/extern-crates.html"><code>extern crate</code> declarations</a></li>
<li><a href="items/use-declarations.html"><code>use</code> declarations</a></li>
<li><a href="items/functions.html">function definitions</a></li>
<li><a href="items/type-aliases.html">type definitions</a></li>
<li><a href="items/structs.html">struct definitions</a></li>
<li><a href="items/enumerations.html">enumeration definitions</a></li>
<li><a href="items/unions.html">union definitions</a></li>
<li><a href="items/constant-items.html">constant items</a></li>
<li><a href="items/static-items.html">static items</a></li>
<li><a href="items/traits.html">trait definitions</a></li>
<li><a href="items/implementations.html">implementations</a></li>
<li><a href="items/external-blocks.html"><code>extern</code> blocks</a></li>
</ul>
<p>Some items form an implicit scope for the declaration of sub-items. In other
words, within a function or module, declarations of items can (in many cases)
be mixed with the statements, control blocks, and similar artifacts that
otherwise compose the item body. The meaning of these scoped items is the same
as if the item was declared outside the scope — it is still a static item
— except that the item's <em>path name</em> within the module namespace is
qualified by the name of the enclosing item, or is private to the enclosing
item (in the case of functions). The grammar specifies the exact locations in
which sub-item declarations may appear.</p>
<a class="header" href="print.html#modules" id="modules"><h1>Modules</h1></a>
<blockquote>
<p><strong><sup>Syntax:<sup></strong><br />
<em>Module</em> :<br />
      <code>mod</code> <a href="identifiers.html">IDENTIFIER</a> <code>;</code><br />
   | <code>mod</code> <a href="identifiers.html">IDENTIFIER</a> <code>{</code><br />
        <a href="attributes.html"><em>InnerAttribute</em></a><sup>*</sup><br />
        <a href="items.html"><em>Item</em></a><sup>*</sup><br />
      <code>}</code></p>
</blockquote>
<p>A module is a container for zero or more <a href="items.html">items</a>.</p>
<p>A <em>module item</em> is a module, surrounded in braces, named, and prefixed with the
keyword <code>mod</code>. A module item introduces a new, named module into the tree of
modules making up a crate. Modules can nest arbitrarily.</p>
<p>An example of a module:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
mod math {
    type Complex = (f64, f64);
    fn sin(f: f64) -&gt; f64 {
        /* ... */
# panic!();
    }
    fn cos(f: f64) -&gt; f64 {
        /* ... */
# panic!();
    }
    fn tan(f: f64) -&gt; f64 {
        /* ... */
# panic!();
    }
}
#}</code></pre></pre>
<p>Modules and types share the same namespace. Declaring a named type with the
same name as a module in scope is forbidden: that is, a type definition, trait,
struct, enumeration, union, type parameter or crate can't shadow the name of a
module in scope, or vice versa. Items brought into scope with <code>use</code> also have
this restriction.</p>
<p>A module without a body is loaded from an external file, by default with the
same name as the module, plus the <code>.rs</code> extension. When a nested submodule is
loaded from an external file, it is loaded from a subdirectory path that
mirrors the module hierarchy.</p>
<pre><code class="language-rust ignore">// Load the `vec` module from `vec.rs`
mod vec;

mod thread {
    // Load the `local_data` module from `thread/local_data.rs`
    // or `thread/local_data/mod.rs`.
    mod local_data;
}
</code></pre>
<p>The directories and files used for loading external file modules can be
influenced with the <code>path</code> attribute.</p>
<pre><code class="language-rust ignore">#[path = &quot;thread_files&quot;]
mod thread {
    // Load the `local_data` module from `thread_files/tls.rs`
    #[path = &quot;tls.rs&quot;]
    mod local_data;
}
</code></pre>
<a class="header" href="print.html#extern-crate-declarations" id="extern-crate-declarations"><h1>Extern crate declarations</h1></a>
<blockquote>
<p><strong><sup>Syntax:<sup></strong><br />
<em>ExternCrate</em> :<br />
   <code>extern</code> <code>crate</code> <a href="identifiers.html">IDENTIFIER</a> (<code>as</code> <a href="identifiers.html">IDENTIFIER</a>)<sup>?</sup> <code>;</code></p>
</blockquote>
<p>An <em><code>extern crate</code> declaration</em> specifies a dependency on an external crate.
The external crate is then bound into the declaring scope as the <code>ident</code>
provided in the <code>extern_crate_decl</code>.</p>
<p>The external crate is resolved to a specific <code>soname</code> at compile time, and a
runtime linkage requirement to that <code>soname</code> is passed to the linker for
loading at runtime. The <code>soname</code> is resolved at compile time by scanning the
compiler's library path and matching the optional <code>crateid</code> provided against
the <code>crateid</code> attributes that were declared on the external crate when it was
compiled. If no <code>crateid</code> is provided, a default <code>name</code> attribute is assumed,
equal to the <code>ident</code> given in the <code>extern_crate_decl</code>.</p>
<p>Three examples of <code>extern crate</code> declarations:</p>
<pre><code class="language-rust ignore">extern crate pcre;

extern crate std; // equivalent to: extern crate std as std;

extern crate std as ruststd; // linking to 'std' under another name
</code></pre>
<p>When naming Rust crates, hyphens are disallowed. However, Cargo packages may
make use of them. In such case, when <code>Cargo.toml</code> doesn't specify a crate name,
Cargo will transparently replace <code>-</code> with <code>_</code> (Refer to <a href="https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md">RFC 940</a> for more
details).</p>
<p>Here is an example:</p>
<pre><code class="language-rust ignore">// Importing the Cargo package hello-world
extern crate hello_world; // hyphen replaced with an underscore
</code></pre>
<a class="header" href="print.html#use-declarations" id="use-declarations"><h1>Use declarations</h1></a>
<blockquote>
<p><strong><sup>Syntax:</sup></strong><br />
<em>UseDeclaration</em> :<br />
   (<a href="visibility-and-privacy.html"><em>Visibility</em></a>)<sup>?</sup> <code>use</code> <em>UseTree</em> <code>;</code></p>
<p><em>UseTree</em> :<br />
      (<a href="paths.html"><em>SimplePath</em></a><sup>?</sup> <code>::</code>)<sup>?</sup> <code>*</code><br />
   | (<a href="paths.html"><em>SimplePath</em></a><sup>?</sup> <code>::</code>)<sup>?</sup> <code>{</code> (<em>UseTree</em> ( <code>,</code>  <em>UseTree</em> )<sup>*</sup> <code>,</code><sup>?</sup>)<sup>?</sup> <code>}</code><br />
   | <a href="paths.html"><em>SimplePath</em></a> <code>as</code> <a href="identifiers.html">IDENTIFIER</a></p>
</blockquote>
<p>A <em>use declaration</em> creates one or more local name bindings synonymous with
some other <a href="paths.html">path</a>. Usually a <code>use</code> declaration is used to shorten the path
required to refer to a module item. These declarations may appear in <a href="items/modules.html">modules</a>
and <a href="expressions/block-expr.html">blocks</a>, usually at the top.</p>
<blockquote>
<p><strong>Note</strong>: Unlike in many languages, <code>use</code> declarations in Rust do <em>not</em>
declare linkage dependency with external crates. Rather, <a href="items/extern-crates.html"><code>extern crate</code>
declarations</a> declare linkage dependencies.</p>
</blockquote>
<p>Use declarations support a number of convenient shortcuts:</p>
<ul>
<li>Simultaneously binding a list of paths with a common prefix, using the
glob-like brace syntax <code>use a::b::{c, d, e::f, g::h::i};</code></li>
<li>Simultaneously binding a list of paths with a common prefix and their common
parent module, using the <code>self</code> keyword, such as <code>use a::b::{self, c, d::e};</code></li>
<li>Rebinding the target name as a new local name, using the syntax <code>use p::q::r as x;</code>. This can also be used with the last two features:
<code>use a::b::{self as ab, c as abc}</code>.</li>
<li>Binding all paths matching a given prefix, using the asterisk wildcard syntax
<code>use a::b::*;</code>.</li>
<li>Nesting groups of the previous features multiple times, such as
<code>use a::b::{self as ab, c, d::{*, e::f}};</code></li>
</ul>
<p>An example of <code>use</code> declarations:</p>
<pre><pre class="playpen"><code class="language-rust">use std::option::Option::{Some, None};
use std::collections::hash_map::{self, HashMap};

fn foo&lt;T&gt;(_: T){}
fn bar(map1: HashMap&lt;String, usize&gt;, map2: hash_map::HashMap&lt;String, usize&gt;){}

fn main() {
    // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
    // std::option::Option::None]);'
    foo(vec![Some(1.0f64), None]);

    // Both `hash_map` and `HashMap` are in scope.
    let map1 = HashMap::new();
    let map2 = hash_map::HashMap::new();
    bar(map1, map2);
}
</code></pre></pre>
<p>Like items, <code>use</code> declarations are private to the containing module, by
default. Also like items, a <code>use</code> declaration can be public, if qualified by
the <code>pub</code> keyword. Such a <code>use</code> declaration serves to <em>re-export</em> a name. A
public <code>use</code> declaration can therefore <em>redirect</em> some public name to a
different target definition: even a definition with a private canonical path,
inside a different module. If a sequence of such redirections form a cycle or
cannot be resolved unambiguously, they represent a compile-time error.</p>
<p>An example of re-exporting:</p>
<pre><pre class="playpen"><code class="language-rust"># fn main() { }
mod quux {
    pub use quux::foo::{bar, baz};

    pub mod foo {
        pub fn bar() { }
        pub fn baz() { }
    }
}
</code></pre></pre>
<p>In this example, the module <code>quux</code> re-exports two public names defined in
<code>foo</code>.</p>
<p>Also note that the paths contained in <code>use</code> items are relative to the crate
root. So, in the previous example, the <code>use</code> refers to <code>quux::foo::{bar, baz}</code>,
and not simply to <code>foo::{bar, baz}</code>. This also means that top-level module
declarations should be at the crate root if direct usage of the declared
modules within <code>use</code> items is desired. It is also possible to use <code>self</code> and
<code>super</code> at the beginning of a <code>use</code> item to refer to the current and direct
parent modules respectively. All rules regarding accessing declared modules in
<code>use</code> declarations apply to both module declarations and <code>extern crate</code>
declarations.</p>
<p>An example of what will and will not work for <code>use</code> items:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_imports)]
use foo::baz::foobaz;    // good: foo is at the root of the crate

mod foo {

    mod example {
        pub mod iter {}
    }

    use foo::example::iter; // good: foo is at crate root
//  use example::iter;      // bad:  example is not at the crate root
    use self::baz::foobaz;  // good: self refers to module 'foo'
    use foo::bar::foobar;   // good: foo is at crate root

    pub mod bar {
        pub fn foobar() { }
    }

    pub mod baz {
        use super::bar::foobar; // good: super refers to module 'foo'
        pub fn foobaz() { }
    }
}

fn main() {}
</code></pre></pre>
<a class="header" href="print.html#functions" id="functions"><h1>Functions</h1></a>
<p>A <em>function</em> consists of a <a href="expressions/block-expr.html">block</a>, along with a name and a set of parameters.
Other than a name, all these are optional. Functions are declared with the
keyword <code>fn</code>. Functions may declare a set of <em>input</em> <a href="variables.html"><em>variables</em></a>
as parameters, through which the caller passes arguments into the function, and
the <em>output</em> <a href="types.html"><em>type</em></a> of the value the function will return to its caller
on completion.</p>
<p>When referred to, a <em>function</em> yields a first-class <em>value</em> of the
corresponding zero-sized <a href="types.html#function-item-types"><em>function item type</em></a>, which
when called evaluates to a direct call to the function.</p>
<p>For example, this is a simple function:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn answer_to_life_the_universe_and_everything() -&gt; i32 {
    return 42;
}
#}</code></pre></pre>
<p>As with <code>let</code> bindings, function arguments are irrefutable patterns, so any
pattern that is valid in a let binding is also valid as an argument:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn first((value, _): (i32, i32)) -&gt; i32 { value }
#}</code></pre></pre>
<p>The block of a function is conceptually wrapped in a block that binds the
argument patterns and then <code>return</code>s the value of the function's block. This
means that the tail expression of the block, if evaluated, ends up being
returned to the caller. As usual, an explicit return expression within
the body of the function will short-cut that implicit return, if reached.</p>
<p>For example, the function above behaves as if it was written as:</p>
<pre><code class="language-rust ignore">// argument_0 is the actual first argument passed from the caller
let (value, _) = argument_0;
return {
    value
};
</code></pre>
<a class="header" href="print.html#generic-functions" id="generic-functions"><h2>Generic functions</h2></a>
<p>A <em>generic function</em> allows one or more <em>parameterized types</em> to appear in its
signature. Each type parameter must be explicitly declared in an
angle-bracket-enclosed and comma-separated list, following the function name.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// foo is generic over A and B

fn foo&lt;A, B&gt;(x: A, y: B) {
# }
#}</code></pre></pre>
<p>Inside the function signature and body, the name of the type parameter can be
used as a type name. <a href="items/traits.html">Trait</a> bounds can be specified for type
parameters to allow methods with that trait to be called on values of that
type. This is specified using the <code>where</code> syntax:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# use std::fmt::Debug;
fn foo&lt;T&gt;(x: T) where T: Debug {
# }
#}</code></pre></pre>
<p>When a generic function is referenced, its type is instantiated based on the
context of the reference. For example, calling the <code>foo</code> function here:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::fmt::Debug;

fn foo&lt;T&gt;(x: &amp;[T]) where T: Debug {
    // details elided
}

foo(&amp;[1, 2]);
#}</code></pre></pre>
<p>will instantiate type parameter <code>T</code> with <code>i32</code>.</p>
<p>The type parameters can also be explicitly supplied in a trailing <a href="paths.html">path</a>
component after the function name. This might be necessary if there is not
sufficient context to determine the type parameters. For example,
<code>mem::size_of::&lt;u32&gt;() == 4</code>.</p>
<a class="header" href="print.html#extern-functions" id="extern-functions"><h2>Extern functions</h2></a>
<p>Extern functions are part of Rust's foreign function interface, providing the
opposite functionality to <a href="items/external-blocks.html">external blocks</a>. Whereas external
blocks allow Rust code to call foreign code, extern functions with bodies
defined in Rust code <em>can be called by foreign code</em>. They are defined in the
same way as any other Rust function, except that they have the <code>extern</code>
modifier.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Declares an extern fn, the ABI defaults to &quot;C&quot;
extern fn new_i32() -&gt; i32 { 0 }

// Declares an extern fn with &quot;stdcall&quot; ABI
# #[cfg(target_arch = &quot;x86_64&quot;)]
extern &quot;stdcall&quot; fn new_i32_stdcall() -&gt; i32 { 0 }
#}</code></pre></pre>
<p>Unlike normal functions, extern fns have type <code>extern &quot;ABI&quot; fn()</code>. This is the
same type as the functions declared in an extern block.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# extern fn new_i32() -&gt; i32 { 0 }
let fptr: extern &quot;C&quot; fn() -&gt; i32 = new_i32;
#}</code></pre></pre>
<p>As non-Rust calling conventions do not support unwinding, unwinding past the end
of an extern function will cause the process to abort. In LLVM, this is
implemented by executing an illegal instruction.</p>
<a class="header" href="print.html#type-aliases" id="type-aliases"><h1>Type aliases</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>TypeAlias</em> :<br />
   <code>type</code> <a href="identifiers.html">IDENTIFIER</a> <a href="items/generics.html"><em>Generics</em></a><sup>?</sup>
<a href="items/generics.html#where-clauses"><em>WhereClause</em></a><sup>?</sup> <code>=</code> <a href="types.html"><em>Type</em></a> <code>;</code></p>
</blockquote>
<p>A <em>type alias</em> defines a new name for an existing <a href="types.html">type</a>. Type aliases are
declared with the keyword <code>type</code>. Every value has a single, specific type, but
may implement several different traits, or be compatible with several different
type constraints.</p>
<p>For example, the following defines the type <code>Point</code> as a synonym for the type
<code>(u8, u8)</code>, the type of pairs of unsigned 8 bit integers:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
type Point = (u8, u8);
let p: Point = (41, 68);
#}</code></pre></pre>
<p>A type alias to an enum type cannot be used to qualify the constructors:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
enum E { A }
type F = E;
let _: F = E::A;  // OK
// let _: F = F::A;  // Doesn't work
#}</code></pre></pre>
<a class="header" href="print.html#structs" id="structs"><h1>Structs</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Struct</em> :<br />
      <em>StructStruct</em><br />
   | <em>TupleStruct</em></p>
<p><em>StructStruct</em> :<br />
   <code>struct</code>
<a href="identifiers.html">IDENTIFIER</a> 
<a href="items/generics.html"><em>Generics</em></a><sup>?</sup>
<a href="items/generics.html#where-clauses"><em>WhereClause</em></a><sup>?</sup>
( <code>{</code> <em>StructFields</em><sup>?</sup> <code>}</code> | <code>;</code> )</p>
<p><em>TupleStruct</em> :<br />
   <code>struct</code>
<a href="identifiers.html">IDENTIFIER</a> 
<a href="items/generics.html"><em>Generics</em></a><sup>?</sup>
<code>(</code> <em>TupleFields</em><sup>?</sup> <code>)</code>
<a href="items/generics.html#where-clauses"><em>WhereClause</em></a><sup>?</sup>
<code>;</code></p>
<p><em>StructFields</em> :<br />
   <em>StructField</em> (<code>,</code> <em>StructField</em>)<sup>*</sup> <code>,</code><sup>?</sup></p>
<p><em>StructField</em> :<br />
   <a href="attributes.html"><em>OuterAttribute</em></a><sup>*</sup><br />
   <a href="visibility-and-privacy.html"><em>Visibility</em></a>
   <a href="identifiers.html">IDENTIFIER</a> <code>:</code> <a href="types.html"><em>Type</em></a></p>
<p><em>TupleFields</em> :<br />
   <em>TupleField</em> (<code>,</code> <em>TupleField</em>)<sup>*</sup> <code>,</code><sup>?</sup></p>
<p><em>TupleField</em> :<br />
   <a href="attributes.html"><em>OuterAttribute</em></a><sup>*</sup><br />
   <a href="visibility-and-privacy.html"><em>Visibility</em></a>
   <a href="types.html"><em>Type</em></a></p>
</blockquote>
<p>A <em>struct</em> is a nominal <a href="types.html#struct-types">struct type</a> defined with the keyword <code>struct</code>.</p>
<p>An example of a <code>struct</code> item and its use:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Point {x: i32, y: i32}
let p = Point {x: 10, y: 11};
let px: i32 = p.x;
#}</code></pre></pre>
<p>A <em>tuple struct</em> is a nominal <a href="types.html#tuple-types">tuple type</a>, also defined with the keyword
<code>struct</code>. For example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Point(i32, i32);
let p = Point(10, 11);
let px: i32 = match p { Point(x, _) =&gt; x };
#}</code></pre></pre>
<p>A <em>unit-like struct</em> is a struct without any fields, defined by leaving off the
list of fields entirely. Such a struct implicitly defines a constant of its
type with the same name. For example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Cookie;
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
#}</code></pre></pre>
<p>is equivalent to</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Cookie {}
const Cookie: Cookie = Cookie {};
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
#}</code></pre></pre>
<p>The precise memory layout of a struct is not specified. One can specify a
particular layout using the <a href="attributes.html#ffi-attributes"><code>repr</code> attribute</a>.</p>
<a class="header" href="print.html#enumerations" id="enumerations"><h1>Enumerations</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Enumeration</em> :<br />
   <code>enum</code>
<a href="identifiers.html">IDENTIFIER</a> 
<a href="items/generics.html"><em>Generics</em></a><sup>?</sup>
<a href="items/generics.html#where-clauses"><em>WhereClause</em></a><sup>?</sup>
<code>{</code> <em>EnumItems</em><sup>?</sup> <code>}</code></p>
<p><em>EnumItems</em> :<br />
   <em>EnumItem</em> ( <code>,</code> <em>EnumItem</em> )<sup>*</sup> <code>,</code><sup>?</sup></p>
<p><em>EnumItem</em> :<br />
   <em>OuterAttribute</em><sup>*</sup><br />
   <a href="identifiers.html">IDENTIFIER</a> ( <em>EnumItemTuple</em> | <em>EnumItemStruct</em>
| <em>EnumItemDiscriminant</em> )<sup>?</sup></p>
<p><em>EnumItemTuple</em> :<br />
   <code>(</code> <a href="items/structs.html"><em>TupleFields</em></a><sup>?</sup> <code>)</code></p>
<p><em>EnumItemStruct</em> :<br />
   <code>{</code> <a href="items/structs.html"><em>StructFields</em></a><sup>?</sup> <code>}</code></p>
<p><em>EnumItemDiscriminant</em> :<br />
   <code>=</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>An <em>enumeration</em>, also referred to as <em>enum</em> is a simultaneous definition of a
nominal <a href="types.html#enumerated-types">enumerated type</a> as well as a set of <em>constructors</em>, that can be used
to create or pattern-match values of the corresponding enumerated type.</p>
<p>Enumerations are declared with the keyword <code>enum</code>.</p>
<p>An example of an <code>enum</code> item and its use:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
enum Animal {
    Dog,
    Cat,
}

let mut a: Animal = Animal::Dog;
a = Animal::Cat;
#}</code></pre></pre>
<p>Enum constructors can have either named or unnamed fields:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
enum Animal {
    Dog(String, f64),
    Cat { name: String, weight: f64 },
}

let mut a: Animal = Animal::Dog(&quot;Cocoa&quot;.to_string(), 37.2);
a = Animal::Cat { name: &quot;Spotty&quot;.to_string(), weight: 2.7 };
#}</code></pre></pre>
<p>In this example, <code>Cat</code> is a <em>struct-like enum variant</em>, whereas <code>Dog</code> is simply
called an enum variant. Each enum instance has a <em>discriminant</em> which is an
integer associated to it that is used to determine which variant it holds. An
opaque reference to this discriminant can be obtained with the
<a href="../std/mem/fn.discriminant.html"><code>mem::discriminant</code></a> function.</p>
<a class="header" href="print.html#custom-discriminant-values-for-field-less-enumerations" id="custom-discriminant-values-for-field-less-enumerations"><h2>Custom Discriminant Values for Field-Less Enumerations</h2></a>
<p>If there is no data attached to <em>any</em> of the variants of an enumeration,
then the discriminant can be directly chosen and accessed.</p>
<p>These enumerations can be cast to integer types with the <code>as</code> operator by a
<a href="expressions/operator-expr.html#semantics">numeric cast</a>. The enumeration can optionally specify which integer each
discriminant gets by following the variant name with <code>=</code> and then an integer
literal. If the first variant in the declaration is unspecified, then it is set
to zero. For every unspecified discriminant, it is set to one higher than the
previous variant in the declaration.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
enum Foo {
    Bar,            // 0
    Baz = 123,      // 123
    Quux,           // 124
}

let baz_discriminant = Foo::Baz as u32;
assert_eq!(baz_discriminant, 123);
#}</code></pre></pre>
<p>Under the [default representation], the specified discriminant is interpreted as
an <code>isize</code> value although the compiler is allowed to use a smaller type in the
actual memory layout. The size and thus acceptable values can be changed by
using a [primitive representation] or the [<code>C</code> representation].</p>
<p>It is an error when two variants share the same discriminant.</p>
<pre><code class="language-rust ignore">enum SharedDiscriminantError {
    SharedA = 1,
    SharedB = 1
}

enum SharedDiscriminantError2 {
    Zero,       // 0
    One,        // 1
    OneToo = 1  // 1 (collision with previous!)
}
</code></pre>
<p>It is also an error to have an unspecified discriminant where the previous
discriminant is the maximum value for the size of the discriminant.</p>
<pre><code class="language-rust ignore">#[repr(u8)]
enum OverflowingDiscriminantError {
    Max = 255,
    MaxPlusOne // Would be 256, but that overflows the enum.
}

#[repr(u8)]
enum OverflowingDiscriminantError2 {
    MaxMinusOne = 254, // 254
    Max,               // 255
    MaxPlusOne         // Would be 256, but that overflows the enum.
}
</code></pre>
<a class="header" href="print.html#zero-variant-enums" id="zero-variant-enums"><h2>Zero-variant Enums</h2></a>
<p>Enums with zero variants are known as <em>zero-variant enums</em>. As they have
no valid values, they cannot be instantiated.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
enum ZeroVariants {}
#}</code></pre></pre>
<a class="header" href="print.html#unions" id="unions"><h1>Unions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Union</em> :<br />
   <code>union</code> <a href="identifiers.html">IDENTIFIER</a> <a href="items/generics.html"><em>Generics</em></a><sup>?</sup> <a href="items/generics.html#where-clauses"><em>WhereClause</em></a><sup>?</sup>
<code>{</code><a href="items/structs.html"><em>StructFields</em></a> <code>}</code></p>
</blockquote>
<p>A union declaration uses the same syntax as a struct declaration, except with
<code>union</code> in place of <code>struct</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[repr(C)]
union MyUnion {
    f1: u32,
    f2: f32,
}
#}</code></pre></pre>
<p>The key property of unions is that all fields of a union share common storage.
As a result writes to one field of a union can overwrite its other fields, and
size of a union is determined by the size of its largest field.</p>
<p>A value of a union type can be created using the same syntax that is used for
struct types, except that it must specify exactly one field:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# union MyUnion { f1: u32, f2: f32 }
#
let u = MyUnion { f1: 1 };
#}</code></pre></pre>
<p>The expression above creates a value of type <code>MyUnion</code> with active field <code>f1</code>.
Active field of a union can be accessed using the same syntax as struct fields:</p>
<pre><code class="language-rust ignore">let f = u.f1;
</code></pre>
<p>Inactive fields can be accessed as well (using the same syntax) if they are
sufficiently layout compatible with the current value kept by the union.
Reading incompatible fields results in undefined behavior. However, the active
field is not generally known statically, so all reads of union fields have to
be placed in <code>unsafe</code> blocks.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# union MyUnion { f1: u32, f2: f32 }
# let u = MyUnion { f1: 1 };
#
unsafe {
    let f = u.f1;
}
#}</code></pre></pre>
<p>Writes to <code>Copy</code> union fields do not require reads for running destructors, so
these writes don't have to be placed in <code>unsafe</code> blocks</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# union MyUnion { f1: u32, f2: f32 }
# let mut u = MyUnion { f1: 1 };
#
u.f1 = 2;
#}</code></pre></pre>
<p>Commonly, code using unions will provide safe wrappers around unsafe union
field accesses.</p>
<p>Another way to access union fields is to use pattern matching. Pattern matching
on union fields uses the same syntax as struct patterns, except that the
pattern must specify exactly one field. Since pattern matching accesses
potentially inactive fields it has to be placed in <code>unsafe</code> blocks as well.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# union MyUnion { f1: u32, f2: f32 }
#
fn f(u: MyUnion) {
    unsafe {
        match u {
            MyUnion { f1: 10 } =&gt; { println!(&quot;ten&quot;); }
            MyUnion { f2 } =&gt; { println!(&quot;{}&quot;, f2); }
        }
    }
}
#}</code></pre></pre>
<p>Pattern matching may match a union as a field of a larger structure. In
particular, when using a Rust union to implement a C tagged union via FFI, this
allows matching on the tag and the corresponding field simultaneously:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[repr(u32)]
enum Tag { I, F }

#[repr(C)]
union U {
    i: i32,
    f: f32,
}

#[repr(C)]
struct Value {
    tag: Tag,
    u: U,
}

fn is_zero(v: Value) -&gt; bool {
    unsafe {
        match v {
            Value { tag: I, u: U { i: 0 } } =&gt; true,
            Value { tag: F, u: U { f: 0.0 } } =&gt; true,
            _ =&gt; false,
        }
    }
}
#}</code></pre></pre>
<p>Since union fields share common storage, gaining write access to one field of a
union can give write access to all its remaining fields. Borrow checking rules
have to be adjusted to account for this fact. As a result, if one field of a
union is borrowed, all its remaining fields are borrowed as well for the same
lifetime.</p>
<pre><code class="language-rust ignore">// ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time
fn test() {
    let mut u = MyUnion { f1: 1 };
    unsafe {
        let b1 = &amp;mut u.f1;
                      ---- first mutable borrow occurs here (via `u.f1`)
        let b2 = &amp;mut u.f2;
                      ^^^^ second mutable borrow occurs here (via `u.f2`)
        *b1 = 5;
    }
    - first borrow ends here
    assert_eq!(unsafe { u.f1 }, 5);
}
</code></pre>
<p>As you could see, in many aspects (except for layouts, safety and ownership)
unions behave exactly like structs, largely as a consequence of inheriting
their syntactic shape from structs. This is also true for many unmentioned
aspects of Rust language (such as privacy, name resolution, type inference,
generics, trait implementations, inherent implementations, coherence, pattern
checking, etc etc etc).</p>
<p>More detailed specification for unions, including unstable bits, can be found
in <a href="https://github.com/rust-lang/rfcs/pull/1897">RFC 1897 &quot;Unions v1.2&quot;</a>.</p>
<a class="header" href="print.html#constant-items" id="constant-items"><h1>Constant items</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong>
<em>ConstantItem</em> :
   <code>const</code> <a href="identifiers.html">IDENTIFIER</a> <code>:</code> <a href="types.html"><em>Type</em></a> <code>=</code> <a href="expressions.html"><em>Expression</em></a> <code>;</code></p>
</blockquote>
<p>A <em>constant item</em> is a named <em><a href="expressions.html#constant-expressions">constant value</a></em> which is not associated with a
specific memory location in the program. Constants are essentially inlined
wherever they are used, meaning that they are copied directly into the relevant
context when used. References to the same constant are not necessarily
guaranteed to refer to the same memory address.</p>
<p>Constants must be explicitly typed. The type must have a <code>'static</code> lifetime: any
references it contains must have <code>'static</code> lifetimes.</p>
<p>Constants may refer to the address of other constants, in which case the
address will have elided lifetimes where applicable, otherwise – in most cases
– defaulting to the <code>static</code> lifetime. (See <a href="lifetime-elision.html#static-lifetime-elision">static lifetime
elision</a>.) The compiler is, however, still at liberty to translate the constant
many times, so the address referred to may not be stable.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
const BIT1: u32 = 1 &lt;&lt; 0;
const BIT2: u32 = 1 &lt;&lt; 1;

const BITS: [u32; 2] = [BIT1, BIT2];
const STRING: &amp;'static str = &quot;bitstring&quot;;

struct BitsNStrings&lt;'a&gt; {
    mybits: [u32; 2],
    mystring: &amp;'a str,
}

const BITS_N_STRINGS: BitsNStrings&lt;'static&gt; = BitsNStrings {
    mybits: BITS,
    mystring: STRING,
};
#}</code></pre></pre>
<a class="header" href="print.html#constants-with-destructors" id="constants-with-destructors"><h2>Constants with Destructors</h2></a>
<p>Constants can contain destructors. Destructors are ran when the value goes out
of scope.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct TypeWithDestructor(i32);

impl Drop for TypeWithDestructor {
    fn drop(&amp;mut self) {
        println!(&quot;Dropped. Held {}.&quot;, self.0);
    }
}

const ZERO_WITH_DESTRUCTOR: TypeWithDestructor = TypeWithDestructor(0);

fn create_and_drop_zero_with_destructor() {
    let x = ZERO_WITH_DESTRUCTOR;
    // x gets dropped at end of function, calling drop.
    // prints &quot;Dropped. Held 0.&quot;.
}
#}</code></pre></pre>
<a class="header" href="print.html#static-items" id="static-items"><h1>Static items</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>StaticItem</em> :<br />
   <code>static</code> <code>mut</code><sup>?</sup> <a href="identifiers.html">IDENTIFIER</a> <code>:</code> <a href="types.html"><em>Type</em></a>
<code>=</code> <a href="expressions.html"><em>Expression</em></a> <code>;</code></p>
</blockquote>
<p>A <em>static item</em> is similar to a <a href="items/constant-items.html">constant</a>, except that it represents a precise
memory location in the program. All references to the static refer to the same
memory location. Static items have the <code>static</code> lifetime, which outlives all
other lifetimes in a Rust program. Non-<code>mut</code> static items that contain a type
that is not <a href="interior-mutability.html">interior mutable</a> may be placed in read-only memory. Static items
do not call <a href="destructors.html"><code>drop</code></a> at the end of the program.</p>
<p>All access to a static is safe, but there are a number of restrictions on
statics:</p>
<ul>
<li>The type must have the <code>Sync</code> trait bound to allow thread-safe access.</li>
<li>Statics allow using paths to statics in the [constant-expression] used to
initialize them, but statics may not refer to other statics by value, only
through a reference.</li>
<li>Constants cannot refer to statics.</li>
</ul>
<a class="header" href="print.html#mutable-statics" id="mutable-statics"><h2>Mutable statics</h2></a>
<p>If a static item is declared with the <code>mut</code> keyword, then it is allowed to be
modified by the program. One of Rust's goals is to make concurrency bugs hard
to run into, and this is obviously a very large source of race conditions or
other bugs. For this reason, an <code>unsafe</code> block is required when either reading
or writing a mutable static variable. Care should be taken to ensure that
modifications to a mutable static are safe with respect to other threads
running in the same process.</p>
<p>Mutable statics are still very useful, however. They can be used with C
libraries and can also be bound from C libraries in an <code>extern</code> block.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# fn atomic_add(_: &amp;mut u32, _: u32) -&gt; u32 { 2 }

static mut LEVELS: u32 = 0;

// This violates the idea of no shared state, and this doesn't internally
// protect against races, so this function is `unsafe`
unsafe fn bump_levels_unsafe1() -&gt; u32 {
    let ret = LEVELS;
    LEVELS += 1;
    return ret;
}

// Assuming that we have an atomic_add function which returns the old value,
// this function is &quot;safe&quot; but the meaning of the return value may not be what
// callers expect, so it's still marked as `unsafe`
unsafe fn bump_levels_unsafe2() -&gt; u32 {
    return atomic_add(&amp;mut LEVELS, 1);
}
#}</code></pre></pre>
<p>Mutable statics have the same restrictions as normal statics, except that the
type does not have to implement the <code>Sync</code> trait.</p>
<a class="header" href="print.html#using-statics-or-consts" id="using-statics-or-consts"><h2>Using Statics or Consts</h2></a>
<p>It can be confusing whether or not you should use a constant item or a static
item. Constants should, in general, be preferred over statics unless one of the
following are true:</p>
<ul>
<li>Large amounts of data are being stored</li>
<li>The single-address property of statics is required.</li>
<li>Interior mutability is required.</li>
</ul>
<a class="header" href="print.html#traits" id="traits"><h1>Traits</h1></a>
<p>A <em>trait</em> describes an abstract interface that types can implement. This
interface consists of <a href="items/associated-items.html">associated items</a>, which come in three varieties:</p>
<ul>
<li><a href="items/associated-items.html#associated-functions-and-methods">functions</a></li>
<li><a href="items/associated-items.html#associated-types">types</a></li>
<li><a href="items/associated-items.html#associated-constants">constants</a></li>
</ul>
<p>All traits define an implicit type parameter <code>Self</code> that refers to &quot;the type
that is implementing this interface&quot;. Traits may also contain additional type
parameters. These type parameters, including <code>Self</code>, may be constrained by
other traits and so forth <a href="items/generics.html">as usual</a>.</p>
<p>Traits are implemented for specific types through separate <a href="items/implementations.html">implementations</a>.</p>
<p>Items associated with a trait do not need to be defined in the trait, but they
may be. If the trait provides a definition, then this definition acts as a
default for any implementation which does not override it. If it does not, then
any implementation must provide a definition.</p>
<a class="header" href="print.html#trait-bounds" id="trait-bounds"><h2>Trait bounds</h2></a>
<p>Generic items may use traits as <a href="trait-bounds.html">bounds</a> on their type parameters.</p>
<a class="header" href="print.html#generic-traits" id="generic-traits"><h2>Generic Traits</h2></a>
<p>Type parameters can be specified for a trait to make it generic. These appear
after the trait name, using the same syntax used in <a href="items/functions.html#generic-functions">generic functions</a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Seq&lt;T&gt; {
    fn len(&amp;self) -&gt; u32;
    fn elt_at(&amp;self, n: u32) -&gt; T;
    fn iter&lt;F&gt;(&amp;self, F) where F: Fn(T);
}
#}</code></pre></pre>
<a class="header" href="print.html#object-safety" id="object-safety"><h2>Object Safety</h2></a>
<p>Object safe traits can be the base trait of a <a href="types.html#trait-objects">trait object</a>. A trait is
<em>object safe</em> if it has the following qualities (defined in <a href="https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md">RFC 255</a>):</p>
<ul>
<li>It must not require <code>Self: Sized</code></li>
<li>All associated functions must either have a <code>where Self: Sized</code> bound, or
<ul>
<li>Not have any type parameters (although lifetime parameters are allowed),
and</li>
<li>Be a <a href="items/associated-items.html#methods">method</a> that does not use <code>Self</code> except in the type of the receiver.</li>
</ul>
</li>
<li>It must not have any associated constants.</li>
<li>All supertraits must also be object safe.</li>
</ul>
<a class="header" href="print.html#supertraits" id="supertraits"><h2>Supertraits</h2></a>
<p><strong>Supertraits</strong> are traits that are required to be implemented for a type to
implement a specific trait. Furthermore, anywhere a [generic] or <a href="types.html#trait-objects">trait object</a>
is bounded by a trait, it has access to the associated items of its supertraits.</p>
<p>Supertraits are declared by trait bounds on the <code>Self</code> type of a trait and
transitively the supertraits of the traits declared in those trait bounds. It is
an error for a trait to be its own supertrait.</p>
<p>The trait with a supertrait is called a <strong>subtrait</strong> of its supertrait.</p>
<p>The following is an example of declaring <code>Shape</code> to be a supertrait of <code>Circle</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Shape { fn area(&amp;self) -&gt; f64; }
trait Circle : Shape { fn radius(&amp;self) -&gt; f64; }
#}</code></pre></pre>
<p>And the following is the same example, except using <a href="items/generics.html#where-clauses">where clauses</a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Shape { fn area(&amp;self) -&gt; f64; }
trait Circle where Self: Shape { fn radius(&amp;self) -&gt; f64; }
#}</code></pre></pre>
<p>This next example gives <code>radius</code> a default implementation using the <code>area</code>
function from <code>Shape</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# trait Shape { fn area(&amp;self) -&gt; f64; }
trait Circle where Self: Shape {
    fn radius(&amp;self) -&gt; f64 {
        // A = pi * r^2
        // so algebraically,
        // r = sqrt(A / pi)
        (self.area() /std::f64::consts::PI).sqrt()
    }
}
#}</code></pre></pre>
<p>This next example calls a supertrait method on a generic parameter.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# trait Shape { fn area(&amp;self) -&gt; f64; }
# trait Circle : Shape { fn radius(&amp;self) -&gt; f64; }
fn print_area_and_radius&lt;C: Circle&gt;(c: C) {
    // Here we call the area method from the supertrait `Shape` of `Circle`.
    println!(&quot;Area: {}&quot;, c.area());
    println!(&quot;Radius: {}&quot;, c.radius());
}
#}</code></pre></pre>
<p>Similarly, here is an example of calling supertrait methods on trait objects.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# trait Shape { fn area(&amp;self) -&gt; f64; }
# trait Circle : Shape { fn radius(&amp;self) -&gt; f64; }
# struct UnitCircle;
# impl Shape for UnitCircle { fn area(&amp;self) -&gt; f64 { std::f64::consts::PI } }
# impl Circle for UnitCircle { fn radius(&amp;self) -&gt; f64 { 1.0 } }
# let circle = UnitCircle;
let circle = Box::new(circle) as Box&lt;dyn Circle&gt;;
let nonsense = circle.radius() * circle.area();
#}</code></pre></pre>
<a class="header" href="print.html#implementations" id="implementations"><h1>Implementations</h1></a>
<p>An <em>implementation</em> is an item that associates items with an <em>implementing type</em>.</p>
<p>There are two types of implementations: inherent implementations and <a href="items/traits.html">trait</a>
implementations.</p>
<p>Implementations are defined with the keyword <code>impl</code>.</p>
<a class="header" href="print.html#inherent-implementations" id="inherent-implementations"><h2>Inherent Implementations</h2></a>
<p>An inherent implementation is defined as the sequence of the <code>impl</code> keyword,
generic type declarations, a path to a nominal type, a where clause, and a
bracketed set of associable items.</p>
<p>The nominal type is called the <em>implementing type</em> and the associable items are
the <em>associated items</em> to the implementing type.</p>
<p>Inherent implementations associate the associated items to the implementing
type.</p>
<p>The associated item has a path of a path to the implementing type followed by
the associate item's path component.</p>
<p>Inherent implementations cannot contain associated type aliases.</p>
<p>A type can have multiple inherent implementations.</p>
<p>The implementing type must be defined within the same crate.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct Point {x: i32, y: i32}

impl Point {
    fn log(&amp;self) {
        println!(&quot;Point is at ({}, {})&quot;, self.x, self.y);
    }
}

let my_point = Point {x: 10, y:11};
my_point.log();
#}</code></pre></pre>
<a class="header" href="print.html#trait-implementations" id="trait-implementations"><h2>Trait Implementations</h2></a>
<p>A <em>trait implementation</em> is defined like an inherent implementation except that
the optional generic type declarations is followed by a <a href="items/traits.html">trait</a> followed
by the keyword <code>for</code>. <!-- To understand this, you have to back-reference to
the previous section. :( --></p>
<p>The trait is known as the <em>implemented trait</em>.</p>
<p>The implementing type implements the implemented trait.</p>
<p>A trait implementation must define all non-default associated items declared
by the implemented trait, may redefine default associated items defined by the
implemented trait, and cannot define any other items.</p>
<p>The path to the associated items is <code>&lt;</code> followed by a path to the implementing
type followed by <code>as</code> followed by a path to the trait followed by <code>&gt;</code> as a path
component followed by the associated item's path component.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# #[derive(Copy, Clone)]
# struct Point {x: f64, y: f64};
# type Surface = i32;
# struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
# trait Shape { fn draw(&amp;self, Surface); fn bounding_box(&amp;self) -&gt; BoundingBox; }
# fn do_draw_circle(s: Surface, c: Circle) { }
struct Circle {
    radius: f64,
    center: Point,
}

impl Copy for Circle {}

impl Clone for Circle {
    fn clone(&amp;self) -&gt; Circle { *self }
}

impl Shape for Circle {
    fn draw(&amp;self, s: Surface) { do_draw_circle(s, *self); }
    fn bounding_box(&amp;self) -&gt; BoundingBox {
        let r = self.radius;
        BoundingBox {
            x: self.center.x - r,
            y: self.center.y - r,
            width: 2.0 * r,
            height: 2.0 * r,
        }
    }
}
#}</code></pre></pre>
<a class="header" href="print.html#trait-implementation-coherence" id="trait-implementation-coherence"><h3>Trait Implementation Coherence</h3></a>
<p>A trait implementation is considered incoherent if either the orphan check fails
or there are overlapping implementation instances.</p>
<p>Two trait implementations overlap when there is a non-empty intersection of the
traits the implementation is for, the implementations can be instantiated with
the same type. <!-- This is probably wrong? Source: No two implementations can 
be instantiable with the same set of types for the input type parameters. --></p>
<p>The <code>Orphan Check</code> states that every trait implementation must meet either of
the following conditions:</p>
<ol>
<li>
<p>The trait being implemented is defined in the same crate.</p>
</li>
<li>
<p>At least one of either <code>Self</code> or a generic type parameter of the trait must
meet the following grammar, where <code>C</code> is a nominal type defined
within the containing crate:</p>
<pre><code class="language-ignore"> T = C
   | &amp;C
   | &amp;mut C
   | Box&lt;C&gt;
</code></pre>
</li>
</ol>
<a class="header" href="print.html#generic-implementations" id="generic-implementations"><h2>Generic Implementations</h2></a>
<p>An implementation can take type and lifetime parameters, which can be used in
the rest of the implementation. Type parameters declared for an implementation
must be used at least once in either the trait or the implementing type of an
implementation. Implementation parameters are written directly after the <code>impl</code>
keyword.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# trait Seq&lt;T&gt; { fn dummy(&amp;self, _: T) { } }
impl&lt;T&gt; Seq&lt;T&gt; for Vec&lt;T&gt; {
    /* ... */
}
impl Seq&lt;bool&gt; for u32 {
    /* Treat the integer as a sequence of bits */
}
#}</code></pre></pre>
<a class="header" href="print.html#external-blocks" id="external-blocks"><h1>External blocks</h1></a>
<p>External blocks form the basis for Rust's foreign function interface.
Declarations in an external block describe symbols in external, non-Rust
libraries.</p>
<p>Functions within external blocks are declared in the same way as other Rust
functions, with the exception that they may not have a body and are instead
terminated by a semicolon.</p>
<p>Functions within external blocks may be called by Rust code, just like
functions defined in Rust. The Rust compiler automatically translates between
the Rust ABI and the foreign ABI.</p>
<p>Functions within external blocks may be variadic by specifying <code>...</code> after one
or more named arguments in the argument list:</p>
<pre><code class="language-rust ignore">extern {
    fn foo(x: i32, ...);
}
</code></pre>
<p>A number of <a href="attributes.html#ffi-attributes">attributes</a> control the behavior of external blocks.</p>
<p>By default external blocks assume that the library they are calling uses the
standard C ABI on the specific platform. Other ABIs may be specified using an
<code>abi</code> string, as shown here:</p>
<pre><code class="language-rust ignore">// Interface to the Windows API
extern &quot;stdcall&quot; { }
</code></pre>
<p>There are three ABI strings which are cross-platform, and which all compilers
are guaranteed to support:</p>
<ul>
<li><code>extern &quot;Rust&quot;</code> -- The default ABI when you write a normal <code>fn foo()</code> in any
Rust code.</li>
<li><code>extern &quot;C&quot;</code> -- This is the same as <code>extern fn foo()</code>; whatever the default
your C compiler supports.</li>
<li><code>extern &quot;system&quot;</code> -- Usually the same as <code>extern &quot;C&quot;</code>, except on Win32, in
which case it's <code>&quot;stdcall&quot;</code>, or what you should use to link to the Windows
API itself</li>
</ul>
<p>There are also some platform-specific ABI strings:</p>
<ul>
<li><code>extern &quot;cdecl&quot;</code> -- The default for x86_32 C code.</li>
<li><code>extern &quot;stdcall&quot;</code> -- The default for the Win32 API on x86_32.</li>
<li><code>extern &quot;win64&quot;</code> -- The default for C code on x86_64 Windows.</li>
<li><code>extern &quot;sysv64&quot;</code> -- The default for C code on non-Windows x86_64.</li>
<li><code>extern &quot;aapcs&quot;</code> -- The default for ARM.</li>
<li><code>extern &quot;fastcall&quot;</code> -- The <code>fastcall</code> ABI -- corresponds to MSVC's
<code>__fastcall</code> and GCC and clang's <code>__attribute__((fastcall))</code></li>
<li><code>extern &quot;vectorcall&quot;</code> -- The <code>vectorcall</code> ABI -- corresponds to MSVC's
<code>__vectorcall</code> and clang's <code>__attribute__((vectorcall))</code></li>
</ul>
<p>Finally, there are some rustc-specific ABI strings:</p>
<ul>
<li><code>extern &quot;rust-intrinsic&quot;</code> -- The ABI of rustc intrinsics.</li>
<li><code>extern &quot;rust-call&quot;</code> -- The ABI of the Fn::call trait functions.</li>
<li><code>extern &quot;platform-intrinsic&quot;</code> -- Specific platform intrinsics -- like, for
example, <code>sqrt</code> -- have this ABI. You should never have to deal with it.</li>
</ul>
<p>The <code>link</code> attribute allows the name of the library to be specified. When
specified the compiler will attempt to link against the native library of the
specified name.</p>
<pre><code class="language-rust ignore">#[link(name = &quot;crypto&quot;)]
extern { }
</code></pre>
<p>The type of a function declared in an extern block is <code>extern &quot;abi&quot; fn(A1, ..., An) -&gt; R</code>, where <code>A1...An</code> are the declared types of its arguments and <code>R</code> is
the declared return type.</p>
<p>It is valid to add the <code>link</code> attribute on an empty extern block. You can use
this to satisfy the linking requirements of extern blocks elsewhere in your
code (including upstream crates) instead of adding the attribute to each extern
block.</p>
<a class="header" href="print.html#type-and-lifetime-parameters" id="type-and-lifetime-parameters"><h1>Type and Lifetime Parameters</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Generics</em> :<br />
   <code>&lt;</code> <em>GenericParams</em> <code>&gt;</code></p>
<p><em>GenericParams</em> :<br />
      <em>LifetimeParams</em><br />
   | ( <em>LifetimeParam</em> <code>,</code> )<sup>*</sup> <em>TypeParams</em></p>
<p><em>LifetimeParams</em> :<br />
   ( <em>LifetimeParam</em> <code>,</code> )<sup>*</sup> <em>LifetimeParam</em><sup>?</sup></p>
<p><em>LifetimeParam</em> :<br />
   <a href="attributes.html"><em>OuterAttribute</em></a><sup>?</sup> <a href="tokens.html#lifetimes-and-loop-labels">LIFETIME_OR_LABEL</a> <code>:</code> <a href="trait-bounds.html"><em>LifetimeBounds</em></a><sup>?</sup></p>
<p><em>TypeParams</em>:<br />
   ( <em>TypeParam</em> <code>,</code> )<sup>*</sup> <em>TypeParam</em> <sup>?</sup></p>
<p><em>TypeParam</em> :<br />
   <a href="attributes.html"><em>OuterAttribute</em></a><sup>?</sup> <a href="identifiers.html">IDENTIFIER</a> ( <code>:</code> <a href="trait-bounds.html"><em>TypeParamBounds</em></a> )<sup>?</sup> ( <code>=</code> <a href="types.html"><em>Type</em></a> )<sup>?</sup></p>
</blockquote>
<p>Functions, type aliases, structs, enumerations, unions, traits and
implementations may be <em>parameterized</em> by types and lifetimes. These parameters
are listed in angle <span class="parenthetical">brackets (<code>&lt;...&gt;</code>)</span>,
usually immediately after and before its definition the name of the item. For
implementations, which don't have a name, they come directly after <code>impl</code>.
Lifetime parameters must be declared before type parameters. Some examples of
items with type and lifetime parameters:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn foo&lt;'a, T&gt;() {}
trait A&lt;U&gt; {}
struct Ref&lt;'a, T&gt; where T: 'a { r: &amp;'a T }
#}</code></pre></pre>
<p><a href="types.html#shared-references-">References</a>, <a href="types.html#raw-pointers-const-and-mut">raw pointers</a>, <a href="types.html#array-and-slice-types">arrays</a>, <a href="types.html#array-and-slice-types">slices</a>, <a href="types.html#tuple-types">tuples</a> and
<a href="types.html#function-pointer-types">function pointers</a> have lifetime or type parameters as well, but are not
referred to with path syntax.</p>
<a class="header" href="print.html#where-clauses" id="where-clauses"><h2>Where clauses</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>WhereClause</em> :<br />
   <code>where</code> ( <em>WhereClauseItem</em> <code>,</code> )<sup>*</sup> <em>WhereClauseItem</em> <sup>?</sup></p>
<p><em>WhereClauseItem</em> :<br />
      <em>LifetimeWhereClauseItem</em><br />
   | <em>TypeBoundWhereClauseItem</em></p>
<p><em>LifetimeWhereClauseItem</em> :<br />
   <a href="trait-bounds.html"><em>Lifetime</em></a> <code>:</code> <a href="trait-bounds.html"><em>LifetimeBounds</em></a></p>
<p><em>TypeBoundWhereClauseItem</em> :<br />
   <em>ForLifetimes</em><sup>?</sup> <a href="types.html"><em>Type</em></a> <code>:</code> <a href="trait-bounds.html"><em>TypeParamBounds</em></a><sup>?</sup></p>
<p><em>ForLifetimes</em> :<br />
   <code>for</code> <code>&lt;</code> <a href="print.html#type-and-lifetime-parameters"><em>LifetimeParams</em></a> <code>&gt;</code></p>
</blockquote>
<p><em>Where clauses</em> provide an another way to specify bounds on type and lifetime
parameters as well as a way to specify bounds on types that aren't type
parameters.</p>
<p>Bounds that don't use the item's parameters or higher-ranked lifetimes are
checked when the item is defined. It is an error for such a bound to be false.</p>
<p><a href="special-types-and-traits.html#copy"><code>Copy</code></a>, <a href="special-types-and-traits.html#clone"><code>Clone</code></a> and <a href="special-types-and-traits.html#sized"><code>Sized</code></a> bounds are also checked for certain generic
types when defining the item. It is an error to have <code>Copy</code> or <code>Clone</code>as a
bound on a mutable reference, <a href="types.html#trait-objects">trait object</a> or <a href="types.html#array-and-slice-types">slice</a> or <code>Sized</code> as a
bound on a trait object or slice.</p>
<pre><code class="language-rust ignore">struct A&lt;T&gt;
where
    T: Iterator,            // Could use A&lt;T: Iterator&gt; instead
    T::Item: Copy,
    String: PartialEq&lt;T&gt;,
    i32: Default,           // Allowed, but not useful
    i32: Iterator,          // Error: the trait bound is not satisfied
    [T]: Copy,              // Error: the trait bound is not satisfied
{
    f: T,
}
</code></pre>
<a class="header" href="print.html#attributes" id="attributes"><h2>Attributes</h2></a>
<p>Generic lifetime and type parameters allow <a href="attributes.html">attributes</a> on them. There are no
built-in attributes that do anything in this position, although custom derive
attributes may give meaning to it.</p>
<p>This example shows using a custom derive attribute to modify the meaning of a
generic parameter.</p>
<pre><code class="language-ignore">// Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as
// an attribute it understands.
#[derive(MyFlexibleClone)] struct Foo&lt;#[my_flexible_clone(unbounded)] H&gt; {
    a: *const H
}
</code></pre>
<a class="header" href="print.html#associated-items" id="associated-items"><h1>Associated Items</h1></a>
<p><em>Associated Items</em> are the items declared in <a href="items/traits.html">traits</a> or defined in
<a href="items/implementations.html">implementations</a>. They are called this because they are defined on an associate
type — the type in the implementation. They are a subset of the kinds of
items you can declare in a module. Specifically, there are <a href="print.html#associated-functions-and-methods">associated
functions</a> (including methods), <a href="print.html#associated-types">associated types</a>, and <a href="print.html#associated-constants">associated constants</a>.</p>
<p>Associated items are useful when the associated item logically is related to the
associating item. For example, the <code>is_some</code> method on <code>Option</code> is intrinsically
related to Options, so should be associated.</p>
<p>Every associated item kind comes in two varieties: definitions that contain the
actual implementation and declarations that declare signatures for
definitions.</p>
<p>It is the declarations that make up the contract of traits and what it available
on generic types.</p>
<a class="header" href="print.html#associated-functions-and-methods" id="associated-functions-and-methods"><h2>Associated functions and methods</h2></a>
<p><em>Associated functions</em> are <a href="items/functions.html">functions</a> associated with a type.</p>
<p>An <em>associated function declaration</em> declares a signature for an associated
function definition. It is written as a function item, except the
function body is replaced with a <code>;</code>.</p>
<p>The identifier if the name of the function. The generics, parameter list,
return type, and where clause of the associated function must be the same as the
associated function declarations's.</p>
<p>An <em>associated function definition</em> defines a function associated with another
type. It is written the same as a [function item].</p>
<p>An example of a common associated function is a <code>new</code> function that returns
a value of the type the associated function is associated with.</p>
<pre><pre class="playpen"><code class="language-rust">struct Struct {
    field: i32
}

impl Struct {
    fn new() -&gt; Struct {
        Struct {
            field: 0i32
        }
    }
}

fn main () {
    let _struct = Struct::new();
}
</code></pre></pre>
<p>When the associated function is declared on a trait, the function can also be
called with a <a href="paths.html">path</a> that is a path to the trait appended by the name of the
trait. When this happens, it is substituted for <code>&lt;_ as Trait&gt;::function_name</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Num {
    fn from_i32(n: i32) -&gt; Self;
}

impl Num for f64 {
    fn from_i32(n: i32) -&gt; f64 { n as f64 }
}

// These 4 are all equivalent in this case.
let _: f64 = Num::from_i32(42);
let _: f64 = &lt;_ as Num&gt;::from_i32(42);
let _: f64 = &lt;f64 as Num&gt;::from_i32(42);
let _: f64 = f64::from_i32(42);
#}</code></pre></pre>
<a class="header" href="print.html#methods" id="methods"><h3>Methods</h3></a>
<p>Associated functions whose first parameter is named <code>self</code> are called <em>methods</em>
and may be invoked using the <a href="expressions/method-call-expr.html">method call operator</a>, for example, <code>x.foo()</code>, as
well as the usual function call notation.</p>
<p>The <code>self</code> parameter must have one of the following types. As a result, the
following shorthands may be used to declare <code>self</code>:</p>
<ul>
<li><code>self</code> -&gt; <code>self: Self</code></li>
<li><code>&amp;'lifetime self</code> -&gt; <code>self: &amp;'lifetime Self</code></li>
<li><code>&amp;'lifetime mut self</code> -&gt; <code>self: &amp;'lifetime mut Self</code></li>
<li><code>self : Box&lt;Self&gt;</code> (no shorthand)</li>
</ul>
<blockquote>
<p>Note: Lifetimes can be and usually are elided with this shorthand.</p>
</blockquote>
<p>Consider the following trait:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# type Surface = i32;
# type BoundingBox = i32;
trait Shape {
    fn draw(&amp;self, Surface);
    fn bounding_box(&amp;self) -&gt; BoundingBox;
}
#}</code></pre></pre>
<p>This defines a trait with two methods. All values that have <a href="items/implementations.html">implementations</a>
of this trait while the trait is in scope can have their <code>draw</code> and
<code>bounding_box</code> methods called.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# type Surface = i32;
# type BoundingBox = i32;
# trait Shape {
#     fn draw(&amp;self, Surface);
#     fn bounding_box(&amp;self) -&gt; BoundingBox;
# }
#
struct Circle {
    // ...
}

impl Shape for Circle {
    // ...
#   fn draw(&amp;self, _: Surface) {}
#   fn bounding_box(&amp;self) -&gt; BoundingBox { 0i32 }
}

# impl Circle {
#     fn new() -&gt; Circle { Circle{} }
# }
#
let circle_shape = Circle::new();
let bounding_box = circle_shape.bounding_box();
#}</code></pre></pre>
<a class="header" href="print.html#associated-types" id="associated-types"><h2>Associated Types</h2></a>
<p><em>Associated types</em> are <a href="items/type-aliases.html">type aliases</a> associated with another type. Associated
types cannot be defined in <a href="items/implementations.html#inherent-implementations">inherent implementations</a> nor can they be given a
default implementation in traits.</p>
<p>An <em>associated type declaration</em> declares a signature for associated type
definitions. It is written as <code>type</code>, then an <a href="identifiers.html">identifier</a>, and
finally an optional list of trait bounds.</p>
<p>The identifier is the name of the declared type alias. The optional trait bounds
must be fulfilled by the implementations of the type alias.</p>
<p>An <em>associated type definition</em> defines a type alias on another type. It is
written as <code>type</code>, then an <a href="identifiers.html">identifier</a>, then an <code>=</code>, and finally a <a href="types.html">type</a>.</p>
<p>If a type <code>Item</code> has an associated type <code>Assoc</code> from a trait <code>Trait</code>, then
<code>&lt;Item as Trait&gt;::Assoc</code> is a type that is an alias of the type specified in the
associated type definition. Furthermore, if <code>Item</code> is a type parameter, then
<code>Item::Assoc</code> can be used in type parameters.</p>
<pre><pre class="playpen"><code class="language-rust">trait AssociatedType {
    // Associated type declaration
    type Assoc;
}

struct Struct;

struct OtherStruct;

impl AssociatedType for Struct {
    // Associated type definition
    type Assoc = OtherStruct;
}

impl OtherStruct {
    fn new() -&gt; OtherStruct {
        OtherStruct
    }
}

fn main() {
    // Usage of the associated type to refer to OtherStruct as &lt;Struct as AssociatedType&gt;::Assoc
    let _other_struct: OtherStruct = &lt;Struct as AssociatedType&gt;::Assoc::new();
}
</code></pre></pre>
<a class="header" href="print.html#associated-types-container-example" id="associated-types-container-example"><h3>Associated Types Container Example</h3></a>
<p>Consider the following example of a <code>Container</code> trait. Notice that the type is
available for use in the method signatures:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Container {
    type E;
    fn empty() -&gt; Self;
    fn insert(&amp;mut self, Self::E);
}
#}</code></pre></pre>
<p>In order for a type to implement this trait, it must not only provide
implementations for every method, but it must specify the type <code>E</code>. Here's an
implementation of <code>Container</code> for the standard library type <code>Vec</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# trait Container {
#     type E;
#     fn empty() -&gt; Self;
#     fn insert(&amp;mut self, Self::E);
# }
impl&lt;T&gt; Container for Vec&lt;T&gt; {
    type E = T;
    fn empty() -&gt; Vec&lt;T&gt; { Vec::new() }
    fn insert(&amp;mut self, x: T) { self.push(x); }
}
#}</code></pre></pre>
<a class="header" href="print.html#associated-constants" id="associated-constants"><h2>Associated Constants</h2></a>
<p><em>Associated constants</em> are <a href="items/constant-items.html">constants</a> associated with a type.</p>
<p>An <em>associated constant declaration</em> declares a signature for associated
constant definitions. It is written as <code>const</code>, then an identifier,
then <code>:</code>, then a type, finished by a <code>;</code>.</p>
<p>The identifier is the name of the constant used in the path. The type is the
type that the definition has to implement.</p>
<p>An <em>associated constant definition</em> defines a constant associated with a
type. It is written the same as a <a href="items/constant-items.html">constant item</a>.</p>
<a class="header" href="print.html#associated-constants-examples" id="associated-constants-examples"><h3>Associated Constants Examples</h3></a>
<p>A basic example:</p>
<pre><pre class="playpen"><code class="language-rust">trait ConstantId {
    const ID: i32;
}

struct Struct;

impl ConstantId for Struct {
    const ID: i32 = 1;
}

fn main() {
    assert_eq!(1, Struct::ID);
}
</code></pre></pre>
<p>Using default values:</p>
<pre><pre class="playpen"><code class="language-rust">trait ConstantIdDefault {
    const ID: i32 = 1;
}

struct Struct;
struct OtherStruct;

impl ConstantIdDefault for Struct {}

impl ConstantIdDefault for OtherStruct {
    const ID: i32 = 5;
}

fn main() {
    assert_eq!(1, Struct::ID);
    assert_eq!(5, OtherStruct::ID);
}
</code></pre></pre>
<a class="header" href="print.html#visibility-and-privacy" id="visibility-and-privacy"><h1>Visibility and Privacy</h1></a>
<blockquote>
<p><strong><sup>Syntax<sup></strong><br />
<em>Visibility</em> :<br />
      EMPTY<br />
   | <code>pub</code><br />
   | <code>pub</code> <code>(</code> <code>crate</code> <code>)</code><br />
   | <code>pub</code> <code>(</code> <code>in</code> <em>ModulePath</em> <code>)</code><br />
   | <code>pub</code> <code>(</code> <code>in</code><sup>?</sup> <code>self</code> <code>)</code><br />
   | <code>pub</code> <code>(</code> <code>in</code><sup>?</sup> <code>super</code> <code>)</code></p>
</blockquote>
<p>These two terms are often used interchangeably, and what they are attempting to
convey is the answer to the question &quot;Can this item be used at this location?&quot;</p>
<p>Rust's name resolution operates on a global hierarchy of namespaces. Each level
in the hierarchy can be thought of as some item. The items are one of those
mentioned above, but also include external crates. Declaring or defining a new
module can be thought of as inserting a new tree into the hierarchy at the
location of the definition.</p>
<p>To control whether interfaces can be used across modules, Rust checks each use
of an item to see whether it should be allowed or not. This is where privacy
warnings are generated, or otherwise &quot;you used a private item of another module
and weren't allowed to.&quot;</p>
<p>By default, everything in Rust is <em>private</em>, with two exceptions: Associated
items in a <code>pub</code> Trait are public by default; Enum variants
in a <code>pub</code> enum are also public by default. When an item is declared as <code>pub</code>,
it can be thought of as being accessible to the outside world. For example:</p>
<pre><pre class="playpen"><code class="language-rust"># fn main() {}
// Declare a private struct
struct Foo;

// Declare a public struct with a private field
pub struct Bar {
    field: i32,
}

// Declare a public enum with two public variants
pub enum State {
    PubliclyAccessibleState,
    PubliclyAccessibleState2,
}
</code></pre></pre>
<p>With the notion of an item being either public or private, Rust allows item
accesses in two cases:</p>
<ol>
<li>If an item is public, then it can be accessed externally from some module
<code>m</code> if you can access all the item's parent modules from <code>m</code>. You can
also potentially be able to name the item through re-exports. See below.</li>
<li>If an item is private, it may be accessed by the current module and its
descendants.</li>
</ol>
<p>These two cases are surprisingly powerful for creating module hierarchies
exposing public APIs while hiding internal implementation details. To help
explain, here's a few use cases and what they would entail:</p>
<ul>
<li>
<p>A library developer needs to expose functionality to crates which link
against their library. As a consequence of the first case, this means that
anything which is usable externally must be <code>pub</code> from the root down to the
destination item. Any private item in the chain will disallow external
accesses.</p>
</li>
<li>
<p>A crate needs a global available &quot;helper module&quot; to itself, but it doesn't
want to expose the helper module as a public API. To accomplish this, the
root of the crate's hierarchy would have a private module which then
internally has a &quot;public API&quot;. Because the entire crate is a descendant of
the root, then the entire local crate can access this private module through
the second case.</p>
</li>
<li>
<p>When writing unit tests for a module, it's often a common idiom to have an
immediate child of the module to-be-tested named <code>mod test</code>. This module
could access any items of the parent module through the second case, meaning
that internal implementation details could also be seamlessly tested from the
child module.</p>
</li>
</ul>
<p>In the second case, it mentions that a private item &quot;can be accessed&quot; by the
current module and its descendants, but the exact meaning of accessing an item
depends on what the item is. Accessing a module, for example, would mean
looking inside of it (to import more items). On the other hand, accessing a
function would mean that it is invoked. Additionally, path expressions and
import statements are considered to access an item in the sense that the
import/expression is only valid if the destination is in the current visibility
scope.</p>
<p>Here's an example of a program which exemplifies the three cases outlined
above:</p>
<pre><pre class="playpen"><code class="language-rust">// This module is private, meaning that no external crate can access this
// module. Because it is private at the root of this current crate, however, any
// module in the crate may access any publicly visible item in this module.
mod crate_helper_module {

    // This function can be used by anything in the current crate
    pub fn crate_helper() {}

    // This function *cannot* be used by anything else in the crate. It is not
    // publicly visible outside of the `crate_helper_module`, so only this
    // current module and its descendants may access it.
    fn implementation_detail() {}
}

// This function is &quot;public to the root&quot; meaning that it's available to external
// crates linking against this one.
pub fn public_api() {}

// Similarly to 'public_api', this module is public so external crates may look
// inside of it.
pub mod submodule {
    use crate_helper_module;

    pub fn my_method() {
        // Any item in the local crate may invoke the helper module's public
        // interface through a combination of the two rules above.
        crate_helper_module::crate_helper();
    }

    // This function is hidden to any module which is not a descendant of
    // `submodule`
    fn my_implementation() {}

    #[cfg(test)]
    mod test {

        #[test]
        fn test_my_implementation() {
            // Because this module is a descendant of `submodule`, it's allowed
            // to access private items inside of `submodule` without a privacy
            // violation.
            super::my_implementation();
        }
    }
}

# fn main() {}
</code></pre></pre>
<p>For a Rust program to pass the privacy checking pass, all paths must be valid
accesses given the two rules above. This includes all use statements,
expressions, types, etc.</p>
<a class="header" href="print.html#pubin-path-pubcrate-pubsuper-and-pubself" id="pubin-path-pubcrate-pubsuper-and-pubself"><h2><code>pub(in path)</code>, <code>pub(crate)</code>, <code>pub(super)</code>, and <code>pub(self)</code></h2></a>
<p>In addition to public and private, Rust allows users to declare an item as
visible within a given scope. The rules for <code>pub</code> restrictions are as follows:</p>
<ul>
<li><code>pub(in path)</code> makes an item visible within the provided <code>path</code>. <code>path</code> must
be a parent module of the item whose visibility is being declared.</li>
<li><code>pub(crate)</code> makes an item visible within the current crate.</li>
<li><code>pub(super)</code> makes an item visible to the parent module. This is equivalent
to <code>pub(in super)</code>.</li>
<li><code>pub(self)</code> makes an item visible to the current module. This is equivalent
to <code>pub(in self)</code>.</li>
</ul>
<p>Here's an example:</p>
<pre><pre class="playpen"><code class="language-rust">pub mod outer_mod {
    pub mod inner_mod {
        // This function is visible within `outer_mod`
        pub(in outer_mod) fn outer_mod_visible_fn() {}

        // This function is visible to the entire crate
        pub(crate) fn crate_visible_fn() {}

        // This function is visible within `outer_mod`
        pub(super) fn super_mod_visible_fn() {
            // This function is visible since we're in the same `mod`
            inner_mod_visible_fn();
        }

        // This function is visible
        pub(self) fn inner_mod_visible_fn() {}
    }
    pub fn foo() {
        inner_mod::outer_mod_visible_fn();
        inner_mod::crate_visible_fn();
        inner_mod::super_mod_visible_fn();

        // This function is no longer visible since we're outside of `inner_mod`
        // Error! `inner_mod_visible_fn` is private
        //inner_mod::inner_mod_visible_fn();
    }
}

fn bar() {
    // This function is still visible since we're in the same crate
    outer_mod::inner_mod::crate_visible_fn();

    // This function is no longer visible since we're outside of `outer_mod`
    // Error! `super_mod_visible_fn` is private
    //outer_mod::inner_mod::super_mod_visible_fn();

    // This function is no longer visible since we're outside of `outer_mod`
    // Error! `outer_mod_visible_fn` is private
    //outer_mod::inner_mod::outer_mod_visible_fn();
    
    outer_mod::foo();
}

fn main() { bar() }
</code></pre></pre>
<a class="header" href="print.html#re-exporting-and-visibility" id="re-exporting-and-visibility"><h2>Re-exporting and Visibility</h2></a>
<p>Rust allows publicly re-exporting items through a <code>pub use</code> directive. Because
this is a public directive, this allows the item to be used in the current
module through the rules above. It essentially allows public access into the
re-exported item. For example, this program is valid:</p>
<pre><pre class="playpen"><code class="language-rust">pub use self::implementation::api;

mod implementation {
    pub mod api {
        pub fn f() {}
    }
}

# fn main() {}
</code></pre></pre>
<p>This means that any external crate referencing <code>implementation::api::f</code> would
receive a privacy violation, while the path <code>api::f</code> would be allowed.</p>
<p>When re-exporting a private item, it can be thought of as allowing the &quot;privacy
chain&quot; being short-circuited through the reexport instead of passing through
the namespace hierarchy as it normally would.</p>
<a class="header" href="print.html#attributes-1" id="attributes-1"><h1>Attributes</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Attribute</em> :<br />
   <em>InnerAttribute</em> | <em>OuterAttribute</em></p>
<p><em>InnerAttribute</em> :<br />
   <code>#![</code> MetaItem <code>]</code></p>
<p><em>OuterAttribute</em> :<br />
   <code>#[</code> MetaItem <code>]</code></p>
<p><em>MetaItem</em> :<br />
      IDENTIFIER<br />
   | IDENTIFIER <code>=</code> LITERAL<br />
   | IDENTIFIER <code>(</code> LITERAL <code>)</code><br />
   | IDENTIFIER <code>(</code> <em>MetaSeq</em> <code>)</code></p>
<p><em>MetaSeq</em> :<br />
      EMPTY<br />
   | <em>MetaItem</em><br />
   | <em>MetaItem</em> <code>,</code> <em>MetaSeq</em></p>
</blockquote>
<p>Any <a href="items.html">item declaration</a> or <a href="items/generics.html">generic lifetime or type parameter</a> may
have an attribute applied to it. Attributes are modeled on Attributes in
<a href="https://www.ecma-international.org/publications/standards/Ecma-335.htm">ECMA-335</a>, with the syntax coming from <a href="https://www.ecma-international.org/publications/standards/Ecma-334.htm">ECMA-334</a> (C#). An <em>attribute</em> is a
general, free-form metadatum that is interpreted according to name, convention,
and language and compiler version. Attributes may appear as any of:</p>
<ul>
<li>A single identifier, the attribute name</li>
<li>An identifier followed by the equals sign '=' and a literal, providing a
key/value pair</li>
<li>An identifier followed by a parenthesized literal, providing a
key/value pair</li>
<li>An identifier followed by a parenthesized list of sub-attribute arguments</li>
</ul>
<p><em>Inner attributes</em>, written with a bang (&quot;!&quot;) after the hash (&quot;#&quot;), apply to the
item that the attribute is declared within. <em>Outer attributes</em>, written without
the bang after the hash, apply to the item or generic parameter that follow the
attribute.</p>
<p>An example of attributes:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// General metadata applied to the enclosing module or crate.
#![crate_type = &quot;lib&quot;]

// A function marked as a unit test
#[test]
fn test_foo() {
    /* ... */
}

// A conditionally-compiled module
#[cfg(target_os = &quot;linux&quot;)]
mod bar {
    /* ... */
}

// A lint attribute used to suppress a warning/error
#[allow(non_camel_case_types)]
type int8_t = i8;
#}</code></pre></pre>
<a class="header" href="print.html#crate-only-attributes" id="crate-only-attributes"><h2>Crate-only attributes</h2></a>
<ul>
<li><code>crate_name</code> - specify the crate's crate name.</li>
<li><code>crate_type</code> - see <a href="linkage.html">linkage</a>.</li>
<li><code>no_builtins</code> - disable optimizing certain code patterns to invocations of
library functions that are assumed to exist</li>
<li><code>no_main</code> - disable emitting the <code>main</code> symbol. Useful when some other
object being linked to defines <code>main</code>.</li>
<li><code>no_start</code> - disable linking to the <code>native</code> crate, which specifies the
&quot;start&quot; language item.</li>
<li><code>no_std</code> - disable linking to the <code>std</code> crate.</li>
<li><code>recursion_limit</code> - Sets the maximum depth for potentially
infinitely-recursive compile-time operations like
auto-dereference or macro expansion. The default is
<code>#![recursion_limit=&quot;64&quot;]</code>.</li>
<li><code>windows_subsystem</code> - Indicates that when this crate is linked for a Windows
target it will configure the resulting binary's
<a href="https://msdn.microsoft.com/en-us/library/fcc1zstk.aspx">subsystem</a> via the linker. Valid values for this
attribute are <code>console</code> and <code>windows</code>, corresponding to
those two respective subsystems. More subsystems may be
allowed in the future, and this attribute is ignored on
non-Windows targets.</li>
</ul>
<a class="header" href="print.html#module-only-attributes" id="module-only-attributes"><h2>Module-only attributes</h2></a>
<ul>
<li><code>no_implicit_prelude</code> - disable injecting <code>use std::prelude::*</code> in this
module.</li>
<li><code>path</code> - specifies the file to load the module from. <code>#[path=&quot;foo.rs&quot;] mod bar;</code> is equivalent to <code>mod bar { /* contents of foo.rs */ }</code>. The path is
taken relative to the directory that the current module is in.</li>
</ul>
<a class="header" href="print.html#function-only-attributes" id="function-only-attributes"><h2>Function-only attributes</h2></a>
<ul>
<li><code>test</code> - indicates that this function is a test function, to only be compiled
in case of <code>--test</code>.
<ul>
<li><code>ignore</code> - indicates that this test function is disabled.</li>
</ul>
</li>
<li><code>should_panic</code> - indicates that this test function should panic, inverting the
success condition.</li>
<li><code>cold</code> - The function is unlikely to be executed, so optimize it (and calls
to it) differently.</li>
</ul>
<a class="header" href="print.html#ffi-attributes" id="ffi-attributes"><h2>FFI attributes</h2></a>
<p>On an <code>extern</code> block, the following attributes are interpreted:</p>
<ul>
<li><code>link_args</code> - specify arguments to the linker, rather than just the library
name and type. This is feature gated and the exact behavior is
implementation-defined (due to variety of linker invocation syntax).</li>
<li><code>link</code> - indicate that a native library should be linked to for the
declarations in this block to be linked correctly. <code>link</code> supports an optional
<code>kind</code> key with three possible values: <code>dylib</code>, <code>static</code>, and <code>framework</code>. See
<a href="items/external-blocks.html">external blocks</a> for more about external blocks.
Two examples: <code>#[link(name = &quot;readline&quot;)]</code> and
<code>#[link(name = &quot;CoreFoundation&quot;, kind = &quot;framework&quot;)]</code>.</li>
<li><code>linked_from</code> - indicates what native library this block of FFI items is
coming from. This attribute is of the form <code>#[linked_from = &quot;foo&quot;]</code> where
<code>foo</code> is the name of a library in either <code>#[link]</code> or a <code>-l</code> flag. This
attribute is currently required to export symbols from a Rust dynamic library
on Windows, and it is feature gated behind the <code>linked_from</code> feature.</li>
</ul>
<p>On declarations inside an <code>extern</code> block, the following attributes are
interpreted:</p>
<ul>
<li><code>link_name</code> - the name of the symbol that this function or static should be
imported as.</li>
<li><code>linkage</code> - on a static, this specifies the <a href="http://llvm.org/docs/LangRef.html#linkage-types">linkage
type</a>.</li>
</ul>
<p>See <a href="type-layout.html">type layout</a> for documentation on the <code>repr</code> attribute
which can be used to control type layout.</p>
<a class="header" href="print.html#macro-related-attributes" id="macro-related-attributes"><h2>Macro-related attributes</h2></a>
<ul>
<li>
<p><code>macro_use</code> on a <code>mod</code> — macros defined in this module will be visible in the
module's parent, after this module has been included.</p>
</li>
<li>
<p><code>macro_use</code> on an <code>extern crate</code> — load macros from this crate.  An optional
list of names <code>#[macro_use(foo, bar)]</code> restricts the import to just those
macros named.  The <code>extern crate</code> must appear at the crate root, not inside
<code>mod</code>, which ensures proper function of the <a href="../book/first-edition/macros.html#the-variable-crate"><code>$crate</code> macro
variable</a>.</p>
</li>
<li>
<p><code>macro_reexport</code> on an <code>extern crate</code> — re-export the named macros.</p>
</li>
<li>
<p><code>macro_export</code> - export a macro for cross-crate usage.</p>
</li>
<li>
<p><code>no_link</code> on an <code>extern crate</code> — even if we load this crate for macros, don't
link it into the output.</p>
</li>
</ul>
<p>See the <a href="../book/first-edition/macros.html#scoping-and-macro-importexport">macros section of the first edition of the
book</a> for more
information on macro scope.</p>
<a class="header" href="print.html#miscellaneous-attributes" id="miscellaneous-attributes"><h2>Miscellaneous attributes</h2></a>
<ul>
<li><code>export_name</code> - on statics and functions, this determines the name of the
exported symbol.</li>
<li><code>link_section</code> - on statics and functions, this specifies the section of the
object file that this item's contents will be placed into.</li>
<li><code>no_mangle</code> - on any item, do not apply the standard name mangling. Set the
symbol for this item to its identifier.</li>
</ul>
<a class="header" href="print.html#deprecation" id="deprecation"><h3>Deprecation</h3></a>
<p>The <code>deprecated</code> attribute marks an item as deprecated. It has two optional
fields, <code>since</code> and <code>note</code>.</p>
<ul>
<li><code>since</code> expects a version number, as in <code>#[deprecated(since = &quot;1.4.1&quot;)]</code>
<ul>
<li><code>rustc</code> doesn't know anything about versions, but external tools like
<code>clippy</code> may check the validity of this field.</li>
</ul>
</li>
<li><code>note</code> is a free text field, allowing you to provide an explanation about
the deprecation and preferred alternatives.</li>
</ul>
<p>Only <a href="visibility-and-privacy.html">public items</a> can be given the
<code>#[deprecated]</code> attribute. <code>#[deprecated]</code> on a module is inherited by all
child items of that module.</p>
<p><code>rustc</code> will issue warnings on usage of <code>#[deprecated]</code> items. <code>rustdoc</code> will
show item deprecation, including the <code>since</code> version and <code>note</code>, if available.</p>
<p>Here's an example.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[deprecated(since = &quot;5.2&quot;, note = &quot;foo was rarely used. Users should instead use bar&quot;)]
pub fn foo() {}

pub fn bar() {}
#}</code></pre></pre>
<p>The <a href="https://github.com/rust-lang/rfcs/blob/master/text/1270-deprecation.md">RFC</a> contains motivations and more details.</p>
<a class="header" href="print.html#documentation" id="documentation"><h3>Documentation</h3></a>
<p>The <code>doc</code> attribute is used to document items and fields. <a href="comments.html#doc-comments">Doc comments</a>
are transformed into <code>doc</code> attributes.</p>
<p>See <a href="../rustdoc/the-doc-attribute.html">The Rustdoc Book</a> for reference material on this attribute.</p>
<a class="header" href="print.html#conditional-compilation" id="conditional-compilation"><h3>Conditional compilation</h3></a>
<p>Sometimes one wants to have different compiler outputs from the same code,
depending on build target, such as targeted operating system, or to enable
release builds.</p>
<p>Configuration options are boolean (on or off) and are named either with a
single identifier (e.g. <code>foo</code>) or an identifier and a string (e.g. <code>foo = &quot;bar&quot;</code>;
the quotes are required and spaces around the <code>=</code> are unimportant). Note that
similarly-named options, such as <code>foo</code>, <code>foo=&quot;bar&quot;</code> and <code>foo=&quot;baz&quot;</code> may each be
set or unset independently.</p>
<p>Configuration options are either provided by the compiler or passed in on the
command line using <code>--cfg</code> (e.g. <code>rustc main.rs --cfg foo --cfg 'bar=&quot;baz&quot;'</code>).
Rust code then checks for their presence using the <code>#[cfg(...)]</code> attribute:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// The function is only included in the build when compiling for macOS
#[cfg(target_os = &quot;macos&quot;)]
fn macos_only() {
  // ...
}

// This function is only included when either foo or bar is defined
#[cfg(any(foo, bar))]
fn needs_foo_or_bar() {
  // ...
}

// This function is only included when compiling for a unixish OS with a 32-bit
// architecture
#[cfg(all(unix, target_pointer_width = &quot;32&quot;))]
fn on_32bit_unix() {
  // ...
}

// This function is only included when foo is not defined
#[cfg(not(foo))]
fn needs_not_foo() {
  // ...
}
#}</code></pre></pre>
<p>This illustrates some conditional compilation can be achieved using the
<code>#[cfg(...)]</code> attribute. <code>any</code>, <code>all</code> and <code>not</code> can be used to assemble
arbitrarily complex configurations through nesting.</p>
<p>The following configurations must be defined by the implementation:</p>
<ul>
<li><code>target_arch = &quot;...&quot;</code> - Target CPU architecture, such as <code>&quot;x86&quot;</code>,
<code>&quot;x86_64&quot;</code> <code>&quot;mips&quot;</code>, <code>&quot;powerpc&quot;</code>, <code>&quot;powerpc64&quot;</code>, <code>&quot;arm&quot;</code>, or
<code>&quot;aarch64&quot;</code>. This value is closely related to the first element of
the platform target triple, though it is not identical.</li>
<li><code>target_os = &quot;...&quot;</code> - Operating system of the target, examples
include <code>&quot;windows&quot;</code>, <code>&quot;macos&quot;</code>, <code>&quot;ios&quot;</code>, <code>&quot;linux&quot;</code>, <code>&quot;android&quot;</code>,
<code>&quot;freebsd&quot;</code>, <code>&quot;dragonfly&quot;</code>, <code>&quot;bitrig&quot;</code> , <code>&quot;openbsd&quot;</code> or
<code>&quot;netbsd&quot;</code>. This value is closely related to the second and third
element of the platform target triple, though it is not identical.</li>
<li><code>target_family = &quot;...&quot;</code> - Operating system family of the target, e. g.
<code>&quot;unix&quot;</code> or <code>&quot;windows&quot;</code>. The value of this configuration option is defined
as a configuration itself, like <code>unix</code> or <code>windows</code>.</li>
<li><code>unix</code> - See <code>target_family</code>.</li>
<li><code>windows</code> - See <code>target_family</code>.</li>
<li><code>target_env = &quot;..&quot;</code> - Further disambiguates the target platform with
information about the ABI/libc. Presently this value is either
<code>&quot;gnu&quot;</code>, <code>&quot;msvc&quot;</code>, <code>&quot;musl&quot;</code>, or the empty string. For historical
reasons this value has only been defined as non-empty when needed
for disambiguation. Thus on many GNU platforms this value will be
empty. This value is closely related to the fourth element of the
platform target triple, though it is not identical. For example,
embedded ABIs such as <code>gnueabihf</code> will simply define <code>target_env</code> as
<code>&quot;gnu&quot;</code>.</li>
<li><code>target_endian = &quot;...&quot;</code> - Endianness of the target CPU, either <code>&quot;little&quot;</code> or
<code>&quot;big&quot;</code>.</li>
<li><code>target_pointer_width = &quot;...&quot;</code> - Target pointer width in bits. This is set
to <code>&quot;32&quot;</code> for targets with 32-bit pointers, and likewise set to <code>&quot;64&quot;</code> for
64-bit pointers.</li>
<li><code>target_has_atomic = &quot;...&quot;</code> - Set of integer sizes on which the target can perform
atomic operations. Values are <code>&quot;8&quot;</code>, <code>&quot;16&quot;</code>, <code>&quot;32&quot;</code>, <code>&quot;64&quot;</code> and <code>&quot;ptr&quot;</code>.</li>
<li><code>target_vendor = &quot;...&quot;</code> - Vendor of the target, for example <code>apple</code>, <code>pc</code>, or
simply <code>&quot;unknown&quot;</code>.</li>
<li><code>test</code> - Enabled when compiling the test harness (using the <code>--test</code> flag).</li>
<li><code>debug_assertions</code> - Enabled by default when compiling without optimizations.
This can be used to enable extra debugging code in development but not in
production.  For example, it controls the behavior of the standard library's
<code>debug_assert!</code> macro.</li>
</ul>
<p>You can also set another attribute based on a <code>cfg</code> variable with <code>cfg_attr</code>:</p>
<pre><code class="language-rust ignore">#[cfg_attr(a, b)]
</code></pre>
<p>This is the same as <code>#[b]</code> if <code>a</code> is set by <code>cfg</code>, and nothing otherwise.</p>
<p>Lastly, configuration options can be used in expressions by invoking the <code>cfg!</code>
macro: <code>cfg!(a)</code> evaluates to <code>true</code> if <code>a</code> is set, and <code>false</code> otherwise.</p>
<a class="header" href="print.html#lint-check-attributes" id="lint-check-attributes"><h3>Lint check attributes</h3></a>
<p>A lint check names a potentially undesirable coding pattern, such as
unreachable code or omitted documentation, for the static entity to which the
attribute applies.</p>
<p>For any lint check <code>C</code>:</p>
<ul>
<li><code>allow(C)</code> overrides the check for <code>C</code> so that violations will go
unreported,</li>
<li><code>deny(C)</code> signals an error after encountering a violation of <code>C</code>,</li>
<li><code>forbid(C)</code> is the same as <code>deny(C)</code>, but also forbids changing the lint
level afterwards,</li>
<li><code>warn(C)</code> warns about violations of <code>C</code> but continues compilation.</li>
</ul>
<p>The lint checks supported by the compiler can be found via <code>rustc -W help</code>,
along with their default settings.  <a href="../unstable-book/language-features/plugin.html#lint-plugins">Compiler
plugins</a> can provide additional lint checks.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub mod m1 {
    // Missing documentation is ignored here
    #[allow(missing_docs)]
    pub fn undocumented_one() -&gt; i32 { 1 }

    // Missing documentation signals a warning here
    #[warn(missing_docs)]
    pub fn undocumented_too() -&gt; i32 { 2 }

    // Missing documentation signals an error here
    #[deny(missing_docs)]
    pub fn undocumented_end() -&gt; i32 { 3 }
}
#}</code></pre></pre>
<p>This example shows how one can use <code>allow</code> and <code>warn</code> to toggle a particular
check on and off:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[warn(missing_docs)]
pub mod m2{
    #[allow(missing_docs)]
    pub mod nested {
        // Missing documentation is ignored here
        pub fn undocumented_one() -&gt; i32 { 1 }

        // Missing documentation signals a warning here,
        // despite the allow above.
        #[warn(missing_docs)]
        pub fn undocumented_two() -&gt; i32 { 2 }
    }

    // Missing documentation signals a warning here
    pub fn undocumented_too() -&gt; i32 { 3 }
}
#}</code></pre></pre>
<p>This example shows how one can use <code>forbid</code> to disallow uses of <code>allow</code> for
that lint check:</p>
<pre><pre class="playpen"><code class="language-rust compile_fail">
# #![allow(unused_variables)]
#fn main() {
#[forbid(missing_docs)]
pub mod m3 {
    // Attempting to toggle warning signals an error here
    #[allow(missing_docs)]
    /// Returns 2.
    pub fn undocumented_too() -&gt; i32 { 2 }
}
#}</code></pre></pre>
<a class="header" href="print.html#must_use-attribute" id="must_use-attribute"><h4><code>must_use</code> Attribute</h4></a>
<p>The <code>must_use</code> attribute can be used on user-defined composite types
(<a href="items/structs.html"><code>struct</code>s</a>, <a href="items/enumerations.html"><code>enum</code>s</a>, and <a href="items/unions.html"><code>union</code>s</a>) and <a href="items/functions.html">functions</a>.</p>
<p>When used on user-defined composite types, if the <a href="expressions.html">expression</a> of an
<a href="statements.html#expression-statements">expression statement</a> has that type, then the <code>unused_must_use</code> lint is
violated.</p>
<pre><pre class="playpen"><code class="language-rust">#[must_use]
struct MustUse {
  // some fields
}

# impl MustUse {
#   fn new() -&gt; MustUse { MustUse {} }
# }
#
fn main() {
  // Violates the `unused_must_use` lint.
  MustUse::new();
}
</code></pre></pre>
<p>When used on a function, if the <a href="expressions.html">expression</a> of an
<a href="statements.html#expression-statements">expression statement</a> is a <a href="expressions/call-expr.html">call expression</a> to that function, then the
<code>unused_must_use</code> lint is violated. The exceptions to this is if the return type
of the function is <code>()</code>, <code>!</code>, or a <a href="items/enumerations.html#zero-variant-enums">zero-variant enum</a>, in which case the
attribute does nothing.</p>
<pre><pre class="playpen"><code class="language-rust">#[must_use]
fn five() -&gt; i32 { 5i32 }

fn main() {
  // Violates the unused_must_use lint.
  five();
}
</code></pre></pre>
<p>When used on a function in a trait declaration, then the behavior also applies
when the call expression is a function from an implementation of the trait.</p>
<pre><pre class="playpen"><code class="language-rust">trait Trait {
  #[must_use]
  fn use_me(&amp;self) -&gt; i32;
}

impl Trait for i32 {
  fn use_me(&amp;self) -&gt; i32 { 0i32 }
}

fn main() {
  // Violates the `unused_must_use` lint.
  5i32.use_me();
}
</code></pre></pre>
<p>When used on a function in an implementation, the attribute does nothing.</p>
<blockquote>
<p>Note: Trivial no-op expressions containing the value will not violate the
lint. Examples include wrapping the value in a type that does not implement
<a href="special-types-and-traits.html#drop"><code>Drop</code></a> and then not using that type and being the final expression of a
<a href="expressions/block-expr.html">block expression</a> that is not used.</p>
<pre><pre class="playpen"><code class="language-rust">#[must_use]
fn five() -&gt; i32 { 5i32 }

fn main() {
  // None of these violate the unused_must_use lint.
  (five(),);
  Some(five());
  { five() };
  if true { five() } else { 0i32 };
  match true {
    _ =&gt; five()  
  };
}
</code></pre></pre>
</blockquote>
<blockquote>
<p>Note: It is idiomatic to use a <a href="statements.html#let-statements">let statement</a> with a pattern of <code>_</code>
when a must-used value is purposely discarded.</p>
<pre><pre class="playpen"><code class="language-rust">#[must_use]
fn five() -&gt; i32 { 5i32 }

fn main() {
  // Does not violate the unused_must_use lint.
  let _ = five();
}
</code></pre></pre>
</blockquote>
<p>The <code>must_use</code> attribute may also include a message by using
<code>#[must_use = &quot;message&quot;]</code>. The message will be given alongside the warning.</p>
<a class="header" href="print.html#inline-attribute" id="inline-attribute"><h3>Inline attribute</h3></a>
<p>The inline attribute suggests that the compiler should place a copy of
the function or static in the caller, rather than generating code to
call the function or access the static where it is defined.</p>
<p>The compiler automatically inlines functions based on internal heuristics.
Incorrectly inlining functions can actually make the program slower, so it
should be used with care.</p>
<p><code>#[inline]</code> and <code>#[inline(always)]</code> always cause the function to be serialized
into the crate metadata to allow cross-crate inlining.</p>
<p>There are three different types of inline attributes:</p>
<ul>
<li><code>#[inline]</code> hints the compiler to perform an inline expansion.</li>
<li><code>#[inline(always)]</code> asks the compiler to always perform an inline expansion.</li>
<li><code>#[inline(never)]</code> asks the compiler to never perform an inline expansion.</li>
</ul>
<a class="header" href="print.html#derive" id="derive"><h3><code>derive</code></h3></a>
<p>The <code>derive</code> attribute allows certain traits to be automatically implemented
for data structures. For example, the following will create an <code>impl</code> for the
<code>PartialEq</code> and <code>Clone</code> traits for <code>Foo</code>, the type parameter <code>T</code> will be given
the <code>PartialEq</code> or <code>Clone</code> constraints for the appropriate <code>impl</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
#[derive(PartialEq, Clone)]
struct Foo&lt;T&gt; {
    a: i32,
    b: T,
}
#}</code></pre></pre>
<p>The generated <code>impl</code> for <code>PartialEq</code> is equivalent to</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct Foo&lt;T&gt; { a: i32, b: T }
impl&lt;T: PartialEq&gt; PartialEq for Foo&lt;T&gt; {
    fn eq(&amp;self, other: &amp;Foo&lt;T&gt;) -&gt; bool {
        self.a == other.a &amp;&amp; self.b == other.b
    }

    fn ne(&amp;self, other: &amp;Foo&lt;T&gt;) -&gt; bool {
        self.a != other.a || self.b != other.b
    }
}
#}</code></pre></pre>
<p>You can implement <code>derive</code> for your own type through <a href="procedural-macros.html">procedural macros</a>.</p>
<a class="header" href="print.html#statements-and-expressions" id="statements-and-expressions"><h1>Statements and expressions</h1></a>
<p>Rust is <em>primarily</em> an expression language. This means that most forms of
value-producing or effect-causing evaluation are directed by the uniform syntax
category of <em>expressions</em>. Each kind of expression can typically <em>nest</em> within
each other kind of expression, and rules for evaluation of expressions involve
specifying both the value produced by the expression and the order in which its
sub-expressions are themselves evaluated.</p>
<p>In contrast, statements in Rust serve <em>mostly</em> to contain and explicitly
sequence expression evaluation.</p>
<a class="header" href="print.html#statements" id="statements"><h1>Statements</h1></a>
<p>A <em>statement</em> is a component of a <a href="expressions/block-expr.html">block</a>, which is in turn a component of an
outer <a href="expressions.html">expression</a> or <a href="items/functions.html">function</a>.</p>
<p>Rust has two kinds of statement: <a href="print.html#declaration-statements">declaration
statements</a> and <a href="print.html#expression-statements">expression
statements</a>.</p>
<a class="header" href="print.html#declaration-statements" id="declaration-statements"><h2>Declaration statements</h2></a>
<p>A <em>declaration statement</em> is one that introduces one or more <em>names</em> into the
enclosing statement block. The declared names may denote new variables or new
<a href="items.html">items</a>.</p>
<p>The two kinds of declaration statements are item declarations and <code>let</code>
statements.</p>
<a class="header" href="print.html#item-declarations" id="item-declarations"><h3>Item declarations</h3></a>
<p>An <em>item declaration statement</em> has a syntactic form identical to an
<a href="items.html">item declaration</a> within a <a href="items/modules.html">module</a>. Declaring an item within a statement
block restricts its scope to the block containing the statement. The item is not
given a <a href="paths.html#canonical-paths">canonical path</a> nor are any sub-items it may declare. The exception to
this is that associated items defined by <a href="items/implementations.html">implementations</a> are still accessible
in outer scopes as long as the item and, if applicable, trait are accessible.
It is otherwise identical in meaning to declaring the item inside a module.</p>
<p>There is no implicit capture of the containing function's generic parameters,
parameters, and local variables. For example, <code>inner</code> may not access
<code>outer_var</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn outer() {
  let outer_var = true;

  fn inner() { /* outer_var is not in scope here */ }

  inner();
}
#}</code></pre></pre>
<a class="header" href="print.html#let-statements" id="let-statements"><h3><code>let</code> statements</h3></a>
<p>A <em><code>let</code> statement</em> introduces a new set of variables, given by a pattern. The
pattern may be followed by a type annotation, and/or an initializer expression.
When no type annotation is given, the compiler will infer the type, or signal
an error if insufficient type information is available for definite inference.
Any variables introduced by a variable declaration are visible from the point of
declaration until the end of the enclosing block scope.</p>
<a class="header" href="print.html#expression-statements" id="expression-statements"><h2>Expression statements</h2></a>
<p>An <em>expression statement</em> is one that evaluates an <a href="expressions.html">expression</a> and ignores its
result. As a rule, an expression statement's purpose is to trigger the effects
of evaluating its expression.</p>
<p>An expression that consists of only a <a href="expressions/block-expr.html">block expression</a> or control flow
expression, if used in a context where a statement is permitted, can omit the
trailing semicolon. This can cause an ambiguity between it being parsed as a
standalone statement and as a part of another expression; in this case, it is
parsed as a statement.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let mut v = vec![1, 2, 3];
v.pop();          // Ignore the element returned from pop
if v.is_empty() {
    v.push(5);
} else {
    v.remove(0);
}                 // Semicolon can be omitted.
[1];              // Separate expression statement, not an indexing expression.
#}</code></pre></pre>
<p>When the trailing semicolon is omitted, the result must be type <code>()</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// bad: the block's type is i32, not ()
// Error: expected `()` because of default return type
// if true {
//   1
// }

// good: the block's type is i32
if true {
  1
} else {
  2
};
#}</code></pre></pre>
<a class="header" href="print.html#expressions" id="expressions"><h1>Expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>Expression</em> :<br />
      <a href="expressions/literal-expr.html"><em>LiteralExpression</em></a><br />
   | <a href="expressions/path-expr.html"><em>PathExpression</em></a><br />
   | <a href="expressions/block-expr.html"><em>BlockExpression</em></a><br />
   | <a href="expressions/operator-expr.html"><em>OperatorExpression</em></a><br />
   | <a href="expressions/grouped-expr.html"><em>GroupedExpression</em></a><br />
   | <a href="expressions/array-expr.html"><em>ArrayExpression</em></a><br />
   | <a href="expressions/array-expr.html#array-and-slice-indexing-expressions"><em>IndexExpression</em></a><br />
   | <a href="expressions/tuple-expr.html"><em>TupleExpression</em></a><br />
   | <a href="expressions/tuple-expr.html#tuple-indexing-expressions"><em>TupleIndexingExpression</em></a><br />
   | <a href="expressions/struct-expr.html"><em>StructExpression</em></a><br />
   | <a href="expressions/enum-variant-expr.html"><em>EnumerationVariantExpression</em></a><br />
   | <a href="expressions/call-expr.html"><em>CallExpression</em></a><br />
   | <a href="expressions/method-call-expr.html"><em>MethodCallExpression</em></a><br />
   | <a href="expressions/field-expr.html"><em>FieldExpression</em></a><br />
   | <a href="expressions/closure-expr.html"><em>ClosureExpression</em></a><br />
   | <a href="expressions/loop-expr.html"><em>LoopExpression</em></a><br />
   | <a href="expressions/loop-expr.html#continue-expressions"><em>ContinueExpression</em></a><br />
   | <a href="expressions/loop-expr.html#break-expressions"><em>BreakExpression</em></a><br />
   | <a href="expressions/range-expr.html"><em>RangeExpression</em></a><br />
   | <a href="expressions/if-expr.html#if-expressions"><em>IfExpression</em></a><br />
   | <a href="expressions/if-expr.html#if-let-expressions"><em>IfLetExpression</em></a><br />
   | <a href="expressions/match-expr.html"><em>MatchExpression</em></a><br />
   | <a href="expressions/return-expr.html"><em>ReturnExpression</em></a></p>
</blockquote>
<p>An expression may have two roles: it always produces a <em>value</em>, and it may have
<em>effects</em> (otherwise known as &quot;side effects&quot;). An expression <em>evaluates to</em> a
value, and has effects during <em>evaluation</em>. Many expressions contain
sub-expressions (operands). The meaning of each kind of expression dictates
several things:</p>
<ul>
<li>Whether or not to evaluate the sub-expressions when evaluating the expression</li>
<li>The order in which to evaluate the sub-expressions</li>
<li>How to combine the sub-expressions' values to obtain the value of the
expression</li>
</ul>
<p>In this way, the structure of expressions dictates the structure of execution.
Blocks are just another kind of expression, so blocks, statements, expressions,
and blocks again can recursively nest inside each other to an arbitrary depth.</p>
<a class="header" href="print.html#expression-precedence" id="expression-precedence"><h2>Expression precedence</h2></a>
<p>The precedence of Rust operators and expressions is ordered as follows, going
from strong to weak. Binary Operators at the same precedence level are grouped
in the order given by their associativity.</p>
<table><thead><tr><th> Operator/Expression         </th><th> Associativity       </th></tr></thead><tbody>
<tr><td> Paths                       </td><td>                     </td></tr>
<tr><td> Method calls                </td><td>                     </td></tr>
<tr><td> Field expressions           </td><td> left to right       </td></tr>
<tr><td> Function calls, array indexing </td><td>                  </td></tr>
<tr><td> <code>?</code>                         </td><td>                     </td></tr>
<tr><td> Unary <code>-</code> <code>*</code> <code>!</code> <code>&amp;</code> <code>&amp;mut</code> </td><td>                    </td></tr>
<tr><td> <code>as</code>                        </td><td> left to right       </td></tr>
<tr><td> <code>*</code> <code>/</code> <code>%</code>                 </td><td> left to right       </td></tr>
<tr><td> <code>+</code> <code>-</code>                     </td><td> left to right       </td></tr>
<tr><td> <code>&lt;&lt;</code> <code>&gt;&gt;</code>                   </td><td> left to right       </td></tr>
<tr><td> <code>&amp;</code>                         </td><td> left to right       </td></tr>
<tr><td> <code>^</code>                         </td><td> left to right       </td></tr>
<tr><td> <code>|</code>         </td><td> left to right       </td></tr>
<tr><td> <code>==</code> <code>!=</code> <code>&lt;</code> <code>&gt;</code> <code>&lt;=</code> <code>&gt;=</code> </td><td> Require parentheses </td></tr>
<tr><td> <code>&amp;&amp;</code>                        </td><td> left to right       </td></tr>
<tr><td> <code>||</code>   </td><td> left to right       </td></tr>
<tr><td> <code>..</code> <code>..=</code>                  </td><td> Require parentheses </td></tr>
<tr><td> <code>=</code> <code>+=</code> <code>-=</code> <code>*=</code> <code>/=</code> <code>%=</code> <br> <code>&amp;=</code> <code>|=</code> <code>^=</code> <code>&lt;&lt;=</code> <code>&gt;&gt;=</code> </td><td> right to left </td></tr>
<tr><td> <code>return</code> <code>break</code> closures   </td><td>                     </td></tr>
</tbody></table>
<a class="header" href="print.html#place-expressions-and-value-expressions" id="place-expressions-and-value-expressions"><h2>Place Expressions and Value Expressions</h2></a>
<p>Expressions are divided into two main categories: place expressions and
value expressions. Likewise within each expression, sub-expressions may occur
in either place context or value context. The evaluation of an expression
depends both on its own category and the context it occurs within.</p>
<p>A <em>place expression</em> is an expression that represents a memory location. These
expressions are <a href="expressions/path-expr.html">paths</a> which refer to local variables, <a href="items/static-items.html">static variables</a>,
<a href="expressions/operator-expr.html#the-dereference-operator">dereferences</a> (<code>*expr</code>), <a href="expressions/array-expr.html#array-and-slice-indexing-expressions">array indexing</a> expressions (<code>expr[expr]</code>),
<a href="expressions/field-expr.html">field</a> references (<code>expr.f</code>) and parenthesized place expressions. All other
expressions are value expressions.</p>
<p>A <em>value expression</em> is an expression that represents an actual value.</p>
<p>The left operand of an <a href="expressions/operator-expr.html#assignment-expressions">assignment</a> or <a href="expressions/operator-expr.html#compound-assignment-expressions">compound assignment</a> expression
is a place expression context, as is the single operand of a unary <a href="expressions/operator-expr.html#borrow-operators">borrow</a>, and
the operand of any <a href="print.html#implicit-borrows">implicit borrow</a>. The discriminant or subject of a
<a href="expressions/match-expr.html">match expression</a> and right side of a <a href="statements.html#let-statements">let statement</a> is also a place
expression context. All other expression contexts are value expression contexts.</p>
<blockquote>
<p>Note: Historically, place expressions were called <em>lvalues</em> and value
expressions were called <em>rvalues</em>.</p>
</blockquote>
<a class="header" href="print.html#moved-and-copied-types" id="moved-and-copied-types"><h3>Moved and copied types</h3></a>
<p>When a place expression is evaluated in a value expression context, or is bound
by value in a pattern, it denotes the value held <em>in</em> that memory location. If
the type of that value implements <a href="special-types-and-traits.html#copy"><code>Copy</code></a>, then the value will be copied. In
the remaining situations if that type is <a href="special-types-and-traits.html#sized"><code>Sized</code></a>, then it may be possible to
move the value. Only the following place expressions may be moved out of:</p>
<ul>
<li><a href="variables.html">Variables</a> which are not currently borrowed.</li>
<li><a href="print.html#temporary-lifetimes">Temporary values</a>.</li>
<li><a href="expressions/field-expr.html">Fields</a> of a place expression which can be moved out of and
doesn't implement <a href="special-types-and-traits.html#drop"><code>Drop</code></a>.</li>
<li>The result of <a href="expressions/operator-expr.html#the-dereference-operator">dereferencing</a> an expression with type <a href="../std/boxed/struct.Box.html"><code>Box&lt;T&gt;</code></a> and that can
also be moved out of.</li>
</ul>
<p>Moving out of a place expression that evaluates to a local variable, the
location is deinitialized and cannot be read from again until it is
reinitialized. In all other cases, trying to use a place expression in a value
expression context is an error.</p>
<a class="header" href="print.html#mutability" id="mutability"><h3>Mutability</h3></a>
<p>For a place expression to be <a href="expressions/operator-expr.html#assignment-expressions">assigned</a> to, mutably <a href="expressions/operator-expr.html#borrow-operators">borrowed</a>,
<a href="print.html#implicit-borrows">implicitly mutably borrowed</a>, or bound to a pattern containing <code>ref mut</code> it
must be <em>mutable</em>. We call these <em>mutable place expressions</em>. In contrast,
other place expressions are called <em>immutable place expressions</em>.</p>
<p>The following expressions can be mutable place expression contexts:</p>
<ul>
<li>Mutable <a href="variables.html">variables</a>, which are not currently borrowed.</li>
<li><a href="items/static-items.html#mutable-statics">Mutable <code>static</code> items</a>.</li>
<li><a href="print.html#temporary-lifetimes">Temporary values</a>.</li>
<li><a href="expressions/field-expr.html">Fields</a>, this evaluates the subexpression in a mutable place
expression context.</li>
<li><a href="expressions/operator-expr.html#the-dereference-operator">Dereferences</a> of a <code>*mut T</code> pointer.</li>
<li>Dereference of a variable, or field of a variable, with type <code>&amp;mut T</code>. Note:
This is an exception to the requirement of the next rule.</li>
<li>Dereferences of a type that implements <code>DerefMut</code>, this then requires that
the value being dereferenced is evaluated is a mutable place expression context.</li>
<li><a href="expressions/array-expr.html#array-and-slice-indexing-expressions">Array indexing</a> of a type that implements <code>DerefMut</code>, this
then evaluates the value being indexed, but not the index, in mutable place
expression context.</li>
</ul>
<a class="header" href="print.html#temporary-lifetimes" id="temporary-lifetimes"><h3>Temporary lifetimes</h3></a>
<p>When using a value expression in most place expression contexts, a temporary
unnamed memory location is created initialized to that value and the expression
evaluates to that location instead, except if promoted to <code>'static</code>. Promotion
of a value expression to a <code>'static</code> slot occurs when the expression could be
written in a constant, borrowed, and dereferencing that borrow where the
expression was the originally written, without changing the runtime behavior.
That is, the promoted expression can be evaluated at compile-time and the
resulting value does not contain <a href="interior-mutability.html">interior mutability</a> or <a href="destructors.html">destructors</a> (these
properties are determined based on the value where possible, e.g. <code>&amp;None</code>
always has the type <code>&amp;'static Option&lt;_&gt;</code>, as it contains nothing disallowed).
Otherwise, the lifetime of temporary values is typically</p>
<ul>
<li>the innermost enclosing statement; the tail expression of a block is
considered part of the statement that encloses the block, or</li>
<li>the condition expression or the loop conditional expression if the
temporary is created in the condition expression of an <code>if</code> or in the loop
conditional expression of a <code>while</code> expression.</li>
</ul>
<p>When a temporary value expression is being created that is assigned into a
<a href="statements.html#let-statements"><code>let</code> declaration</a>, however, the temporary is created with the lifetime of
the enclosing block instead, as using the enclosing <a href="statements.html#let-statements"><code>let</code> declaration</a>
would be a guaranteed error (since a pointer to the temporary
would be stored into a variable, but the temporary would be freed before the
variable could be used). The compiler uses simple syntactic rules to decide
which values are being assigned into a <code>let</code> binding, and therefore deserve a
longer temporary lifetime.</p>
<p>Here are some examples:</p>
<ul>
<li><code>let x = foo(&amp;temp())</code>. The expression <code>temp()</code> is a value expression. As it
is being borrowed, a temporary is created which will be freed after
the innermost enclosing statement; in this case, the <code>let</code> declaration.</li>
<li><code>let x = temp().foo()</code>. This is the same as the previous example,
except that the value of <code>temp()</code> is being borrowed via autoref on a
method-call. Here we are assuming that <code>foo()</code> is an <code>&amp;self</code> method
defined in some trait, say <code>Foo</code>. In other words, the expression
<code>temp().foo()</code> is equivalent to <code>Foo::foo(&amp;temp())</code>.</li>
<li><code>let x = if foo(&amp;temp()) {bar()} else {baz()};</code>. The expression <code>temp()</code> is
a value expression. As the temporary is created in the condition expression
of an <code>if</code>, it will be freed at the end of the condition expression;
in this example before the call to <code>bar</code> or <code>baz</code> is made.</li>
<li><code>let x = if temp().must_run_bar {bar()} else {baz()};</code>.
Here we assume the type of <code>temp()</code> is a struct with a boolean field
<code>must_run_bar</code>. As the previous example, the temporary corresponding to
<code>temp()</code> will be freed at the end of the condition expression.</li>
<li><code>while foo(&amp;temp()) {bar();}</code>. The temporary containing the return value from
the call to <code>temp()</code> is created in the loop conditional expression. Hence it
will be freed at the end of the loop conditional expression; in this example
before the call to <code>bar</code> if the loop body is executed.</li>
<li><code>let x = &amp;temp()</code>. Here, the same temporary is being assigned into
<code>x</code>, rather than being passed as a parameter, and hence the
temporary's lifetime is considered to be the enclosing block.</li>
<li><code>let x = SomeStruct { foo: &amp;temp() }</code>. As in the previous case, the
temporary is assigned into a struct which is then assigned into a
binding, and hence it is given the lifetime of the enclosing block.</li>
<li><code>let x = [ &amp;temp() ]</code>. As in the previous case, the
temporary is assigned into an array which is then assigned into a
binding, and hence it is given the lifetime of the enclosing block.</li>
<li><code>let ref x = temp()</code>. In this case, the temporary is created using a ref
binding, but the result is the same: the lifetime is extended to the enclosing
block.</li>
</ul>
<a class="header" href="print.html#implicit-borrows" id="implicit-borrows"><h3>Implicit Borrows</h3></a>
<p>Certain expressions will treat an expression as a place expression by implicitly
borrowing it. For example, it is possible to compare two unsized [slices] for
equality directly, because the <code>==</code> operator implicitly borrows it's operands:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let c = [1, 2, 3];
# let d = vec![1, 2, 3];
let a: &amp;[i32];
let b: &amp;[i32];
# a = &amp;c;
# b = &amp;d;
// ...
*a == *b;
// Equivalent form:
::std::cmp::PartialEq::eq(&amp;*a, &amp;*b);
#}</code></pre></pre>
<p>Implicit borrows may be taken in the following expressions:</p>
<ul>
<li>Left operand in <a href="expressions/method-call-expr.html">method-call</a> expressions.</li>
<li>Left operand in <a href="expressions/field-expr.html">field</a> expressions.</li>
<li>Left operand in <a href="expressions/call-expr.html">call expressions</a>.</li>
<li>Left operand in <a href="expressions/array-expr.html#array-and-slice-indexing-expressions">array indexing</a> expressions.</li>
<li>Operand of the <a href="expressions/operator-expr.html#the-dereference-operator">dereference operator</a> (<code>*</code>).</li>
<li>Operands of <a href="expressions/operator-expr.html#comparison-operators">comparison</a>.</li>
<li>Left operands of the <a href="expressions/operator-expr.html#compound-assignment-expressions">compound assignment</a>.</li>
</ul>
<a class="header" href="print.html#constant-expressions" id="constant-expressions"><h2>Constant expressions</h2></a>
<p>Certain types of expressions can be evaluated at compile time. These are called
<em>constant expressions</em>. Certain places, such as in
<a href="items/constant-items.html">constants</a> and <a href="items/static-items.html">statics</a>,
require a constant expression, and are always evaluated at compile time. In
other places, such as in <a href="statements.html#let-statements"><code>let</code> statements</a>,
constant expressions may be evaluated at compile time. If errors, such as out
of bounds <a href="expressions/array-expr.html#array-and-slice-indexing-expressions">array indexing</a> or <a href="expressions/operator-expr.html#overflow">overflow</a> occurs,
then it is a compiler error if the value must be evaluated at compile time,
otherwise it is just a warning, but the code will most likely panic when run.</p>
<p>The following expressions are constant expressions, so long as any operands are
also constant expressions and do not cause any <a href="destructors.html"><code>Drop::drop</code></a> calls
to be ran.</p>
<ul>
<li><a href="expressions/literal-expr.html">Literals</a>.</li>
<li><a href="expressions/path-expr.html">Paths</a> to <a href="items/functions.html">functions</a> and constants.
Recursively defining constants is not allowed.</li>
<li><a href="expressions/tuple-expr.html">Tuple expressions</a>.</li>
<li><a href="expressions/array-expr.html">Array expressions</a>.</li>
<li><a href="expressions/struct-expr.html">Struct</a> expressions.</li>
<li><a href="expressions/enum-variant-expr.html">Enum variant</a> expressions.</li>
<li><a href="expressions/block-expr.html">Block expressions</a>, including <code>unsafe</code> blocks, which only contain items and
possibly a constant tail expression.</li>
<li><a href="expressions/field-expr.html">Field</a> expressions.</li>
<li>Index expressions, <a href="expressions/array-expr.html#array-and-slice-indexing-expressions">array indexing</a> or <a href="types.html#array-and-slice-types">slice</a> with a <code>usize</code>.</li>
<li><a href="expressions/range-expr.html">Range expressions</a>.</li>
<li><a href="expressions/closure-expr.html">Closure expressions</a> which don't capture variables from the environment.</li>
<li>Built in <a href="expressions/operator-expr.html#negation-operators">negation</a>, <a href="expressions/operator-expr.html#arithmetic-and-logical-binary-operators">arithmetic, logical</a>, <a href="expressions/operator-expr.html#comparison-operators">comparison</a> or <a href="expressions/operator-expr.html#lazy-boolean-operators">lazy boolean</a>
operators used on integer and floating point types, <code>bool</code> and <code>char</code>.</li>
<li>Shared <a href="expressions/operator-expr.html#borrow-operators">borrow</a>s, except if applied to a type with <a href="interior-mutability.html">interior mutability</a>.</li>
<li>The <a href="expressions/operator-expr.html#the-dereference-operator">dereference operator</a>.</li>
<li><a href="expressions/grouped-expr.html">Grouped</a> expressions.</li>
<li><a href="expressions/operator-expr.html#type-cast-expressions">Cast</a> expressions, except pointer to address and
function pointer to address casts.</li>
</ul>
<a class="header" href="print.html#overloading-traits" id="overloading-traits"><h2>Overloading Traits</h2></a>
<p>Many of the following operators and expressions can also be overloaded for
other types using traits in <code>std::ops</code> or <code>std::cmp</code>. These traits also
exist in <code>core::ops</code> and <code>core::cmp</code> with the same names.</p>
<a class="header" href="print.html#literal-expressions" id="literal-expressions"><h1>Literal expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>LiteralExpression</em> :<br />
      <a href="tokens.html#character-literals">CHAR_LITERAL</a><br />
   | <a href="tokens.html#string-literals">STRING_LITERAL</a><br />
   | <a href="tokens.html#raw-string-literals">RAW_STRING_LITERAL</a><br />
   | <a href="tokens.html#byte-literals">BYTE_LITERAL</a><br />
   | <a href="tokens.html#byte-string-literals">BYTE_STRING_LITERAL</a><br />
   | <a href="tokens.html#raw-byte-string-literals">RAW_BYTE_STRING_LITERAL</a><br />
   | <a href="tokens.html#integer-literals">INTEGER_LITERAL</a><br />
   | <a href="tokens.html#floating-point-literals">FLOAT_LITERAL</a><br />
   | <a href="tokens.html#boolean-literals">BOOLEAN_LITERAL</a></p>
</blockquote>
<p>A <em>literal expression</em> consists of one of the <a href="tokens.html#literals">literal</a>
forms described earlier. It directly describes a number, character, string,
or boolean value.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
&quot;hello&quot;;   // string type
'5';       // character type
5;         // integer type
#}</code></pre></pre>
<a class="header" href="print.html#path-expressions" id="path-expressions"><h1>Path expressions</h1></a>
<p>A <a href="paths.html">path</a> used as an expression context denotes either a local
variable or an item. Path expressions that resolve to local or static variables
are <a href="expressions.html#place-expressions-and-value-expressions">place expressions</a>, other paths are <a href="expressions.html#place-expressions-and-value-expressions">value expressions</a>. Using a
<a href="items/static-items.html#mutable-statics"><code>static mut</code></a> variable requires an <a href="expressions/block-expr.html#unsafe-blocks"><code>unsafe</code> block</a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# mod globals {
#     pub static STATIC_VAR: i32 = 5;
#     pub static mut STATIC_MUT_VAR: i32 = 7;
# }
# let local_var = 3;
local_var;
globals::STATIC_VAR;
unsafe { globals::STATIC_MUT_VAR };
let some_constructor = Some::&lt;i32&gt;;
let push_integer = Vec::&lt;i32&gt;::push;
let slice_reverse = &lt;[i32]&gt;::reverse;
#}</code></pre></pre>
<a class="header" href="print.html#block-expressions" id="block-expressions"><h1>Block expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>BlockExpression</em> :<br />
   <code>{</code><br />
      <a href="attributes.html"><em>InnerAttribute</em></a><sup>*</sup><br />
      <a href="statements.html"><em>Statement</em></a><sup>*</sup><br />
      <a href="expressions.html"><em>Expression</em></a><sup>?</sup><br />
   <code>}</code></p>
</blockquote>
<p>A <em>block expression</em> is similar to a module in terms of the declarations that
are possible, but can also contain <a href="statements.html">statements</a> and end with
an <a href="expressions.html">expression</a>. Each block conceptually introduces a new namespace scope. Use
items can bring new names into scopes and declared items are in scope for only
the block itself.</p>
<p>A block will execute each statement sequentially, and then execute the
expression, if given. If the block doesn't end in an expression, its value is
<code>()</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x: () = { println!(&quot;Hello.&quot;); };
#}</code></pre></pre>
<p>If it ends in an expression, its value and type are that of the expression:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x: i32 = { println!(&quot;Hello.&quot;); 5 };

assert_eq!(5, x);
#}</code></pre></pre>
<p>Blocks are always <a href="expressions.html#place-expressions-and-value-expressions">value expressions</a> and evaluate the last expression in
value expression context. This can be used to force moving a value if really
needed.</p>
<a class="header" href="print.html#unsafe-blocks" id="unsafe-blocks"><h2><code>unsafe</code> blocks</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>UnsafeBlockExpression</em> :<br />
   <code>unsafe</code> <em>BlockExpression</em></p>
</blockquote>
<p><em>See <a href="unsafe-blocks.html"><code>unsafe</code> block</a> for more information on when to use <code>unsafe</code></em></p>
<p>A block of code can be prefixed with the <code>unsafe</code> keyword, to permit calling
<code>unsafe</code> functions or dereferencing raw pointers within a safe function. Examples:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
unsafe {
    let b = [13u8, 17u8];
    let a = &amp;b[0] as *const u8;
    assert_eq!(*a, 13);
    assert_eq!(*a.offset(1), 17);
}

# unsafe fn f() -&gt; i32 { 10 }
let a = unsafe { f() };
#}</code></pre></pre>
<a class="header" href="print.html#operator-expressions" id="operator-expressions"><h1>Operator expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>OperatorExpression</em> :<br />
      <a href="print.html#borrow-operators"><em>BorrowExpression</em></a><br />
   | <a href="print.html#the-dereference-operator"><em>DereferenceExpression</em></a><br />
   | <a href="print.html#the-question-mark-operator"><em>ErrorPropagationExpression</em></a><br />
   | <a href="print.html#negation-operators"><em>NegationExpression</em></a><br />
   | <a href="print.html#arithmetic-and-logical-binary-operators"><em>ArithmeticOrLogicalExpression</em></a><br />
   | <a href="print.html#comparison-operators"><em>ComparisonExpression</em></a><br />
   | <a href="print.html#lazy-boolean-operators"><em>LazyBooleanExpression</em></a><br />
   | <a href="print.html#type-cast-expressions"><em>TypeCastExpression</em></a><br />
   | <a href="print.html#assignment-expressions"><em>AssignmentExpression</em></a><br />
   | <a href="print.html#compound-assignment-expressions"><em>CompoundAssignmentExpression</em></a></p>
</blockquote>
<p>Operators are defined for built in types by the Rust language. Many of the
following operators can also be overloaded using traits in <code>std::ops</code> or
<code>std::cmp</code>.</p>
<a class="header" href="print.html#overflow" id="overflow"><h2>Overflow</h2></a>
<p>Integer operators will panic when they overflow when compiled in debug mode.
The <code>-C debug-assertions</code> and <code>-C overflow-checks</code> compiler flags can be used
to control this more directly. The following things are considered to be
overflow:</p>
<ul>
<li>When <code>+</code>, <code>*</code> or <code>-</code> create a value greater than the maximum value, or less
than the minimum value that can be stored. This includes unary <code>-</code> on the
smallest value of any signed integer type.</li>
<li>Using <code>/</code> or <code>%</code>, where the left-hand argument is the smallest integer of a
signed integer type and the right-hand argument is <code>-1</code>.</li>
<li>Using <code>&lt;&lt;</code> or <code>&gt;&gt;</code> where the right-hand argument is greater than or equal to
the number of bits in the type of the left-hand argument, or is negative.</li>
</ul>
<a class="header" href="print.html#borrow-operators" id="borrow-operators"><h2>Borrow operators</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>BorrowExpression</em> :<br />
      (<code>&amp;</code>|<code>&amp;&amp;</code>) <a href="expressions.html"><em>Expression</em></a><br />
   | (<code>&amp;</code>|<code>&amp;&amp;</code>) <code>mut</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>The <code>&amp;</code> (shared borrow) and <code>&amp;mut</code> (mutable borrow) operators are unary prefix
operators. When applied to a <a href="expressions.html#place-expressions-and-value-expressions">place expression</a>, this expressions produces a
reference (pointer) to the location that the value refers to. The memory
location is also placed into a borrowed state for the duration of the reference.
For a shared borrow (<code>&amp;</code>), this implies that the place may not be mutated, but
it may be read or shared again. For a mutable borrow (<code>&amp;mut</code>), the place may not
be accessed in any way until the borrow expires. <code>&amp;mut</code> evaluates its operand in
a mutable place expression context. If the <code>&amp;</code> or <code>&amp;mut</code> operators are applied
to a <a href="expressions.html#place-expressions-and-value-expressions">value expression</a>, then a <a href="expressions.html#temporary-lifetimes">temporary value</a> is created.</p>
<p>These operators cannot be overloaded.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
{
    // a temporary with value 7 is created that lasts for this scope.
    let shared_reference = &amp;7;
}
let mut array = [-2, 3, 9];
{
    // Mutably borrows `array` for this scope.
    // `array` may only be used through `mutable_reference`.
    let mutable_reference = &amp;mut array;
}
#}</code></pre></pre>
<p>Even though <code>&amp;&amp;</code> is a single token (<a href="print.html#lazy-boolean-operators">the lazy 'and' operator</a>),
when used in the context of borrow expressions it works as two borrows:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// same meanings:
let a = &amp;&amp;  10;
let a = &amp; &amp; 10;

// same meanings:
let a = &amp;&amp;&amp;&amp;  mut 10;
let a = &amp;&amp; &amp;&amp; mut 10;
let a = &amp; &amp; &amp; &amp; mut 10;
#}</code></pre></pre>
<a class="header" href="print.html#the-dereference-operator" id="the-dereference-operator"><h2>The dereference operator</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>DereferenceExpression</em> :<br />
   <code>*</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>The <code>*</code> (dereference) operator is also a unary prefix operator. When applied to
a <a href="types.html#pointer-types">pointer</a> it denotes the pointed-to location. If
the expression is of type <code>&amp;mut T</code> and <code>*mut T</code>, and is either a local
variable, a (nested) field of a local variable or is a mutable <a href="expressions.html#place-expressions-and-value-expressions">place
expression</a>, then the resulting memory location can be assigned to.
Dereferencing a raw pointer requires <code>unsafe</code>.</p>
<p>On non-pointer types <code>*x</code> is equivalent to <code>*std::ops::Deref::deref(&amp;x)</code> in an
<a href="expressions.html#mutability">immutable place expression context</a> and
<code>*std::ops::Deref::deref_mut(&amp;mut x)</code> in a mutable place expression context.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = &amp;7;
assert_eq!(*x, 7);
let y = &amp;mut 9;
*y = 11;
assert_eq!(*y, 11);
#}</code></pre></pre>
<a class="header" href="print.html#the-question-mark-operator" id="the-question-mark-operator"><h2>The question mark operator</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ErrorPropagationExpression</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>?</code></p>
</blockquote>
<p>The question mark operator (<code>?</code>) unwraps valid values or returns erroneous
values, propagating them to the calling function. It is a unary postfix
operator that can only be applied to the types <code>Result&lt;T, E&gt;</code> and <code>Option&lt;T&gt;</code>.</p>
<p>When applied to values of the <code>Result&lt;T, E&gt;</code> type, it propagates errors. If
the value is <code>Err(e)</code>, then it will return <code>Err(From::from(e))</code> from the
enclosing function or closure. If applied to <code>Ok(x)</code>, then it will unwrap the
value to evaluate to <code>x</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# use std::num::ParseIntError;
fn try_to_parse() -&gt; Result&lt;i32, ParseIntError&gt; {
    let x: i32 = &quot;123&quot;.parse()?; // x = 123
    let y: i32 = &quot;24a&quot;.parse()?; // returns an Err() immediately
    Ok(x + y)                    // Doesn't run.
}

let res = try_to_parse();
println!(&quot;{:?}&quot;, res);
# assert!(res.is_err())
#}</code></pre></pre>
<p>When applied to values of the <code>Option&lt;T&gt;</code> type, it propagates <code>Nones</code>. If the
value is <code>None</code>, then it will return <code>None</code>. If applied to <code>Some(x)</code>, then it
will unwrap the value to evaluate to <code>x</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn try_option_some() -&gt; Option&lt;u8&gt; {
    let val = Some(1)?;
    Some(val)
}
assert_eq!(try_option_some(), Some(1));

fn try_option_none() -&gt; Option&lt;u8&gt; {
    let val = None?;
    Some(val)
}
assert_eq!(try_option_none(), None);
#}</code></pre></pre>
<p><code>?</code> cannot be overloaded.</p>
<a class="header" href="print.html#negation-operators" id="negation-operators"><h2>Negation operators</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>NegationExpression</em> :<br />
      <code>-</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <code>!</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>These are the last two unary operators. This table summarizes the behavior of
them on primitive types and which traits are used to overload these operators
for other types. Remember that signed integers are always represented using
two's complement. The operands of all of these operators are evaluated in
<a href="expressions.html#place-expressions-and-value-expressions">value expression context</a> so are moved or copied.</p>
<table><thead><tr><th> Symbol </th><th> Integer     </th><th> <code>bool</code>      </th><th> Floating Point </th><th> Overloading Trait  </th></tr></thead><tbody>
<tr><td> <code>-</code>    </td><td> Negation*   </td><td>             </td><td> Negation       </td><td> <code>std::ops::Neg</code>    </td></tr>
<tr><td> <code>!</code>    </td><td> Bitwise NOT </td><td> Logical NOT </td><td>                </td><td> <code>std::ops::Not</code>    </td></tr>
</tbody></table>
<p>* Only for signed integer types.</p>
<p>Here are some example of these operators</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = 6;
assert_eq!(-x, -6);
assert_eq!(!x, -7);
assert_eq!(true, !false);
#}</code></pre></pre>
<a class="header" href="print.html#arithmetic-and-logical-binary-operators" id="arithmetic-and-logical-binary-operators"><h2>Arithmetic and Logical Binary Operators</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ArithmeticOrLogicalExpression</em> :<br />
      <a href="expressions.html"><em>Expression</em></a> <code>+</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>-</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>*</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>/</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>%</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&amp;</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>|</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>^</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&lt;&lt;</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&gt;&gt;</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>Binary operators expressions are all written with infix notation. This table
summarizes the behavior of arithmetic and logical binary operators on
primitive types and which traits are used to overload these operators for other
types. Remember that signed integers are always represented using two's
complement. The operands of all of these operators are evaluated in <a href="expressions.html#place-expressions-and-value-expressions">value
expression context</a> so are moved or copied.</p>
<table><thead><tr><th> Symbol </th><th> Integer                 </th><th> <code>bool</code>      </th><th> Floating Point </th><th> Overloading Trait  </th></tr></thead><tbody>
<tr><td> <code>+</code>    </td><td> Addition                </td><td>             </td><td> Addition       </td><td> <code>std::ops::Add</code>    </td></tr>
<tr><td> <code>-</code>    </td><td> Subtraction             </td><td>             </td><td> Subtraction    </td><td> <code>std::ops::Sub</code>    </td></tr>
<tr><td> <code>*</code>    </td><td> Multiplication          </td><td>             </td><td> Multiplication </td><td> <code>std::ops::Mul</code>    </td></tr>
<tr><td> <code>/</code>    </td><td> Division*                </td><td>             </td><td> Division       </td><td> <code>std::ops::Div</code>    </td></tr>
<tr><td> <code>%</code>    </td><td> Remainder               </td><td>             </td><td> Remainder      </td><td> <code>std::ops::Rem</code>    </td></tr>
<tr><td> <code>&amp;</code>    </td><td> Bitwise AND             </td><td> Logical AND </td><td>                </td><td> <code>std::ops::BitAnd</code> </td></tr>
<tr><td> <code>|</code> </td><td> Bitwise OR </td><td> Logical OR  </td><td>                </td><td> <code>std::ops::BitOr</code>  </td></tr>
<tr><td> <code>^</code>    </td><td> Bitwise XOR             </td><td> Logical XOR </td><td>                </td><td> <code>std::ops::BitXor</code> </td></tr>
<tr><td> <code>&lt;&lt;</code>   </td><td> Left Shift              </td><td>             </td><td>                </td><td> <code>std::ops::Shl</code>    </td></tr>
<tr><td> <code>&gt;&gt;</code>   </td><td> Right Shift**            </td><td>             </td><td>                </td><td> <code>std::ops::Shr</code>    </td></tr>
</tbody></table>
<p>* Integer division rounds towards zero.</p>
<p>** Arithmetic right shift on signed integer types, logical right shift on
unsigned integer types.</p>
<p>Here are examples of these operators being used.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
assert_eq!(3 + 6, 9);
assert_eq!(5.5 - 1.25, 4.25);
assert_eq!(-5 * 14, -70);
assert_eq!(14 / 3, 4);
assert_eq!(100 % 7, 2);
assert_eq!(0b1010 &amp; 0b1100, 0b1000);
assert_eq!(0b1010 | 0b1100, 0b1110);
assert_eq!(0b1010 ^ 0b1100, 0b110);
assert_eq!(13 &lt;&lt; 3, 104);
assert_eq!(-10 &gt;&gt; 2, -3);
#}</code></pre></pre>
<a class="header" href="print.html#comparison-operators" id="comparison-operators"><h2>Comparison Operators</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ComparisonExpression</em> :<br />
      <a href="expressions.html"><em>Expression</em></a> <code>==</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>!=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&gt;</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&lt;</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&gt;=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&lt;=</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>Comparison operators are also defined both for primitive types and many type in
the standard library. Parentheses are required when chaining comparison
operators. For example, the expression <code>a == b == c</code> is invalid and may be
written as <code>(a == b) == c</code>.</p>
<p>Unlike arithmetic and logical operators, the traits for
overloading the operators the traits for these operators are used more
generally to show how a type may be compared and will likely be assumed to
define actual comparisons by functions that use these traits as bounds. Many
functions and macros in the standard library can then use that assumption
(although not to ensure safety). Unlike the arithmetic and logical operators
above, these operators implicitly take shared borrows of their operands,
evaluating them in <a href="expressions.html#place-expressions-and-value-expressions">place expression context</a>:</p>
<pre><code class="language-rust ignore">a == b;
// is equivalent to
::std::cmp::PartialEq::eq(&amp;a, &amp;b);
</code></pre>
<p>This means that the operands don't have to be moved out of.</p>
<table><thead><tr><th> Symbol </th><th> Meaning                  </th><th> Overloading method         </th></tr></thead><tbody>
<tr><td> <code>==</code>   </td><td> Equal                    </td><td> <code>std::cmp::PartialEq::eq</code>  </td></tr>
<tr><td> <code>!=</code>   </td><td> Not equal                </td><td> <code>std::cmp::PartialEq::ne</code>  </td></tr>
<tr><td> <code>&gt;</code>    </td><td> Greater than             </td><td> <code>std::cmp::PartialOrd::gt</code> </td></tr>
<tr><td> <code>&lt;</code>    </td><td> Less than                </td><td> <code>std::cmp::PartialOrd::lt</code> </td></tr>
<tr><td> <code>&gt;=</code>   </td><td> Greater than or equal to </td><td> <code>std::cmp::PartialOrd::ge</code> </td></tr>
<tr><td> <code>&lt;=</code>   </td><td> Less than or equal to    </td><td> <code>std::cmp::PartialOrd::le</code> </td></tr>
</tbody></table>
<p>Here are examples of the comparison operators being used.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
assert!(123 == 123);
assert!(23 != -12);
assert!(12.5 &gt; 12.2);
assert!([1, 2, 3] &lt; [1, 3, 4]);
assert!('A' &lt;= 'B');
assert!(&quot;World&quot; &gt;= &quot;Hello&quot;);
#}</code></pre></pre>
<a class="header" href="print.html#lazy-boolean-operators" id="lazy-boolean-operators"><h2>Lazy boolean operators</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>LazyBooleanExpression</em> :<br />
      <a href="expressions.html"><em>Expression</em></a> <code>||</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&amp;&amp;</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>The operators <code>||</code> and <code>&amp;&amp;</code> may be applied to operands of boolean type. The
<code>||</code> operator denotes logical 'or', and the <code>&amp;&amp;</code> operator denotes logical
'and'. They differ from <code>|</code> and <code>&amp;</code> in that the right-hand operand is only
evaluated when the left-hand operand does not already determine the result of
the expression. That is, <code>||</code> only evaluates its right-hand operand when the
left-hand operand evaluates to <code>false</code>, and <code>&amp;&amp;</code> only when it evaluates to
<code>true</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = false || true; // true
let y = false &amp;&amp; panic!(); // false, doesn't evaluate `panic!()`
#}</code></pre></pre>
<a class="header" href="print.html#type-cast-expressions" id="type-cast-expressions"><h2>Type cast expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>TypeCastExpression</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>as</code> <a href="paths.html"><em>PathInExpression</em></a></p>
</blockquote>
<p>A type cast expression is denoted with the binary operator <code>as</code>.</p>
<p>Executing an <code>as</code> expression casts the value on the left-hand side to the type
on the right-hand side.</p>
<p>An example of an <code>as</code> expression:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# fn sum(values: &amp;[f64]) -&gt; f64 { 0.0 }
# fn len(values: &amp;[f64]) -&gt; i32 { 0 }
fn average(values: &amp;[f64]) -&gt; f64 {
    let sum: f64 = sum(values);
    let size: f64 = len(values) as f64;
    sum / size
}
#}</code></pre></pre>
<p><code>as</code> can be used to explicitly perform <a href="type-coercions.html">coercions</a>, as
well as the following additional casts. Here <code>*T</code> means either <code>*const T</code> or
<code>*mut T</code>.</p>
<table><thead><tr><th> Type of <code>e</code>           </th><th> <code>U</code>                   </th><th> Cast performed by <code>e as U</code>       </th></tr></thead><tbody>
<tr><td> Integer or Float type </td><td> Integer or Float type </td><td> Numeric cast                     </td></tr>
<tr><td> C-like enum           </td><td> Integer type          </td><td> Enum cast                        </td></tr>
<tr><td> <code>bool</code> or <code>char</code>      </td><td> Integer type          </td><td> Primitive to integer cast        </td></tr>
<tr><td> <code>u8</code>                  </td><td> <code>char</code>                </td><td> <code>u8</code> to <code>char</code> cast              </td></tr>
<tr><td> <code>*T</code>                  </td><td> <code>*V</code> where <code>V: Sized</code> * </td><td> Pointer to pointer cast       </td></tr>
<tr><td> <code>*T</code> where <code>T: Sized</code> </td><td> Numeric type          </td><td> Pointer to address cast          </td></tr>
<tr><td> Integer type          </td><td> <code>*V</code> where <code>V: Sized</code> </td><td> Address to pointer cast          </td></tr>
<tr><td> <code>&amp;[T; n]</code>             </td><td> <code>*const T</code>            </td><td> Array to pointer cast            </td></tr>
<tr><td> <a href="types.html#function-pointer-types">Function pointer</a> </td><td> <code>*V</code> where <code>V: Sized</code> </td><td> Function pointer to pointer cast </td></tr>
<tr><td> Function pointer      </td><td> Integer               </td><td> Function pointer to address cast </td></tr>
<tr><td> Closure **          </td><td> Function pointer      </td><td> Closure to function pointer cast </td></tr>
</tbody></table>
<p>* or <code>T</code> and <code>V</code> are compatible unsized types, e.g., both slices, both the
same trait object.</p>
<p>** only for closures that do capture (close over) any local variables</p>
<a class="header" href="print.html#semantics" id="semantics"><h3>Semantics</h3></a>
<ul>
<li>Numeric cast
<ul>
<li>Casting between two integers of the same size (e.g. i32 -&gt; u32) is a no-op</li>
<li>Casting from a larger integer to a smaller integer (e.g. u32 -&gt; u8) will
truncate</li>
<li>Casting from a smaller integer to a larger integer (e.g. u8 -&gt; u32) will
<ul>
<li>zero-extend if the source is unsigned</li>
<li>sign-extend if the source is signed</li>
</ul>
</li>
<li>Casting from a float to an integer will round the float towards zero
<ul>
<li><strong><a href="https://github.com/rust-lang/rust/issues/10184">NOTE: currently this will cause Undefined Behavior if the rounded
value cannot be represented by the target integer type</a></strong>.
This includes Inf and NaN. This is a bug and will be fixed.</li>
</ul>
</li>
<li>Casting from an integer to float will produce the floating point
representation of the integer, rounded if necessary (rounding strategy
unspecified)</li>
<li>Casting from an f32 to an f64 is perfect and lossless</li>
<li>Casting from an f64 to an f32 will produce the closest possible value
(rounding strategy unspecified)
<ul>
<li><strong><a href="https://github.com/rust-lang/rust/issues/15536">NOTE: currently this will cause Undefined Behavior if the value
is finite but larger or smaller than the largest or smallest finite
value representable by f32</a></strong>. This is a bug and will
be fixed.</li>
</ul>
</li>
</ul>
</li>
<li>Enum cast
<ul>
<li>Casts an enum to its discriminant, then uses a numeric cast if needed.</li>
</ul>
</li>
<li>Primitive to integer cast
<ul>
<li><code>false</code> casts to <code>0</code>, <code>true</code> casts to <code>1</code></li>
<li><code>char</code> casts to the value of the code point, then uses a numeric cast if needed.</li>
</ul>
</li>
<li><code>u8</code> to <code>char</code> cast
<ul>
<li>Casts to the <code>char</code> with the corresponding code point.</li>
</ul>
</li>
</ul>
<a class="header" href="print.html#assignment-expressions" id="assignment-expressions"><h2>Assignment expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>AssignmentExpression</em> :<br />
   | <a href="expressions.html"><em>Expression</em></a> <code>=</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>An <em>assignment expression</em> consists of a <a href="expressions.html#place-expressions-and-value-expressions">place expression</a> followed by an
equals sign (<code>=</code>) and a <a href="expressions.html#place-expressions-and-value-expressions">value expression</a>. Such an expression always has
the <a href="types.html#tuple-types"><code>unit</code> type</a>.</p>
<p>Evaluating an assignment expression <a href="destructors.html">drops</a> the left-hand
operand, unless it's an uninitialized local variable or field of a local variable,
and <a href="expressions.html#moved-and-copied-types">either copies or moves</a> its
right-hand operand to its left-hand operand. The left-hand operand must be a
place expression: using a value expression results in a compiler error, rather
than promoting it to a temporary.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let mut x = 0;
# let y = 0;
x = y;
#}</code></pre></pre>
<a class="header" href="print.html#compound-assignment-expressions" id="compound-assignment-expressions"><h2>Compound assignment expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>CompoundAssignmentExpression</em> :<br />
      <a href="expressions.html"><em>Expression</em></a> <code>+=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>-=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>*=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>/=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>%=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&amp;=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>|=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>^=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&lt;&lt;=</code> <a href="expressions.html"><em>Expression</em></a><br />
   | <a href="expressions.html"><em>Expression</em></a> <code>&gt;&gt;=</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>The <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code>, <code>&amp;</code>, <code>|</code>, <code>^</code>, <code>&lt;&lt;</code>, and <code>&gt;&gt;</code> operators may be
composed with the <code>=</code> operator. The expression <code>place_exp OP= value</code> is
equivalent to <code>place_expr = place_expr OP val</code>. For example, <code>x = x + 1</code> may be
written as <code>x += 1</code>. Any such expression always has the <a href="types.html#tuple-types"><code>unit</code> type</a>.
These operators can all be overloaded using the trait with the same name as for
the normal operation followed by 'Assign', for example, <code>std::ops::AddAssign</code>
is used to overload <code>+=</code>. As with <code>=</code>, <code>place_expr</code> must be a <a href="expressions.html#place-expressions-and-value-expressions">place
expression</a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut x = 10;
x += 4;
assert_eq!(x, 14);
#}</code></pre></pre>
<a class="header" href="print.html#grouped-expressions" id="grouped-expressions"><h1>Grouped expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>GroupedExpression</em> :<br />
   <code>(</code> <a href="expressions.html"><em>Expression</em></a> <code>)</code></p>
</blockquote>
<p>An expression enclosed in parentheses evaluates to the result of the enclosed
expression. Parentheses can be used to explicitly specify evaluation order
within an expression.</p>
<p>An example of a parenthesized expression:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x: i32 = 2 + 3 * 4;
let y: i32 = (2 + 3) * 4;
assert_eq!(x, 14);
assert_eq!(y, 20);
#}</code></pre></pre>
<p>An example of a necessary use of parentheses is when calling a function pointer
that is a member of a struct:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct A {
#    f: fn() -&gt; &amp;'static str
# }
# impl A {
#    fn f(&amp;self) -&gt; &amp;'static str {
#        &quot;The method f&quot;
#    }
# }
# let a = A{f: || &quot;The field f&quot;};
# 
assert_eq!( a.f (), &quot;The method f&quot;);
assert_eq!((a.f)(), &quot;The field f&quot;);
#}</code></pre></pre>
<a class="header" href="print.html#array-and-array-index-expressions" id="array-and-array-index-expressions"><h1>Array and array index expressions</h1></a>
<a class="header" href="print.html#array-expressions" id="array-expressions"><h2>Array expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ArrayExpression</em> :<br />
      <code>[</code>  <code>]</code><br />
   | <code>[</code> <a href="expressions.html"><em>Expression</em></a> ( <code>,</code> <a href="expressions.html"><em>Expression</em></a> )<sup>*</sup> <code>,</code><sup>?</sup> <code>]</code><br />
   | <code>[</code> <a href="expressions.html"><em>Expression</em></a> <code>;</code> <a href="expressions.html"><em>Expression</em></a> <code>]</code></p>
</blockquote>
<p>An <em><a href="types.html#array-and-slice-types">array</a> expression</em> can be written by
enclosing zero or more comma-separated expressions of uniform type in square
brackets. This produces and array containing each of these values in the
order they are written.</p>
<p>Alternatively there can be exactly two expressions inside the brackets,
separated by a semi-colon. The expression after the <code>;</code> must be a have type
<code>usize</code> and be a <a href="expressions.html#constant-expressions">constant expression</a>,
such as a <a href="tokens.html#literals">literal</a> or a <a href="items/constant-items.html">constant
item</a>. <code>[a; b]</code> creates an array containing <code>b</code>
copies of the value of <code>a</code>. If the expression after the semi-colon has a value
greater than 1 then this requires that the type of <code>a</code> is
<a href="special-types-and-traits.html#copy"><code>Copy</code></a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
[1, 2, 3, 4];
[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];
[0; 128];              // array with 128 zeros
[0u8, 0u8, 0u8, 0u8,];
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // 2D array
#}</code></pre></pre>
<a class="header" href="print.html#array-and-slice-indexing-expressions" id="array-and-slice-indexing-expressions"><h2>Array and slice indexing expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>IndexExpression</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>[</code> <a href="expressions.html"><em>Expression</em></a> <code>]</code></p>
</blockquote>
<p><a href="types.html#array-and-slice-types">Array and slice</a>-typed expressions can be
indexed by writing a square-bracket-enclosed expression of type <code>usize</code> (the
index) after them. When the array is mutable, the resulting <a href="expressions.html#place-expressions-and-value-expressions">memory location</a>
can be assigned to.</p>
<p>For other types an index expression <code>a[b]</code> is equivalent to
<code>*std::ops::Index::index(&amp;a, b)</code>, or
<code>*std::ops::IndexMut::index_mut(&amp;mut a, b)</code> in a mutable place expression
context. Just as with methods, Rust will also insert dereference operations on
<code>a</code> repeatedly to find an implementation.</p>
<p>Indices are zero-based for arrays and slices. Array access is a <a href="expressions.html#constant-expressions">constant
expression</a>, so bounds can be checked at compile-time with a constant index
value. Otherwise a check will be performed at run-time that will put the thread
in a <em>panicked state</em> if it fails.</p>
<pre><pre class="playpen"><code class="language-rust should_panic">
# #![allow(unused_variables)]
#fn main() {
// lint is deny by default.
#![warn(const_err)]

([1, 2, 3, 4])[2];        // Evaluates to 3

let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
b[1][2];                  // multidimensional array indexing

let x = ([&quot;a&quot;, &quot;b&quot;])[10]; // warning: index out of bounds

let n = 10;
let y = ([&quot;a&quot;, &quot;b&quot;])[n];  // panics

let arr = [&quot;a&quot;, &quot;b&quot;];
arr[10];                  // warning: index out of bounds
#}</code></pre></pre>
<p>The array index expression can be implemented for types other than arrays and slices
by implementing the <a href="../std/ops/trait.Index.html">Index</a> and <a href="../std/ops/trait.IndexMut.html">IndexMut</a> traits.</p>
<a class="header" href="print.html#tuple-and-tuple-indexing-expressions" id="tuple-and-tuple-indexing-expressions"><h1>Tuple and tuple indexing expressions</h1></a>
<a class="header" href="print.html#tuple-expressions" id="tuple-expressions"><h2>Tuple expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>TupleExpression</em> :<br />
      <code>(</code> <code>)</code><br />
   | <code>(</code> ( <a href="expressions.html"><em>Expression</em></a> <code>,</code> )<sup>+</sup> <a href="expressions.html"><em>Expression</em></a><sup>?</sup> <code>)</code></p>
</blockquote>
<p>Tuples are written by enclosing zero or more comma-separated expressions in
parentheses. They are used to create <a href="types.html#tuple-types">tuple-typed</a>
values.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
(0.0, 4.5);
(&quot;a&quot;, 4usize, true);
();
#}</code></pre></pre>
<p>You can disambiguate a single-element tuple from a value in parentheses with a
comma:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
(0,); // single-element tuple
(0); // zero in parentheses
#}</code></pre></pre>
<a class="header" href="print.html#tuple-indexing-expressions" id="tuple-indexing-expressions"><h2>Tuple indexing expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>TupleIndexingExpression</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>.</code> <a href="tokens.html#integer-literals">TUPLE_INDEX</a></p>
</blockquote>
<p><a href="types.html#tuple-types">Tuples</a> and <a href="items/structs.html">struct tuples</a> can be
indexed using the number corresponding to the position of the field. The index
must be written as a <a href="tokens.html#integer-literals">decimal literal</a> with no
underscores or suffix. Tuple indexing expressions also differ from field
expressions in that they can unambiguously be called as a function. In all
other aspects they have the same behavior.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct Point(f32, f32);
let pair = (1, 2);
assert_eq!(pair.1, 2);
let unit_x = Point(1.0, 0.0);
assert_eq!(unit_x.0, 1.0);
#}</code></pre></pre>
<a class="header" href="print.html#struct-expressions" id="struct-expressions"><h1>Struct expressions</h1></a>
<p>There are several forms of struct expressions. A <em>struct expression</em> consists
of the <a href="paths.html">path</a> of a <a href="items/structs.html">struct item</a>, followed by a
brace-enclosed list of zero or more comma-separated name-value pairs, providing
the field values of a new instance of the struct. A field name can be any
<a href="identifiers.html">identifier</a>, and is separated from its value expression by a
colon. In the case of a tuple struct the field names are numbers corresponding
to the position of the field. The numbers must be written in decimal,
containing no underscores and with no leading zeros or integer suffix. A value
of a <a href="items/unions.html">union</a> type can also be created using this syntax,
except that it must specify exactly one field.</p>
<p>Struct expressions can't be used directly in the head of a <a href="expressions/loop-expr.html">loop</a>
or an <a href="expressions/if-expr.html#if-expressions">if</a>, <a href="expressions/if-expr.html#if-let-expressions">if let</a> or <a href="expressions/match-expr.html">match</a> expression. But struct expressions can still be
in used inside parentheses, for example.</p>
<p>A <em>tuple struct expression</em> consists of the path of a struct item, followed by
a parenthesized list of one or more comma-separated expressions (in other
words, the path of a struct item followed by a tuple expression). The struct
item must be a tuple struct item.</p>
<p>A <em>unit-like struct expression</em> consists only of the path of a struct item.</p>
<p>The following are examples of struct expressions:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct Point { x: f64, y: f64 }
# struct NothingInMe { }
# struct TuplePoint(f64, f64);
# mod game { pub struct User&lt;'a&gt; { pub name: &amp;'a str, pub age: u32, pub score: usize } }
# struct Cookie; fn some_fn&lt;T&gt;(t: T) {}
Point {x: 10.0, y: 20.0};
NothingInMe {};
TuplePoint(10.0, 20.0);
TuplePoint { 0: 10.0, 1: 20.0 }; // Results in the same value as the above line
let u = game::User {name: &quot;Joe&quot;, age: 35, score: 100_000};
some_fn::&lt;Cookie&gt;(Cookie);
#}</code></pre></pre>
<p>A struct expression forms a new value of the named struct type. Note that for a
given <em>unit-like</em> struct type, this will always be the same value.</p>
<p>A struct expression can terminate with the syntax <code>..</code> followed by an
expression to denote a functional update. The expression following <code>..</code> (the
base) must have the same struct type as the new struct type being formed. The
entire expression denotes the result of constructing a new struct (with the
same type as the base expression) with the given values for the fields that
were explicitly specified and the values in the base expression for all other
fields. Just as with all struct expressions, all of the fields of the struct
must be <a href="visibility-and-privacy.html">visible</a>, even those not explicitly
named.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct Point3d { x: i32, y: i32, z: i32 }
let base = Point3d {x: 1, y: 2, z: 3};
Point3d {y: 0, z: 10, .. base};
#}</code></pre></pre>
<a class="header" href="print.html#struct-field-init-shorthand" id="struct-field-init-shorthand"><h2>Struct field init shorthand</h2></a>
<p>When initializing a data structure (struct, enum, union) with named (but not
numbered) fields, it is allowed to write <code>fieldname</code> as a shorthand for
<code>fieldname: fieldname</code>. This allows a compact syntax with less duplication.</p>
<p>Example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# struct Point3d { x: i32, y: i32, z: i32 }
# let x = 0;
# let y_value = 0;
# let z = 0;
Point3d { x: x, y: y_value, z: z };
Point3d { x, y: y_value, z };
#}</code></pre></pre>
<a class="header" href="print.html#enumeration-variant-expressions" id="enumeration-variant-expressions"><h1>Enumeration Variant expressions</h1></a>
<p>Enumeration variants can be constructed similarly to structs, using a path to
an enum variant instead of to a struct:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# enum Message {
#     Quit,
#     WriteString(String),
#     Move { x: i32, y: i32 },
# }
let q = Message::Quit;
let w = Message::WriteString(&quot;Some string&quot;.to_string());
let m = Message::Move { x: 50, y: 200 };
#}</code></pre></pre>
<a class="header" href="print.html#call-expressions" id="call-expressions"><h1>Call expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>CallExpression</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>(</code> <em>CallParams</em><sup>?</sup> <code>)</code></p>
<p><em>CallParams</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> ( <code>,</code> <a href="expressions.html"><em>Expression</em></a> )<sup>*</sup> <code>,</code><sup>?</sup></p>
</blockquote>
<p>A <em>call expression</em> consists of an expression followed by a parenthesized
expression-list. It invokes a function, providing zero or more input variables.
If the function eventually returns, then the expression completes. For
<a href="types.html#function-item-types">non-function types</a>, the expression f(...) uses
the method on one of the <a href="../std/ops/trait.Fn.html"><code>std::ops::Fn</code></a>, <a href="../std/ops/trait.FnMut.html"><code>std::ops::FnMut</code></a> or
<a href="../std/ops/trait.FnOnce.html"><code>std::ops::FnOnce</code></a> traits, which differ in whether they take the type by
reference, mutable reference, or take ownership respectively. An automatic
borrow will be taken if needed. Rust will also automatically dereference <code>f</code> as
required. Some examples of call expressions:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# fn add(x: i32, y: i32) -&gt; i32 { 0 }
let three: i32 = add(1i32, 2i32);
let name: &amp;'static str = (|| &quot;Rust&quot;)();
#}</code></pre></pre>
<a class="header" href="print.html#disambiguating-function-calls" id="disambiguating-function-calls"><h2>Disambiguating Function Calls</h2></a>
<p>Rust treats all function calls as sugar for a more explicit, fully-qualified
syntax. Upon compilation, Rust will desugar all function calls into the explicit
form. Rust may sometimes require you to qualify function calls with trait,
depending on the ambiguity of a call in light of in-scope items.</p>
<blockquote>
<p><strong>Note</strong>: In the past, the Rust community used the terms &quot;Unambiguous
Function Call Syntax&quot;, &quot;Universal Function Call Syntax&quot;, or &quot;UFCS&quot;, in
documentation, issues, RFCs, and other community writings. However, the term
lacks descriptive power and potentially confuses the issue at hand. We mention
it here for searchability's sake.</p>
</blockquote>
<p>Several situations often occur which result in ambiguities about the receiver or
referent of method or associated function calls. These situations may include:</p>
<ul>
<li>Multiple in-scope traits define methods with the same name for the same types</li>
<li>Auto-<code>deref</code> is undesirable; for example, distinguishing between methods on a
smart pointer itself and the pointer's referent</li>
<li>Methods which take no arguments, like <code>default()</code>, and return properties of a
type, like <code>size_of()</code></li>
</ul>
<p>To resolve the ambiguity, the programmer may refer to their desired method or
function using more specific paths, types, or traits.</p>
<p>For example,</p>
<pre><pre class="playpen"><code class="language-rust">trait Pretty {
    fn print(&amp;self);
}

trait Ugly {
  fn print(&amp;self);
}

struct Foo;
impl Pretty for Foo {
    fn print(&amp;self) {}
}

struct Bar;
impl Pretty for Bar {
    fn print(&amp;self) {}
}
impl Ugly for Bar{
    fn print(&amp;self) {}
}

fn main() {
    let f = Foo;
    let b = Bar;

    // we can do this because we only have one item called `print` for `Foo`s
    f.print();
    // more explicit, and, in the case of `Foo`, not necessary
    Foo::print(&amp;f);
    // if you're not into the whole brevity thing
    &lt;Foo as Pretty&gt;::print(&amp;f);

    // b.print(); // Error: multiple 'print' found
    // Bar::print(&amp;b); // Still an error: multiple `print` found

    // necessary because of in-scope items defining `print`
    &lt;Bar as Pretty&gt;::print(&amp;b);
}
</code></pre></pre>
<p>Refer to <a href="https://github.com/rust-lang/rfcs/blob/master/text/0132-ufcs.md">RFC 132</a> for further details and motivations.</p>
<a class="header" href="print.html#method-call-expressions" id="method-call-expressions"><h1>Method-call expressions</h1></a>
<p>A <em>method call</em> consists of an expression (the <em>receiver</em>) followed by a single
dot, an <a href="identifiers.html">identifier</a>, and a parenthesized expression-list. Method calls are
resolved to associated <a href="items/associated-items.html#methods">methods</a> on specific traits, either statically
dispatching to a method if the exact <code>self</code>-type of the left-hand-side is known,
or dynamically dispatching if the left-hand-side expression is an indirect
<a href="types.html#trait-objects">trait object</a>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let pi: Result&lt;f32, _&gt; = &quot;3.14&quot;.parse();
let log_pi = pi.unwrap_or(1.0).log(2.72);
# assert!(1.14 &lt; log_pi &amp;&amp; log_pi &lt; 1.15)
#}</code></pre></pre>
<p>When looking up a method call, the receiver may be automatically dereferenced or
borrowed in order to call a method. This requires a more complex lookup process
than for other functions, since there may be a number of possible methods to
call. The following procedure is used:</p>
<p>The first step is to build a list of candidate receiver types. Obtain
these by repeatedly <a href="expressions/operator-expr.html#the-dereference-operator">dereferencing</a> the receiver expression's type,
adding each type encountered to the list, then finally attempting an [unsized
coercion] at the end, and adding the result type if that is successful. Then,
for each candidate <code>T</code>, add <code>&amp;T</code> and <code>&amp;mut T</code> to the list immediately after <code>T</code>.</p>
<p>For instance, if the receiver has type <code>Box&lt;[i32;2]&gt;</code>, then the candidate types
will be <code>Box&lt;[i32;2]&gt;</code>, <code>&amp;Box&lt;[i32;2]&gt;</code>, <code>&amp;mut Box&lt;[i32;2]&gt;</code>, <code>[i32; 2]</code> (by
dereferencing), <code>&amp;[i32; 2]</code>, <code>&amp;mut [i32; 2]</code>, <code>[i32]</code> (by unsized coercion),
<code>&amp;[i32]</code>, and finally <code>&amp;mut [i32]</code>.</p>
<p>Then, for each candidate type <code>T</code>, search for a <a href="visibility-and-privacy.html">visible</a> method with
a receiver of that type in the following places:</p>
<ol>
<li><code>T</code>'s inherent methods (methods implemented directly on <code>T</code>).</li>
<li>Any of the methods provided by a <a href="visibility-and-privacy.html">visible</a> trait implemented by <code>T</code>. If <code>T</code>
is a type parameter, methods provided by trait bounds on <code>T</code> are looked up
first. Then all remaining methods in scope are looked up.</li>
</ol>
<blockquote>
<p>Note: the lookup is done for each type in order, which can occasionally lead
to surprising results. The below code will print &quot;In trait impl!&quot;, because
<code>&amp;self</code> methods are looked up first, the trait method is found before the
struct's <code>&amp;mut self</code> method is found.</p>
<pre><pre class="playpen"><code class="language-rust">struct Foo {}

trait Bar {
  fn bar(&amp;self);
}

impl Foo {
  fn bar(&amp;mut self) {
    println!(&quot;In struct impl!&quot;)
  }
}

impl Bar for Foo {
  fn bar(&amp;self) {
    println!(&quot;In trait impl!&quot;)
  }
}

fn main() {
  let mut f = Foo{};
  f.bar();
}
</code></pre></pre>
</blockquote>
<p>If this results in multiple possible candidates, then it is an error, and the
receiver must be <a href="expressions/call-expr.html#disambiguating-function-calls">converted</a> to an appropriate receiver type
to make the method call.</p>
<p>This process does not take into account the mutability or lifetime of the
receiver, or whether a method is <code>unsafe</code>. Once a method is looked up, if it
can't be called for one (or more) of those reasons, the result is a compiler
error.</p>
<p>If a step is reached where there is more than one possible method, such as where
generic methods or traits are considered the same, then it is a compiler
error. These cases require a <a href="expressions/call-expr.html#disambiguating-function-calls">disambiguating function call syntax</a> for method
and function invocation.</p>
<blockquote>
<p>Warning: For <a href="types.html#trait-objects">trait objects</a>, if there is an inherent method of the same name
as a trait method, it will give a compiler error when trying to call the
method in a method call expression. Instead, you can call the method using
<a href="expressions/call-expr.html#disambiguating-function-calls">disambiguating function call syntax</a>, in which case it calls the trait
method, not the inherent method. There is no way to call the inherent method.
Just don't define inherent methods on trait objects with the same name a trait
method and you'll be fine.</p>
</blockquote>
<a class="header" href="print.html#field-access-expressions" id="field-access-expressions"><h1>Field access expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>FieldExpression</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>.</code> <a href="identifiers.html">IDENTIFIER</a></p>
</blockquote>
<p>A <em>field expression</em> consists of an expression followed by a single dot and an
<a href="identifiers.html">identifier</a>, when not immediately followed by a parenthesized expression-list
(the latter is always a <a href="expressions/method-call-expr.html">method call expression</a>). A field expression denotes a
field of a <a href="items/structs.html">struct</a> or <a href="items/unions.html">union</a>. To call a function stored in a struct,
parentheses are needed around the field expression.</p>
<pre><code class="language-rust ignore">mystruct.myfield;
foo().x;
(Struct {a: 10, b: 20}).a;
mystruct.method();          // Method expression
(mystruct.function_field)() // Call expression containing a field expression
</code></pre>
<p>A field access is a <a href="expressions.html#place-expressions-and-value-expressions">place expression</a> referring to the location of that field.
When the subexpression is <a href="expressions.html#mutability">mutable</a>, the field expression is also mutable.</p>
<p>Also, if the type of the expression to the left of the dot is a pointer, it is
automatically dereferenced as many times as necessary to make the field access
possible. In cases of ambiguity, we prefer fewer autoderefs to more.</p>
<p>Finally, the fields of a struct or a reference to a struct are treated as
separate entities when borrowing. If the struct does not implement
<a href="special-types-and-traits.html#drop"><code>Drop</code></a> and is stored in a local variable,
this also applies to moving out of each of its fields. This also does not apply
if automatic dereferencing is done though user defined types.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct A { f1: String, f2: String, f3: String }
let mut x: A;
# x = A {
#     f1: &quot;f1&quot;.to_string(),
#     f2: &quot;f2&quot;.to_string(),
#     f3: &quot;f3&quot;.to_string()
# };
let a: &amp;mut String = &amp;mut x.f1; // x.f1 borrowed mutably
let b: &amp;String = &amp;x.f2;         // x.f2 borrowed immutably
let c: &amp;String = &amp;x.f2;         // Can borrow again
let d: String = x.f3;           // Move out of x.f3
#}</code></pre></pre>
<a class="header" href="print.html#closure-expressions" id="closure-expressions"><h1>Closure expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ClosureExpression</em> :<br />
   <code>move</code><sup>?</sup><br />
   ( <code>||</code> | <code>|</code> <a href="items/functions.html"><em>FunctionParameters</em></a><sup>?</sup> <code>|</code> )<br />
   (<a href="expressions.html"><em>Expression</em></a> | <code>-&gt;</code> <a href="types.html"><em>TypeNoBounds</em></a> <a href="expressions/block-expr.html"><em>BlockExpression</em></a>)</p>
</blockquote>
<p>A <em>closure expression</em> defines a closure and denotes it as a value, in a single
expression. A closure expression is a pipe-symbol-delimited (<code>|</code>) list of
patterns followed by an expression. Type annotations may optionally be added
for the type of the parameters or for the return type. If there is a return
type, the expression used for the body of the closure must be a normal
<a href="expressions/block-expr.html">block</a>. A closure expression also may begin with the
<code>move</code> keyword before the initial <code>|</code>.</p>
<p>A closure expression denotes a function that maps a list of parameters
(<code>ident_list</code>) onto the expression that follows the <code>ident_list</code>. The patterns
in the <code>ident_list</code> are the parameters to the closure. If a parameter's types
is not specified, then the compiler infers it from context. Each closure
expression has a unique anonymous type.</p>
<p>Closure expressions are most useful when passing functions as arguments to other
functions, as an abbreviation for defining and capturing a separate function.</p>
<p>Significantly, closure expressions <em>capture their environment</em>, which regular
<a href="items/functions.html">function definitions</a> do not. Without the <code>move</code>
keyword, the closure expression infers how it captures each variable from its
environment, preferring to capture by shared reference, effectively borrowing
all outer variables mentioned inside the closure's body. If needed the compiler
will infer that instead mutable references should be taken, or that the values
should be moved or copied (depending on their type) from the environment. A
closure can be forced to capture its environment by copying or moving values by
prefixing it with the <code>move</code> keyword. This is often used to ensure that the
closure's type is <code>'static</code>.</p>
<p>The compiler will determine which of the <a href="types.html#closure-types">closure
traits</a> the closure's type will implement by how it
acts on its captured variables. The closure will also implement
<a href="special-types-and-traits.html#send"><code>Send</code></a> and/or
<a href="special-types-and-traits.html#sync"><code>Sync</code></a> if all of its captured types do.
These traits allow functions to accept closures using generics, even though the
exact types can't be named.</p>
<p>In this example, we define a function <code>ten_times</code> that takes a higher-order
function argument, and we then call it with a closure expression as an argument,
followed by a closure expression that moves values from its environment.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn ten_times&lt;F&gt;(f: F) where F: Fn(i32) {
    for index in 0..10 {
        f(index);
    }
}

ten_times(|j| println!(&quot;hello, {}&quot;, j));
// With type annotations
ten_times(|j: i32| -&gt; () { println!(&quot;hello, {}&quot;, j) });

let word = &quot;konnichiwa&quot;.to_owned();
ten_times(move |j| println!(&quot;{}, {}&quot;, word, j));
#}</code></pre></pre>
<a class="header" href="print.html#loops" id="loops"><h1>Loops</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>LoopExpression</em> :<br />
   <a href="print.html#loop-labels"><em>LoopLabel</em></a><sup>?</sup> (<br />
         <a href="print.html#infinite-loops"><em>InfiniteLoopExpression</em></a><br />
      | <a href="print.html#predicate-loops"><em>PredicateLoopExpression</em></a><br />
      | <a href="print.html#predicate-pattern-loops"><em>PredicatePatternLoopExpression</em></a><br />
      | <a href="print.html#iterator-loops"><em>IteratorLoopExpression</em></a><br />
   )</p>
</blockquote>
<p>Rust supports four loop expressions:</p>
<ul>
<li>A <a href="print.html#infinite-loops"><code>loop</code> expression</a> denotes an infinite loop.</li>
<li>A <a href="print.html#predicate-loops"><code>while</code> expression</a> loops until a predicate is false.</li>
<li>A <a href="print.html#predicate-pattern-loops"><code>while let</code> expression</a> tests a refutable pattern.</li>
<li>A <a href="print.html#iterator-loops"><code>for</code> expression</a> extracts values from an iterator,
looping until the iterator is empty.</li>
</ul>
<p>All four types of loop support <a href="print.html#break-expressions"><code>break</code> expressions</a>,
<a href="print.html#continue-expressions"><code>continue</code> expressions</a>, and <a href="print.html#loop-labels">labels</a>.
Only <code>loop</code> supports <a href="print.html#break-and-loop-values">evaluation to non-trivial values</a>.</p>
<a class="header" href="print.html#infinite-loops" id="infinite-loops"><h2>Infinite loops</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>InfiniteLoopExpression</em> :<br />
   <code>loop</code> <a href="expressions/block-expr.html"><em>BlockExpression</em></a></p>
</blockquote>
<p>A <code>loop</code> expression repeats execution of its body continuously:
<code>loop { println!(&quot;I live.&quot;); }</code>.</p>
<p>A <code>loop</code> expression without an associated <code>break</code> expression is diverging and
has type <a href="types.html#never-type"><code>!</code></a>. A <code>loop</code> expression containing
associated <a href="print.html#break-expressions"><code>break</code> expression(s)</a> may terminate, and must
have type compatible with the value of the <code>break</code> expression(s).</p>
<a class="header" href="print.html#predicate-loops" id="predicate-loops"><h2>Predicate loops</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>PredicateLoopExpression</em> :<br />
   <code>while</code> <a href="expressions.html"><em>Expression</em></a><sub>except struct expression</sub> <a href="expressions/block-expr.html"><em>BlockExpression</em></a></p>
</blockquote>
<p>A <code>while</code> loop begins by evaluating the boolean loop conditional expression. If
the loop conditional expression evaluates to <code>true</code>, the loop body block
executes, then control returns to the loop conditional expression. If the loop
conditional expression evaluates to <code>false</code>, the <code>while</code> expression completes.</p>
<p>An example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut i = 0;

while i &lt; 10 {
    println!(&quot;hello&quot;);
    i = i + 1;
}
#}</code></pre></pre>
<a class="header" href="print.html#predicate-pattern-loops" id="predicate-pattern-loops"><h2>Predicate pattern loops</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<a href="print.html#predicate-pattern-loops"><em>PredicatePatternLoopExpression</em></a> :<br />
   <code>while</code> <code>let</code> <em>Pattern</em> <code>=</code> <a href="expressions.html"><em>Expression</em></a><sub>except struct expression</sub>
<a href="expressions/block-expr.html"><em>BlockExpression</em></a></p>
</blockquote>
<p>A <code>while let</code> loop is semantically similar to a <code>while</code> loop but in place of a
condition expression it expects the keyword <code>let</code> followed by a refutable
pattern, an <code>=</code>, an expression and a block expression. If the value of the expression on
the right hand side of the <code>=</code> matches the pattern, the loop body block executes then
control returns to the pattern matching statement. Otherwise, the while
expression completes.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut x = vec![1, 2, 3];

while let Some(y) = x.pop() {
    println!(&quot;y = {}&quot;, y);
}
#}</code></pre></pre>
<a class="header" href="print.html#iterator-loops" id="iterator-loops"><h2>Iterator loops</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>IteratorLoopExpression</em> :<br />
   <code>for</code> <em>Pattern</em> <code>in</code> <a href="expressions.html"><em>Expression</em></a><sub>except struct expression</sub>
<a href="expressions/block-expr.html"><em>BlockExpression</em></a></p>
</blockquote>
<p>A <code>for</code> expression is a syntactic construct for looping over elements provided
by an implementation of <code>std::iter::IntoIterator</code>. If the iterator yields a
value, that value is given the specified name and the body of the loop is
executed, then control returns to the head of the <code>for</code> loop. If the iterator
is empty, the <code>for</code> expression completes.</p>
<p>An example of a <code>for</code> loop over the contents of an array:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let v = &amp;[&quot;apples&quot;, &quot;cake&quot;, &quot;coffee&quot;];

for text in v {
    println!(&quot;I like {}.&quot;, text);
}
#}</code></pre></pre>
<p>An example of a for loop over a series of integers:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut sum = 0;
for n in 1..11 {
    sum += n;
}
assert_eq!(sum, 55);
#}</code></pre></pre>
<a class="header" href="print.html#loop-labels" id="loop-labels"><h2>Loop labels</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>LoopLabel</em> :<br />
   <a href="tokens.html#lifetimes-and-loop-labels">LIFETIME_OR_LABEL</a> <code>:</code></p>
</blockquote>
<p>A loop expression may optionally have a <em>label</em>. The label is written as
a lifetime preceding the loop expression, as in <code>'foo: loop { break 'foo; }</code>,
<code>'bar: while false {}</code>, <code>'humbug: for _ in 0..0 {}</code>.
If a label is present, then labeled <code>break</code> and <code>continue</code> expressions nested
within this loop may exit out of this loop or return control to its head.
See <a href="print.html#break-expressions">break expressions</a> and <a href="print.html#continue-expressions">continue
expressions</a>.</p>
<a class="header" href="print.html#break-expressions" id="break-expressions"><h2><code>break</code> expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>BreakExpression</em> :<br />
   <code>break</code> <a href="tokens.html#lifetimes-and-loop-labels">LIFETIME_OR_LABEL</a><sup>?</sup> <a href="expressions.html"><em>Expression</em></a><sup>?</sup></p>
</blockquote>
<p>When <code>break</code> is encountered, execution of the associated loop body is
immediately terminated, for example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut last = 0;
for x in 1..100 {
    if x &gt; 12 {
        break;
    }
    last = x;
}
assert_eq!(last, 12);
#}</code></pre></pre>
<p>A <code>break</code> expression is normally associated with the innermost <code>loop</code>, <code>for</code> or
<code>while</code> loop enclosing the <code>break</code> expression, but a <a href="print.html#loop-labels">label</a> can
be used to specify which enclosing loop is affected. Example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
'outer: loop {
    while true {
        break 'outer;
    }
}
#}</code></pre></pre>
<p>A <code>break</code> expression is only permitted in the body of a loop, and has one of
the forms <code>break</code>, <code>break 'label</code> or (<a href="print.html#break-and-loop-values">see below</a>)
<code>break EXPR</code> or <code>break 'label EXPR</code>.</p>
<a class="header" href="print.html#continue-expressions" id="continue-expressions"><h2><code>continue</code> expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ContinueExpression</em> :<br />
   <code>continue</code> <a href="tokens.html#lifetimes-and-loop-labels">LIFETIME_OR_LABEL</a><sup>?</sup></p>
</blockquote>
<p>When <code>continue</code> is encountered, the current iteration of the associated loop
body is immediately terminated, returning control to the loop <em>head</em>. In
the case of a <code>while</code> loop, the head is the conditional expression controlling
the loop. In the case of a <code>for</code> loop, the head is the call-expression
controlling the loop.</p>
<p>Like <code>break</code>, <code>continue</code> is normally associated with the innermost enclosing
loop, but <code>continue 'label</code> may be used to specify the loop affected.
A <code>continue</code> expression is only permitted in the body of a loop.</p>
<a class="header" href="print.html#break-and-loop-values" id="break-and-loop-values"><h2><code>break</code> and loop values</h2></a>
<p>When associated with a <code>loop</code>, a break expression may be used to return a value
from that loop, via one of the forms <code>break EXPR</code> or <code>break 'label EXPR</code>, where
<code>EXPR</code> is an expression whose result is returned from the <code>loop</code>. For example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let (mut a, mut b) = (1, 1);
let result = loop {
    if b &gt; 10 {
        break b;
    }
    let c = a + b;
    a = b;
    b = c;
};
// first number in Fibonacci sequence over 10:
assert_eq!(result, 13);
#}</code></pre></pre>
<p>In the case a <code>loop</code> has an associated <code>break</code>, it is not considered diverging,
and the <code>loop</code> must have a type compatible with each <code>break</code> expression.
<code>break</code> without an expression is considered identical to <code>break</code> with
expression <code>()</code>.</p>
<a class="header" href="print.html#range-expressions" id="range-expressions"><h1>Range expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>RangeExpression</em> :<br />
      <em>RangeExpr</em><br />
   | <em>RangeFromExpr</em><br />
   | <em>RangeToExpr</em><br />
   | <em>RangeFullExpr</em><br />
   | <em>RangeInclusiveExpr</em><br />
   | <em>RangeToInclusiveExpr</em></p>
<p><em>RangeExpr</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>..</code> <a href="expressions.html"><em>Expression</em></a></p>
<p><em>RangeFromExpr</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>..</code></p>
<p><em>RangeToExpr</em> :<br />
   <code>..</code> <a href="expressions.html"><em>Expression</em></a></p>
<p><em>RangeFullExpr</em> :<br />
   <code>..</code></p>
<p><em>RangeExpr</em> :<br />
   <a href="expressions.html"><em>Expression</em></a> <code>..=</code> <a href="expressions.html"><em>Expression</em></a></p>
<p><em>RangeToExpr</em> :<br />
   <code>..=</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>The <code>..</code> and <code>..=</code> operators will construct an object of one of the
<code>std::ops::Range</code> (or <code>core::ops::Range</code>) variants, according to the following
table:</p>
<table><thead><tr><th> Production             </th><th> Syntax        </th><th> Type                         </th><th> Range                 </th></tr></thead><tbody>
<tr><td> <em>RangeExpr</em>            </td><td> start<code>..</code>end  </td><td> <a href="https://doc.rust-lang.org/std/ops/struct.Range.html">std::ops::Range</a>            </td><td> start ≤ x &lt; end </td></tr>
<tr><td> <em>RangeFromExpr</em>        </td><td> start<code>..</code>     </td><td> <a href="https://doc.rust-lang.org/std/ops/struct.RangeFrom.html">std::ops::RangeFrom</a>        </td><td> start ≤ x          </td></tr>
<tr><td> <em>RangeToExpr</em>          </td><td> <code>..</code>end       </td><td> <a href="https://doc.rust-lang.org/std/ops/struct.RangeTo.html">std::ops::RangeTo</a>          </td><td>            x &lt; end </td></tr>
<tr><td> <em>RangeFullExpr</em>        </td><td> <code>..</code>          </td><td> <a href="https://doc.rust-lang.org/std/ops/struct.RangeFull.html">std::ops::RangeFull</a>        </td><td>            -          </td></tr>
<tr><td> <em>RangeInclusiveExpr</em>   </td><td> start<code>..=</code>end </td><td> <a href="https://doc.rust-lang.org/std/ops/struct.RangeInclusive.html">std::ops::RangeInclusive</a>   </td><td> start ≤ x ≤ end </td></tr>
<tr><td> <em>RangeToInclusiveExpr</em> </td><td> <code>..=</code>end      </td><td> <a href="https://doc.rust-lang.org/std/ops/struct.RangeToInclusive.html">std::ops::RangeToInclusive</a> </td><td>            x ≤ end </td></tr>
</tbody></table>
<p>Examples:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
1..2;   // std::ops::Range
3..;    // std::ops::RangeFrom
..4;    // std::ops::RangeTo
..;     // std::ops::RangeFull
5..=6;  // std::ops::RangeInclusive
..=7;   // std::ops::RangeToInclusive
#}</code></pre></pre>
<p>The following expressions are equivalent.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = std::ops::Range {start: 0, end: 10};
let y = 0..10;

assert_eq!(x, y);
#}</code></pre></pre>
<p>Ranges can be used in <code>for</code> loops:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
for i in 1..11 {
    println!(&quot;{}&quot;, i);
}
#}</code></pre></pre>
<a class="header" href="print.html#if-and-if-let-expressions" id="if-and-if-let-expressions"><h1><code>if</code> and <code>if let</code> expressions</h1></a>
<a class="header" href="print.html#if-expressions" id="if-expressions"><h2><code>if</code> expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>IfExpression</em> :<br />
   <code>if</code> <a href="expressions.html"><em>Expression</em></a><sub><em>except struct expression</em></sub> <a href="expressions/block-expr.html"><em>BlockExpression</em></a><br />
   (<code>else</code> (
<a href="expressions/block-expr.html"><em>BlockExpression</em></a>
| <em>IfExpression</em>
| <em>IfLetExpression</em> ) )<sup>?</sup></p>
</blockquote>
<p>An <code>if</code> expression is a conditional branch in program control. The form of an
<code>if</code> expression is a condition expression, followed by a consequent block, any
number of <code>else if</code> conditions and blocks, and an optional trailing <code>else</code>
block. The condition expressions must have type <code>bool</code>. If a condition
expression evaluates to <code>true</code>, the consequent block is executed and any
subsequent <code>else if</code> or <code>else</code> block is skipped. If a condition expression
evaluates to <code>false</code>, the consequent block is skipped and any subsequent <code>else if</code> condition is evaluated. If all <code>if</code> and <code>else if</code> conditions evaluate to
<code>false</code> then any <code>else</code> block is executed. An if expression evaluates to the
same value as the executed block, or <code>()</code> if no block is evaluated. An <code>if</code>
expression must have the same type in all situations.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let x = 3;
if x == 4 {
    println!(&quot;x is four&quot;);
} else if x == 3 {
    println!(&quot;x is three&quot;);
} else {
    println!(&quot;x is something else&quot;);
}

let y = if 12 * 15 &gt; 150 {
    &quot;Bigger&quot;
} else {
    &quot;Smaller&quot;
};
assert_eq!(y, &quot;Bigger&quot;);
#}</code></pre></pre>
<a class="header" href="print.html#if-let-expressions" id="if-let-expressions"><h2><code>if let</code> expressions</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>IfLetExpression</em> :<br />
   <code>if</code> <code>let</code> <em>Pattern</em> <code>=</code> <a href="expressions.html"><em>Expression</em></a><sub><em>except struct expression</em></sub>
<a href="expressions/block-expr.html"><em>BlockExpression</em></a><br />
   (<code>else</code> (
<a href="expressions/block-expr.html"><em>BlockExpression</em></a>
| <em>IfExpression</em>
| <em>IfLetExpression</em> ) )<sup>?</sup></p>
</blockquote>
<p>An <code>if let</code> expression is semantically similar to an <code>if</code> expression but in
place of a condition expression it expects the keyword <code>let</code> followed by a
refutable pattern, an <code>=</code> and an expression. If the value of the expression on
the right hand side of the <code>=</code> matches the pattern, the corresponding block
will execute, otherwise flow proceeds to the following <code>else</code> block if it
exists. Like <code>if</code> expressions, <code>if let</code> expressions have a value determined by
the block that is evaluated.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let dish = (&quot;Ham&quot;, &quot;Eggs&quot;);

// this body will be skipped because the pattern is refuted
if let (&quot;Bacon&quot;, b) = dish {
    println!(&quot;Bacon is served with {}&quot;, b);
} else {
    // This block is evaluated instead.
    println!(&quot;No bacon will be served&quot;);
}

// this body will execute
if let (&quot;Ham&quot;, b) = dish {
    println!(&quot;Ham is served with {}&quot;, b);
}
#}</code></pre></pre>
<p><code>if</code> and <code>if let</code> expressions can be intermixed:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = Some(3);
let a = if let Some(1) = x {
    1
} else if x == Some(2) {
    2
} else if let Some(y) = x {
    y
} else {
    -1
};
assert_eq!(a, 3);
#}</code></pre></pre>
<a class="header" href="print.html#match-expressions" id="match-expressions"><h1><code>match</code> expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>MatchExpression</em> :<br />
   <code>match</code> <a href="expressions.html"><em>Expression</em></a><sub><em>except struct expression</em></sub> <code>{</code><br />
      <a href="attributes.html"><em>InnerAttribute</em></a><sup>*</sup><br />
      <em>MatchArms</em><sup>?</sup><br />
   <code>}</code></p>
<p><em>MatchArms</em> :<br />
   ( <em>MatchArm</em> <code>=&gt;</code>
( <a href="expressions/block-expr.html#block-expressions"><em>BlockExpression</em></a> <code>,</code><sup>?</sup>
| <a href="expressions.html"><em>Expression</em></a> <code>,</code> )
)<sup>*</sup><br />
   <em>MatchArm</em> <code>=&gt;</code> ( <a href="expressions/block-expr.html#block-expressions"><em>BlockExpression</em></a> | <a href="expressions.html"><em>Expression</em></a> ) <code>,</code><sup>?</sup></p>
<p><em>MatchArm</em> :<br />
   <a href="attributes.html"><em>OuterAttribute</em></a><sup>*</sup> <em>MatchArmPatterns</em> <em>MatchArmGuard</em><sup>?</sup></p>
<p><em>MatchArmPatterns</em> :<br />
   <code>|</code><sup>?</sup> <em>Pattern</em> ( <code>|</code> <em>Pattern</em> )<sup>*</sup></p>
<p><em>MatchArmGuard</em> :<br />
   <code>if</code> <a href="expressions.html"><em>Expression</em></a></p>
</blockquote>
<p>A <code>match</code> expression branches on a <em>pattern</em>. The exact form of matching that
occurs depends on the pattern. Patterns consist of some combination of
literals, destructured arrays or enum constructors, structs and tuples,
variable binding specifications, wildcards (<code>..</code>), and placeholders (<code>_</code>). A
<code>match</code> expression has a <em>head expression</em>, which is the value to compare to
the patterns. The type of the patterns must equal the type of the head
expression.</p>
<p>A <code>match</code> behaves differently depending on whether or not the head expression
is a <a href="expressions.html#place-expressions-and-value-expressions">place expression or value expression</a>.
If the head expression is a <a href="expressions.html#place-expressions-and-value-expressions">value expression</a>, it is first evaluated into a
temporary location, and the resulting value is sequentially compared to the
patterns in the arms until a match is found. The first arm with a matching
pattern is chosen as the branch target of the <code>match</code>, any variables bound by
the pattern are assigned to local variables in the arm's block, and control
enters the block.</p>
<p>When the head expression is a <a href="expressions.html#place-expressions-and-value-expressions">place expression</a>, the match does not allocate a
temporary location; however, a by-value binding may copy or move from the
memory location.
When possible, it is preferable to match on place expressions, as the lifetime
of these matches inherits the lifetime of the place expression rather than being
restricted to the inside of the match.</p>
<p>An example of a <code>match</code> expression:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = 1;

match x {
    1 =&gt; println!(&quot;one&quot;),
    2 =&gt; println!(&quot;two&quot;),
    3 =&gt; println!(&quot;three&quot;),
    4 =&gt; println!(&quot;four&quot;),
    5 =&gt; println!(&quot;five&quot;),
    _ =&gt; println!(&quot;something else&quot;),
}
#}</code></pre></pre>
<p>Patterns that bind variables default to binding to a copy or move of the
matched value (depending on the matched value's type). This can be changed to
bind to a reference by using the <code>ref</code> keyword, or to a mutable reference using
<code>ref mut</code>.</p>
<p>Patterns can be used to <em>destructure</em> structs, enums, and tuples. Destructuring
breaks a value up into its component pieces. The syntax used is the same as
when creating such values. When destructing a data structure with named (but
not numbered) fields, it is allowed to write <code>fieldname</code> as a shorthand for
<code>fieldname: fieldname</code>. In a pattern whose head expression has a <code>struct</code>,
<code>enum</code> or <code>tupl</code> type, a placeholder (<code>_</code>) stands for a <em>single</em> data field,
whereas a wildcard <code>..</code> stands for <em>all</em> the fields of a particular variant.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# enum Message {
#     Quit,
#     WriteString(String),
#     Move { x: i32, y: i32 },
#     ChangeColor(u8, u8, u8),
# }
# let message = Message::Quit;
match message {
    Message::Quit =&gt; println!(&quot;Quit&quot;),
    Message::WriteString(write) =&gt; println!(&quot;{}&quot;, &amp;write),
    Message::Move{ x, y: 0 } =&gt; println!(&quot;move {} horizontally&quot;, x),
    Message::Move{ .. } =&gt; println!(&quot;other move&quot;),
    Message::ChangeColor { 0: red, 1: green, 2: _ } =&gt; {
        println!(&quot;color change, red: {}, green: {}&quot;, red, green);
    }
};
#}</code></pre></pre>
<p>Patterns can also dereference pointers by using the <code>&amp;</code>, <code>&amp;mut</code> and <code>box</code>
symbols, as appropriate. For example, these two matches on <code>x: &amp;i32</code> are
equivalent:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let x = &amp;3;
let y = match *x { 0 =&gt; &quot;zero&quot;, _ =&gt; &quot;some&quot; };
let z = match x { &amp;0 =&gt; &quot;zero&quot;, _ =&gt; &quot;some&quot; };

assert_eq!(y, z);
#}</code></pre></pre>
<p>Subpatterns can also be bound to variables by the use of the syntax <code>variable @ subpattern</code>. For example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let x = 1;

match x {
    e @ 1 ... 5 =&gt; println!(&quot;got a range element {}&quot;, e),
    _ =&gt; println!(&quot;anything&quot;),
}
#}</code></pre></pre>
<p>Multiple match patterns may be joined with the <code>|</code> operator. An inclusive range
of values may be specified with <code>..=</code>. For example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let x = 9;
let message = match x {
    0 | 1  =&gt; &quot;not many&quot;,
    2 ..= 9 =&gt; &quot;a few&quot;,
    _      =&gt; &quot;lots&quot;
};

assert_eq!(message, &quot;a few&quot;);
#}</code></pre></pre>
<p>Other forms of [range] (<code>..</code> for an exclusive range, or any range with one or
both endpoints left unspecified) are not supported in matches. The
syntax <code>...</code> is also accepted for inclusive ranges in patterns only, for
backwards compatibility.</p>
<p>Range patterns only work <a href="types.html#textual-types"><code>char</code></a> and <a href="types.html#numeric-types">numeric types</a>. A range pattern may not
be a sub-range of another range pattern inside the same <code>match</code>.</p>
<p>Slice patterns can match both arrays of fixed size and slices of dynamic size.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Fixed size
let arr = [1, 2, 3];
match arr {
    [1, _, _] =&gt; &quot;starts with one&quot;,
    [a, b, c] =&gt; &quot;starts with something else&quot;,
};
#}</code></pre></pre>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Dynamic size
let v = vec![1, 2, 3];
match v[..] {
    [a, b] =&gt; { /* this arm will not apply because the length doesn't match */ }
    [a, b, c] =&gt; { /* this arm will apply */ }
    _ =&gt; { /* this wildcard is required, since we don't know length statically */ }
}
#}</code></pre></pre>
<p>Finally, match patterns can accept <em>pattern guards</em> to further refine the
criteria for matching a case. Pattern guards appear after the pattern and
consist of a bool-typed expression following the <code>if</code> keyword. A pattern guard
may refer to the variables bound within the pattern they follow.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let maybe_digit = Some(0);
# fn process_digit(i: i32) { }
# fn process_other(i: i32) { }
let message = match maybe_digit {
    Some(x) if x &lt; 10 =&gt; process_digit(x),
    Some(x) =&gt; process_other(x),
    None =&gt; panic!(),
};
#}</code></pre></pre>
<a class="header" href="print.html#return-expressions" id="return-expressions"><h1><code>return</code> expressions</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>ReturnExpression</em> :<br />
   <code>return</code> <a href="expressions.html"><em>Expression</em></a><sup>?</sup></p>
</blockquote>
<p>Return expressions are denoted with the keyword <code>return</code>. Evaluating a <code>return</code>
expression moves its argument into the designated output location for the
current function call, destroys the current function activation frame, and
transfers control to the caller frame.</p>
<p>An example of a <code>return</code> expression:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn max(a: i32, b: i32) -&gt; i32 {
    if a &gt; b {
        return a;
    }
    return b;
}
#}</code></pre></pre>
<a class="header" href="print.html#type-system" id="type-system"><h1>Type system</h1></a>
<a class="header" href="print.html#types" id="types"><h1>Types</h1></a>
<p>Every variable, item and value in a Rust program has a type. The <em>type</em> of a
<em>value</em> defines the interpretation of the memory holding it.</p>
<p>Built-in types are tightly integrated into the language, in nontrivial ways
that are not possible to emulate in user-defined types. User-defined types have
limited capabilities.</p>
<a class="header" href="print.html#primitive-types" id="primitive-types"><h2>Primitive types</h2></a>
<p>Some types are defined by the language, rather than as part of the standard
library, these are called <em>primitive types</em>. Some of these are individual
types:</p>
<ul>
<li>The boolean type <code>bool</code> with values <code>true</code> and <code>false</code>.</li>
<li>The <a href="print.html#machine-types">machine types</a> (integer and floating-point).</li>
<li>The <a href="print.html#machine-dependent-integer-types">machine-dependent integer types</a>.</li>
<li>The <a href="print.html#textual-types">textual types</a> <code>char</code> and <code>str</code>.</li>
<li>The [never type] <code>!</code></li>
</ul>
<p>There are also some primitive constructs for generic types built in to the
language:</p>
<ul>
<li><a href="print.html#tuple-types">Tuples</a></li>
<li><a href="print.html#array-and-slice-types">Arrays</a></li>
<li><a href="print.html#array-and-slice-types">Slices</a></li>
<li><a href="print.html#function-pointer-types">Function pointers</a></li>
<li><a href="print.html#pointer-types">References</a></li>
<li><a href="print.html#raw-pointers-const-and-mut">Pointers</a></li>
</ul>
<a class="header" href="print.html#numeric-types" id="numeric-types"><h2>Numeric types</h2></a>
<a class="header" href="print.html#machine-types" id="machine-types"><h3>Machine types</h3></a>
<p>The machine types are the following:</p>
<ul>
<li>
<p>The unsigned word types <code>u8</code>, <code>u16</code>, <code>u32</code>, <code>u64</code>, and <code>u128</code> with values drawn from
the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1],
[0, 2^64 - 1], and [0, 2^128 - 1] respectively.</p>
</li>
<li>
<p>The signed two's complement word types <code>i8</code>, <code>i16</code>, <code>i32</code>, <code>i64</code>, and <code>i128</code>, with
values drawn from the integer intervals [-(2^7), 2^7 - 1],
[-(2^15), 2^15 - 1], [-(2^31), 2^31 - 1], [-(2^63), 2^63 - 1], and
[-(2^127), 2^127 - 1] respectively.</p>
</li>
<li>
<p>The IEEE 754-2008 &quot;binary32&quot; and &quot;binary64&quot; floating-point types: <code>f32</code> and
<code>f64</code>, respectively.</p>
</li>
</ul>
<a class="header" href="print.html#machine-dependent-integer-types" id="machine-dependent-integer-types"><h3>Machine-dependent integer types</h3></a>
<p>The <code>usize</code> type is an unsigned integer type with the same number of bits as the
platform's pointer type. It can represent every memory address in the process.</p>
<p>The <code>isize</code> type is a signed integer type with the same number of bits as the
platform's pointer type. The theoretical upper bound on object and array size
is the maximum <code>isize</code> value. This ensures that <code>isize</code> can be used to calculate
differences between pointers into an object or array and can address every byte
within an object along with one byte past the end.</p>
<a class="header" href="print.html#textual-types" id="textual-types"><h2>Textual types</h2></a>
<p>The types <code>char</code> and <code>str</code> hold textual data.</p>
<p>A value of type <code>char</code> is a <a href="http://www.unicode.org/glossary/#unicode_scalar_value">Unicode scalar value</a> (i.e. a code point that
is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to
0xD7FF or 0xE000 to 0x10FFFF range. A <code>[char]</code> is effectively a UCS-4 / UTF-32
string.</p>
<p>A value of type <code>str</code> is a Unicode string, represented as an array of 8-bit
unsigned bytes holding a sequence of UTF-8 code points. Since <code>str</code> is a
<a href="dynamically-sized-types.html">dynamically sized type</a>, it is not a <em>first-class</em> type, but can only be
instantiated through a pointer type, such as <code>&amp;str</code>.</p>
<a class="header" href="print.html#never-type" id="never-type"><h2>Never type</h2></a>
<p>The never type <code>!</code> is a type with no values, representing the result of
computations that never complete. Expressions of type <code>!</code> can be coerced into
any other type.</p>
<a class="header" href="print.html#tuple-types" id="tuple-types"><h2>Tuple types</h2></a>
<p>A tuple <em>type</em> is a heterogeneous product of other types, called the <em>elements</em>
of the tuple. It has no nominal name and is instead structurally typed.</p>
<p>Tuple types and values are denoted by listing the types or values of their
elements, respectively, in a parenthesized, comma-separated list.</p>
<p>Because tuple elements don't have a name, they can only be accessed by
pattern-matching or by using <code>N</code> directly as a field to access the <code>N</code>th
element.</p>
<p>An example of a tuple type and its use:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
type Pair&lt;'a&gt; = (i32, &amp;'a str);
let p: Pair&lt;'static&gt; = (10, &quot;ten&quot;);
let (a, b) = p;

assert_eq!(a, 10);
assert_eq!(b, &quot;ten&quot;);
assert_eq!(p.0, 10);
assert_eq!(p.1, &quot;ten&quot;);
#}</code></pre></pre>
<p>For historical reasons and convenience, the tuple type with no elements (<code>()</code>)
is often called ‘unit’ or ‘the unit type’.</p>
<a class="header" href="print.html#array-and-slice-types" id="array-and-slice-types"><h2>Array, and Slice types</h2></a>
<p>Rust has two different types for a list of items:</p>
<ul>
<li><code>[T; N]</code>, an 'array'</li>
<li><code>[T]</code>, a 'slice'</li>
</ul>
<p>An array has a fixed size, and can be allocated on either the stack or the
heap.</p>
<p>A slice is a <a href="dynamically-sized-types.html">dynamically sized type</a> representing a 'view' into an array. To
use a slice type it generally has to be used behind a pointer for example as</p>
<ul>
<li><code>&amp;[T]</code>, a 'shared slice', often just called a 'slice', it doesn't own the
data it points to, it borrows it.</li>
<li><code>&amp;mut [T]</code>, a 'mutable slice', mutably borrows the data it points to.</li>
<li><code>Box&lt;[T]&gt;</code>, a 'boxed slice'</li>
</ul>
<p>Examples:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// A stack-allocated array
let array: [i32; 3] = [1, 2, 3];

// A heap-allocated array, coerced to a slice
let boxed_array: Box&lt;[i32]&gt; = Box::new([1, 2, 3]);

// A (shared) slice into an array
let slice: &amp;[i32] = &amp;boxed_array[..];
#}</code></pre></pre>
<p>All elements of arrays and slices are always initialized, and access to an
array or slice is always bounds-checked in safe methods and operators.</p>
<blockquote>
<p>Note: The <a href="../std/vec/struct.Vec.html"><code>Vec&lt;T&gt;</code></a> standard library type provides a heap-allocated resizable
array type.</p>
</blockquote>
<a class="header" href="print.html#struct-types" id="struct-types"><h2>Struct types</h2></a>
<p>A <code>struct</code> <em>type</em> is a heterogeneous product of other types, called the
<em>fields</em> of the type.<sup class="footnote-reference"><a href="print.html#structtype">1</a></sup></p>
<p>New instances of a <code>struct</code> can be constructed with a <a href="expressions/struct-expr.html">struct
expression</a>.</p>
<p>The memory layout of a <code>struct</code> is undefined by default to allow for compiler
optimizations like field reordering, but it can be fixed with the
<code>#[repr(...)]</code> attribute. In either case, fields may be given in any order in a
corresponding struct <em>expression</em>; the resulting <code>struct</code> value will always
have the same memory layout.</p>
<p>The fields of a <code>struct</code> may be qualified by <a href="visibility-and-privacy.html">visibility
modifiers</a>, to allow access to data in a struct
outside a module.</p>
<p>A <em>tuple struct</em> type is just like a struct type, except that the fields are
anonymous.</p>
<p>A <em>unit-like struct</em> type is like a struct type, except that it has no fields.
The one value constructed by the associated <a href="expressions/struct-expr.html">struct expression</a> is the only
value that inhabits such a type.</p>
<div class="footnote-definition" id="structtype"><sup class="footnote-definition-label">1</sup>
<p><code>struct</code> types are analogous to <code>struct</code> types in C, the
<em>record</em> types of the ML family, or the <em>struct</em> types of the Lisp family.</p>
</div>
<a class="header" href="print.html#enumerated-types" id="enumerated-types"><h2>Enumerated types</h2></a>
<p>An <em>enumerated type</em> is a nominal, heterogeneous disjoint union type, denoted
by the name of an <a href="items/enumerations.html"><code>enum</code> item</a>. <sup class="footnote-reference"><a href="print.html#enumtype">2</a></sup></p>
<p>An <a href="items/enumerations.html"><code>enum</code> item</a> declares both the type and a number
of <em>variants</em>, each of which is independently named and has the syntax of a
struct, tuple struct or unit-like struct.</p>
<p>New instances of an <code>enum</code> can be constructed in an <a href="expressions/enum-variant-expr.html">enumeration variant
expression</a>.</p>
<p>Any <code>enum</code> value consumes as much memory as the largest variant for its
corresponding <code>enum</code> type, as well as the size needed to store a discriminant.</p>
<p>Enum types cannot be denoted <em>structurally</em> as types, but must be denoted by
named reference to an <a href="items/enumerations.html"><code>enum</code> item</a>.</p>
<div class="footnote-definition" id="enumtype"><sup class="footnote-definition-label">2</sup>
<p>The <code>enum</code> type is analogous to a <code>data</code> constructor declaration in
ML, or a <em>pick ADT</em> in Limbo.</p>
</div>
<a class="header" href="print.html#union-types" id="union-types"><h2>Union types</h2></a>
<p>A <em>union type</em> is a nominal, heterogeneous C-like union, denoted by the name of
a <a href="items/unions.html"><code>union</code> item</a>.</p>
<p>A union contains the value of any one of its fields. Since the accessing the
wrong field can cause unexpected or undefined behaviour, <code>unsafe</code> is required
to read from a union field or to write to a field that doesn't implement
<a href="special-types-and-traits.html#copy"><code>Copy</code></a>.</p>
<p>The memory layout of a <code>union</code> is undefined by default, but the <code>#[repr(...)]</code>
attribute can be used to fix a layout.</p>
<a class="header" href="print.html#recursive-types" id="recursive-types"><h2>Recursive types</h2></a>
<p>Nominal types — <a href="print.html#struct-types">structs</a>,
<a href="print.html#enumerated-types">enumerations</a> and <a href="print.html#union-types">unions</a> — may be
recursive. That is, each <code>enum</code> variant or <code>struct</code> or <code>union</code> field may refer,
directly or indirectly, to the enclosing <code>enum</code> or <code>struct</code> type itself. Such
recursion has restrictions:</p>
<ul>
<li>Recursive types must include a nominal type in the recursion (not mere <a href="../grammar.html#type-definitions">type
definitions</a>, or other structural types
such as <a href="print.html#array-and-slice-types">arrays</a> or <a href="print.html#tuple-types">tuples</a>). So
<code>type Rec = &amp;'static [Rec]</code> is not allowed.</li>
<li>The size of a recursive type must be finite; in other words the recursive
fields of the type must be <a href="print.html#pointer-types">pointer types</a>.</li>
<li>Recursive type definitions can cross module boundaries, but not module
<em>visibility</em> boundaries, or crate boundaries (in order to simplify the module
system and type checker).</li>
</ul>
<p>An example of a <em>recursive</em> type and its use:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
enum List&lt;T&gt; {
    Nil,
    Cons(T, Box&lt;List&lt;T&gt;&gt;)
}

let a: List&lt;i32&gt; = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil))));
#}</code></pre></pre>
<a class="header" href="print.html#pointer-types" id="pointer-types"><h2>Pointer types</h2></a>
<p>All pointers in Rust are explicit first-class values. They can be moved or
copied, stored into data structs, and returned from functions.</p>
<a class="header" href="print.html#shared-references-" id="shared-references-"><h3>Shared references (<code>&amp;</code>)</h3></a>
<p>These point to memory <em>owned by some other value</em>. When a shared reference to a
value is created it prevents direct mutation of the value. <a href="interior-mutability.html">Interior
mutability</a> provides an exception for this in certain
circumstances. As the name suggests, any number of shared references to a value
may exit. A shared reference type is written <code>&amp;type</code>, or <code>&amp;'a type</code> when you
need to specify an explicit lifetime. Copying a reference is a &quot;shallow&quot;
operation: it involves only copying the pointer itself, that is, pointers are
<code>Copy</code>. Releasing a reference has no effect on the value it points to, but
referencing of a <a href="expressions.html#temporary-lifetimes">temporary value</a> will
keep it alive during the scope of the reference itself.</p>
<a class="header" href="print.html#mutable-references-mut" id="mutable-references-mut"><h3>Mutable references (<code>&amp;mut</code>)</h3></a>
<p>These also point to memory owned by some other value. A mutable reference type
is written <code>&amp;mut type</code> or <code>&amp;'a mut type</code>. A mutable reference (that hasn't been
borrowed) is the only way to access the value it points to, so is not <code>Copy</code>.</p>
<a class="header" href="print.html#raw-pointers-const-and-mut" id="raw-pointers-const-and-mut"><h3>Raw pointers (<code>*const</code> and <code>*mut</code>)</h3></a>
<p>Raw pointers are pointers without safety or liveness guarantees. Raw pointers
are written as <code>*const T</code> or <code>*mut T</code>, for example <code>*const i32</code> means a raw
pointer to a 32-bit integer. Copying or dropping a raw pointer has no effect on
the lifecycle of any other value. Dereferencing a raw pointer is an <a href="unsafe-functions.html"><code>unsafe</code>
operation</a>, this can also be used to convert a raw
pointer to a reference by reborrowing it (<code>&amp;*</code> or <code>&amp;mut *</code>). Raw pointers are
generally discouraged in Rust code; they exist to support interoperability with
foreign code, and writing performance-critical or low-level functions.</p>
<p>When comparing pointers they are compared by their address, rather than by what
they point to. When comparing pointers to <a href="dynamically-sized-types.html">dynamically sized
types</a> they also have their addition data
compared.</p>
<a class="header" href="print.html#smart-pointers" id="smart-pointers"><h3>Smart Pointers</h3></a>
<p>The standard library contains additional 'smart pointer' types beyond references
and raw pointers.</p>
<a class="header" href="print.html#function-item-types" id="function-item-types"><h2>Function item types</h2></a>
<p>When referred to, a function item, or the constructor of a tuple-like struct or
enum variant, yields a zero-sized value of its <em>function item type</em>. That type
explicitly identifies the function - its name, its type arguments, and its
early-bound lifetime arguments (but not its late-bound lifetime arguments,
which are only assigned when the function is called) - so the value does not
need to contain an actual function pointer, and no indirection is needed when
the function is called.</p>
<p>There is no syntax that directly refers to a function item type, but the
compiler will display the type as something like <code>fn(u32) -&gt; i32 {fn_name}</code> in
error messages.</p>
<p>Because the function item type explicitly identifies the function, the item
types of different functions - different items, or the same item with different
generics - are distinct, and mixing them will create a type error:</p>
<pre><pre class="playpen"><code class="language-rust compile_fail E0308">
# #![allow(unused_variables)]
#fn main() {
fn foo&lt;T&gt;() { }
let x = &amp;mut foo::&lt;i32&gt;;
*x = foo::&lt;u32&gt;; //~ ERROR mismatched types
#}</code></pre></pre>
<p>However, there is a <a href="type-coercions.html">coercion</a> from function items to <a href="print.html#function-pointer-types">function
pointers</a> with the same signature, which is triggered
not only when a function item is used when a function pointer is directly
expected, but also when different function item types with the same signature
meet in different arms of the same <code>if</code> or <code>match</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# let want_i32 = false;
# fn foo&lt;T&gt;() { }

// `foo_ptr_1` has function pointer type `fn()` here
let foo_ptr_1: fn() = foo::&lt;i32&gt;;

// ... and so does `foo_ptr_2` - this type-checks.
let foo_ptr_2 = if want_i32 {
    foo::&lt;i32&gt;
} else {
    foo::&lt;u32&gt;
};
#}</code></pre></pre>
<p>All function items implement <a href="../std/ops/trait.Fn.html"><code>Fn</code></a>, <a href="../std/ops/trait.FnMut.html"><code>FnMut</code></a>, <a href="../std/ops/trait.FnOnce.html"><code>FnOnce</code></a>, <a href="special-types-and-traits.html#copy"><code>Copy</code></a>,
[<code>Clone]</code>, <a href="special-types-and-traits.html#send"><code>Send</code></a>, and <a href="special-types-and-traits.html#sync"><code>Sync</code></a>.</p>
<a class="header" href="print.html#function-pointer-types" id="function-pointer-types"><h2>Function pointer types</h2></a>
<p>Function pointer types, written using the <code>fn</code> keyword, refer to a function
whose identity is not necessarily known at compile-time. They can be created
via a coercion from both <a href="print.html#function-item-types">function items</a> and
non-capturing <a href="print.html#closure-types">closures</a>.</p>
<p>A function pointer type consists of a possibly-empty set of function-type
modifiers (such as <code>unsafe</code> or <code>extern</code>), a sequence of input types and an
output type.</p>
<p>An example where <code>Binop</code> is defined as a function pointer type:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn add(x: i32, y: i32) -&gt; i32 {
    x + y
}

let mut x = add(5,7);

type Binop = fn(i32, i32) -&gt; i32;
let bo: Binop = add;
x = bo(5,7);
#}</code></pre></pre>
<a class="header" href="print.html#closure-types" id="closure-types"><h2>Closure types</h2></a>
<p>A <a href="expressions/closure-expr.html">closure expression</a> produces a closure value with a unique, anonymous type
that cannot be written out. A closure type is approximately equivalent to a
struct which contains the captured variables. For instance, the following
closure:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn f&lt;F : FnOnce() -&gt; String&gt; (g: F) {
    println!(&quot;{}&quot;, g());
}

let mut s = String::from(&quot;foo&quot;);
let t = String::from(&quot;bar&quot;);

f(|| {
    s += &amp;*t;
    s
});
// Prints &quot;foobar&quot;.
#}</code></pre></pre>
<p>generates a closure type roughly like the following:</p>
<pre><code class="language-rust ignore">struct Closure&lt;'a&gt; {
    s : String,
    t : &amp;'a String,
}

impl&lt;'a&gt; (FnOnce() -&gt; String) for Closure&lt;'a&gt; {
    fn call_once(self) -&gt; String {
        self.s += &amp;*self.t;
        self.s
    }
}
</code></pre>
<p>so that the call to <code>f</code> works as if it were:</p>
<pre><code class="language-rust ignore">f(Closure{s: s, t: &amp;t});
</code></pre>
<p>The compiler prefers to capture a closed-over variable by immutable borrow,
followed by unique immutable borrow (see below), by mutable borrow, and finally
by move. It will pick the first choice of these that allows the closure to
compile. The choice is made only with regards to the contents of the closure
expression; the compiler does not take into account surrounding code, such as
the lifetimes of involved variables.</p>
<p>If the <code>move</code> keyword is used, then all captures are by move or, for <code>Copy</code>
types, by copy, regardless of whether a borrow would work. The <code>move</code> keyword is
usually used to allow the closure to outlive the captured values, such as if the
closure is being returned or used to spawn a new thread.</p>
<p>Composite types such as structs, tuples, and enums are always captured entirely,
not by individual fields. It may be necessary to borrow into a local variable in
order to capture a single field:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# use std::collections::HashSet;
# 
struct SetVec {
    set: HashSet&lt;u32&gt;,
    vec: Vec&lt;u32&gt;
}

impl SetVec {
    fn populate(&amp;mut self) {
        let vec = &amp;mut self.vec;
        self.set.iter().for_each(|&amp;n| {
            vec.push(n);
        })
    }
}
#}</code></pre></pre>
<p>If, instead, the closure were to use <code>self.vec</code> directly, then it would attempt
to capture <code>self</code> by mutable reference. But since <code>self.set</code> is already
borrowed to iterate over, the code would not compile.</p>
<a class="header" href="print.html#unique-immutable-borrows-in-captures" id="unique-immutable-borrows-in-captures"><h3>Unique immutable borrows in captures</h3></a>
<p>Captures can occur by a special kind of borrow called a <em>unique immutable
borrow</em>, which cannot be used anywhere else in the language and cannot be
written out explicitly. It occurs when modifying the referent of a mutable
reference, as in the following example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let mut b = false;
let x = &amp;mut b;
{
    let mut c = || { *x = true; };
    // The following line is an error:
    // let y = &amp;x;
    c();
}
let z = &amp;x;
#}</code></pre></pre>
<p>In this case, borrowing <code>x</code> mutably is not possible, because <code>x</code> is not <code>mut</code>.
But at the same time, borrowing <code>x</code> immutably would make the assignment illegal,
because a <code>&amp; &amp;mut</code> reference may not be unique, so it cannot safely be used to
modify a value. So a unique immutable borrow is used: it borrows <code>x</code> immutably,
but like a mutable borrow, it must be unique. In the above example, uncommenting
the declaration of <code>y</code> will produce an error because it would violate the
uniqueness of the closure's borrow of <code>x</code>; the declaration of z is valid because
the closure's lifetime has expired at the end of the block, releasing the borrow.</p>
<a class="header" href="print.html#call-traits-and-coercions" id="call-traits-and-coercions"><h3>Call traits and coercions</h3></a>
<p>Closure types all implement <a href="../std/ops/trait.FnOnce.html"><code>FnOnce</code></a>, indicating that they can be called once
by consuming ownership of the closure. Additionally, some closures implement
more specific call traits:</p>
<ul>
<li>
<p>A closure which does not move out of any captured variables implements
<a href="../std/ops/trait.FnMut.html"><code>FnMut</code></a>, indicating that it can be called by mutable reference.</p>
</li>
<li>
<p>A closure which does not mutate or move out of any captured variables
implements <a href="../std/ops/trait.Fn.html"><code>Fn</code></a>, indicating that it can be called by shared reference.</p>
</li>
</ul>
<blockquote>
<p>Note: <code>move</code> closures may still implement <a href="../std/ops/trait.Fn.html"><code>Fn</code></a> or <a href="../std/ops/trait.FnMut.html"><code>FnMut</code></a>, even though
they capture variables by move. This is because the traits implemented by a
closure type are determined by what the closure does with captured values,
not how it captures them.</p>
</blockquote>
<p><em>Non-capturing closures</em> are closures that don't capture anything from their
environment. They can be coerced to function pointers (<code>fn</code>) with the matching
signature.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let add = |x, y| x + y;

let mut x = add(5,7);

type Binop = fn(i32, i32) -&gt; i32;
let bo: Binop = add;
x = bo(5,7);
#}</code></pre></pre>
<a class="header" href="print.html#other-traits" id="other-traits"><h3>Other traits</h3></a>
<p>All closure types implement <a href="special-types-and-traits.html#sized"><code>Sized</code></a>. Additionally, closure types implement the
following traits if allowed to do so by the types of the captures it stores:</p>
<ul>
<li><a href="special-types-and-traits.html#clone"><code>Clone</code></a></li>
<li><a href="special-types-and-traits.html#copy"><code>Copy</code></a></li>
<li><a href="special-types-and-traits.html#sync"><code>Sync</code></a></li>
<li><a href="special-types-and-traits.html#send"><code>Send</code></a></li>
</ul>
<p>The rules for <a href="special-types-and-traits.html#send"><code>Send</code></a> and <a href="special-types-and-traits.html#sync"><code>Sync</code></a> match those for normal struct types, while
<a href="special-types-and-traits.html#clone"><code>Clone</code></a> and <a href="special-types-and-traits.html#copy"><code>Copy</code></a> behave as if <a href="attributes.html#derive">derived</a>. For <a href="special-types-and-traits.html#clone"><code>Clone</code></a>, the order
of cloning of the captured variables is left unspecified.</p>
<p>Because captures are often by reference, the following general rules arise:</p>
<ul>
<li>A closure is <a href="special-types-and-traits.html#sync"><code>Sync</code></a> if all captured variables are <a href="special-types-and-traits.html#sync"><code>Sync</code></a>.</li>
<li>A closure is <a href="special-types-and-traits.html#send"><code>Send</code></a> if all variables captured by non-unique immutable
reference are <a href="special-types-and-traits.html#sync"><code>Sync</code></a>, and all values captured by unique immutable or mutable
reference, copy, or move are <a href="special-types-and-traits.html#send"><code>Send</code></a>.</li>
<li>A closure is <a href="special-types-and-traits.html#clone"><code>Clone</code></a> or <a href="special-types-and-traits.html#copy"><code>Copy</code></a> if it does not capture any values by
unique immutable or mutable reference, and if all values it captures by copy
or move are <a href="special-types-and-traits.html#clone"><code>Clone</code></a> or <a href="special-types-and-traits.html#copy"><code>Copy</code></a>, respectively.</li>
</ul>
<a class="header" href="print.html#trait-objects" id="trait-objects"><h2>Trait objects</h2></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong>
<em>TraitObjectType</em> :
   <code>dyn</code><sup>?</sup> <em>TypeParamBounds</em></p>
</blockquote>
<p>A <em>trait object</em> is an opaque value of another type that implements a set of
traits. The set of traits is made up of an <a href="items/traits.html#object-safety">object safe</a> <em>base trait</em> plus any
number of <a href="special-types-and-traits.html#auto-traits">auto traits</a>.</p>
<p>Trait objects implement the base trait, its auto traits, and any <a href="items/traits.html#supertraits">supertraits</a>
of the base trait.</p>
<p>Trait objects are written as the optional keyword <code>dyn</code> followed by a set of
trait bounds, but with the following restrictions on the trait bounds. All
traits except the first trait must be auto traits, there may not be more than
one lifetime, and opt-out bounds (e.g. <code>?sized</code>) are not allowed. Furthermore,
paths to traits may be parenthesized.</p>
<p>For example, given a trait <code>Trait</code>, the following are all trait objects:</p>
<ul>
<li><code>Trait</code></li>
<li><code>dyn Trait</code></li>
<li><code>dyn Trait + Send</code></li>
<li><code>dyn Trait + Send + Sync</code></li>
<li><code>dyn Trait + 'static</code></li>
<li><code>dyn Trait + Send + 'static</code></li>
<li><code>dyn Trait +</code></li>
<li><code>dyn 'static + Trait</code>.</li>
<li><code>dyn (Trait)</code></li>
</ul>
<p>If the first bound of the trait object is a path that starts with <code>::</code>, then the
<code>dyn</code> will be treated as a part of the path. The first path can be put in
parenthesis to get around this. As such, if you want a trait object with the
trait <code>::your_module::Trait</code>, you should write it as
<code>dyn (::your_module::Trait)</code>.</p>
<blockquote>
<p>Note: For clarity, it is recommended to always use the <code>dyn</code> keyword on your
trait objects unless your codebase supports compiling with Rust 1.26 or lower.</p>
</blockquote>
<p>Two trait object types alias each other if the base traits alias each other and
if the sets of auto traits are the same and the lifetime bounds are the same.
For example, <code>dyn Trait + Send + UnwindSafe</code> is the same as
<code>dyn Trait + Unwindsafe + Send</code>.</p>
<blockquote>
<p>Warning: With two trait object types, even when the complete set of traits is
the same, if the base traits differ, the type is different. For example,
<code>dyn Send + Sync</code> is a different type from <code>dyn Sync + Send</code>. See
<a href="https://github.com/rust-lang/rust/issues/33140">issue 33140</a>.</p>
</blockquote>
<p>Due to the opaqueness of which concrete type the value is of, trait objects are
<a href="dynamically-sized-types.html">dynamically sized types</a>. Like all
<abbr title="dynamically sized types">DSTs</abbr>, trait objects are used
behind some type of pointer; for example <code>&amp;dyn SomeTrait</code> or
<code>Box&lt;dyn SomeTrait&gt;</code>. Each instance of a pointer to a trait object includes:</p>
<ul>
<li>a pointer to an instance of a type <code>T</code> that implements <code>SomeTrait</code></li>
<li>a <em>virtual method table</em>, often just called a <em>vtable</em>, which contains, for
each method of <code>SomeTrait</code> and its <a href="items/traits.html#supertraits">supertraits</a> that <code>T</code> implements, a
pointer to <code>T</code>'s implementation (i.e. a function pointer).</li>
</ul>
<p>The purpose of trait objects is to permit &quot;late binding&quot; of methods. Calling a
method on a trait object results in virtual dispatch at runtime: that is, a
function pointer is loaded from the trait object vtable and invoked indirectly.
The actual implementation for each vtable entry can vary on an object-by-object
basis.</p>
<p>An example of a trait object:</p>
<pre><pre class="playpen"><code class="language-rust">trait Printable {
    fn stringify(&amp;self) -&gt; String;
}

impl Printable for i32 {
    fn stringify(&amp;self) -&gt; String { self.to_string() }
}

fn print(a: Box&lt;dyn Printable&gt;) {
    println!(&quot;{}&quot;, a.stringify());
}

fn main() {
    print(Box::new(10) as Box&lt;dyn Printable&gt;);
}
</code></pre></pre>
<p>In this example, the trait <code>Printable</code> occurs as a trait object in both the
type signature of <code>print</code>, and the cast expression in <code>main</code>.</p>
<a class="header" href="print.html#trait-object-lifetime-bounds" id="trait-object-lifetime-bounds"><h3>Trait Object Lifetime Bounds</h3></a>
<p>Since a trait object can contain references, the lifetimes of those references
need to be expressed as part of the trait object. This lifetime is written as
<code>Trait + 'a</code>. There are <a href="lifetime-elision.html#default-trait-object-lifetimes">defaults</a> that allow this lifetime to usually be
inferred with a sensible choice.</p>
<a class="header" href="print.html#type-parameters" id="type-parameters"><h2>Type parameters</h2></a>
<p>Within the body of an item that has type parameter declarations, the names of
its type parameters are types:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn to_vec&lt;A: Clone&gt;(xs: &amp;[A]) -&gt; Vec&lt;A&gt; {
    if xs.is_empty() {
        return vec![];
    }
    let first: A = xs[0].clone();
    let mut rest: Vec&lt;A&gt; = to_vec(&amp;xs[1..]);
    rest.insert(0, first);
    rest
}
#}</code></pre></pre>
<p>Here, <code>first</code> has type <code>A</code>, referring to <code>to_vec</code>'s <code>A</code> type parameter; and
<code>rest</code> has type <code>Vec&lt;A&gt;</code>, a vector with element type <code>A</code>.</p>
<a class="header" href="print.html#anonymous-type-parameters" id="anonymous-type-parameters"><h2>Anonymous type parameters</h2></a>
<blockquote>
<p>Note: This section is a placeholder for more comprehensive reference
material.</p>
</blockquote>
<blockquote>
<p>Note: This is often called &quot;impl Trait in argument position&quot;.</p>
</blockquote>
<p>Functions can declare an argument to be an anonymous type parameter where the
callee must provide a type that has the bounds declared by the anonymous type
parameter and the function can only use the methods available by the trait
bounds of the anonymous type parameter.</p>
<p>They are written as <code>impl</code> followed by a set of trait bounds.</p>
<a class="header" href="print.html#abstract-return-types" id="abstract-return-types"><h2>Abstract return types</h2></a>
<blockquote>
<p>Note: This section is a placeholder for more comprehensive reference
material.</p>
</blockquote>
<blockquote>
<p>Note: This is often called &quot;impl Trait in return position&quot;.</p>
</blockquote>
<p>Functions, except for associated trait functions, can return an abstract
return type. These  types stand in for another concrete type where the
use-site may only use the trait methods declared by the trait bounds of the
type.</p>
<p>They are written as <code>impl</code> followed by a set of trait bounds.</p>
<a class="header" href="print.html#self-types" id="self-types"><h2>Self types</h2></a>
<p>The special type <code>Self</code> has a meaning within traits and implementations: it
refers to the implementing type. For example, in:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
pub trait From&lt;T&gt; {
    fn from(T) -&gt; Self;
}

impl From&lt;i32&gt; for String {
    fn from(x: i32) -&gt; Self {
        x.to_string()
    }
}
#}</code></pre></pre>
<p>The notation <code>Self</code> in the impl refers to the implementing type: <code>String</code>. In
another example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Printable {
    fn make_string(&amp;self) -&gt; String;
}

impl Printable for String {
    fn make_string(&amp;self) -&gt; String {
        (*self).clone()
    }
}
#}</code></pre></pre>
<blockquote>
<p>Note: The notation <code>&amp;self</code> is a shorthand for <code>self: &amp;Self</code>.</p>
</blockquote>
<a class="header" href="print.html#dynamically-sized-types" id="dynamically-sized-types"><h1>Dynamically Sized Types</h1></a>
<p>Most types have a fixed size that is known at compile time and implement the
trait <a href="special-types-and-traits.html#sized"><code>Sized</code></a>. A type with a size that is known only at run-time is
called a <em>dynamically sized type</em> (<em>DST</em>) or, informally, an unsized type.
<a href="types.html#array-and-slice-types">Slices</a> and <a href="types.html#trait-objects">trait objects</a> are two examples of <abbr title="dynamically sized
types">DSTs</abbr>. Such types can only be used in certain cases:</p>
<ul>
<li><a href="types.html#pointer-types">Pointer types</a> to <abbr title="dynamically sized types">DSTs</abbr> are
sized but have twice the size of pointers to sized types
<ul>
<li>Pointers to slices also store the number of elements of the slice.</li>
<li>Pointers to trait objects also store a pointer to a vtable.</li>
</ul>
</li>
<li><abbr title="dynamically sized types">DSTs</abbr> can be provided as
type arguments when a bound of <code>?Sized</code>. By default any type parameter
has a <code>Sized</code> bound.</li>
<li>Traits may be implemented for <abbr title="dynamically sized
types">DSTs</abbr>. Unlike type parameters <code>Self: ?Sized</code> by default in trait
definitions.</li>
<li>Structs may contain a <abbr title="dynamically sized type">DST</abbr> as the
last field, this makes the struct itself a
<abbr title="dynamically sized type">DST</abbr>.</li>
</ul>
<p>Notably: <a href="variables.html">variables</a>, function parameters, <a href="items/constant-items.html">const</a> and <a href="items/static-items.html">static</a> items must be
<code>Sized</code>.</p>
<a class="header" href="print.html#type-layout" id="type-layout"><h1>Type Layout</h1></a>
<p>The layout of a type is its size, alignment, and the relative offsets of its
fields. For enums, how the discriminant is laid out and interpreted is also part
of type layout.</p>
<p>Type layout can be changed with each compilation. Instead of trying to document
exactly what is done, we only document what is guaranteed today.</p>
<a class="header" href="print.html#size-and-alignment" id="size-and-alignment"><h2>Size and Alignment</h2></a>
<p>All values have an alignment and size.</p>
<p>The <em>alignment</em> of a value specifies what addresses are valid to store the value
at. A value of alignment <code>n</code> must only be stored at an address that is a
multiple of n. For example, a value with an alignment of 2 must be stored at an
even address, while a value with an alignment of 1 can be stored at any address.
Alignment is measured in bytes, and must be at least 1, and always a power of 2.
The alignment of a value can be checked with the <a href="../std/mem/fn.align_of_val.html"><code>align_of_val</code></a> function.</p>
<p>The <em>size</em> of a value is the offset in bytes between successive elements in an
array with that item type including alignment padding. The size of a value is
always a multiple of its alignment. The size of a value can be checked with the
<a href="../std/mem/fn.size_of_val.html"><code>size_of_val</code></a> function.</p>
<p>Types where all values have the same size and alignment known at compile time
implement the <a href="../std/marker/trait.Sized.html"><code>Sized</code></a> trait and can be checked with the <a href="../std/mem/fn.size_of.html"><code>size_of</code></a> and
<a href="../std/mem/fn.align_of.html"><code>align_of</code></a> functions. Types that are not <a href="../std/marker/trait.Sized.html"><code>Sized</code></a> are known as <a href="dynamically-sized-types.html">dynamically
sized types</a>. Since all values of a <code>Sized</code> type share the same size and
alignment, we refer to those shared values as the size of the type and the
alignment of the type respectively.</p>
<a class="header" href="print.html#primitive-data-layout" id="primitive-data-layout"><h2>Primitive Data Layout</h2></a>
<p>The size of most primitives is given in this table.</p>
<table><thead><tr><th>Type </th><th> <code>size_of::&lt;Type&gt;()</code></th></tr></thead><tbody>
<tr><td>bool </td><td> 1</td></tr>
<tr><td>u8 </td><td> 1</td></tr>
<tr><td>u16 </td><td> 2</td></tr>
<tr><td>u32 </td><td> 4</td></tr>
<tr><td>u64 </td><td> 8</td></tr>
<tr><td>u128 </td><td> 16</td></tr>
<tr><td>i8 </td><td> 1</td></tr>
<tr><td>i16 </td><td> 2</td></tr>
<tr><td>i32 </td><td> 4</td></tr>
<tr><td>i64 </td><td> 8</td></tr>
<tr><td>i128 </td><td> 16</td></tr>
<tr><td>f32 </td><td> 4</td></tr>
<tr><td>f64 </td><td> 8</td></tr>
<tr><td>char </td><td> 4</td></tr>
</tbody></table>
<p><code>usize</code> and <code>isize</code> have a size big enough to contain every address on the
target platform. For example, on a 32 bit target, this is 4 bytes and on a 64
bit target, this is 8 bytes.</p>
<p>Most primitives are generally aligned to their size, although this is
platform-specific behavior. In particular, on x86 u64 and f64 are only
aligned to 32 bits.</p>
<a class="header" href="print.html#pointers-and-references-layout" id="pointers-and-references-layout"><h2>Pointers and References Layout</h2></a>
<p>Pointers and references have the same layout. Mutability of the pointer or
reference does not change the layout.</p>
<p>Pointers to sized types have the same size and alignment as <code>usize</code>.</p>
<p>Pointers to unsized types are sized. The size and alignment is guaranteed to be
at least equal to the size and alignment of a pointer.</p>
<blockquote>
<p>Note: Though you should not rely on this, all pointers to <abbr
title="Dynamically Sized Types">DSTs</abbr> are currently twice the size of
the size of <code>usize</code> and have the same alignment.</p>
</blockquote>
<a class="header" href="print.html#array-layout" id="array-layout"><h2>Array Layout</h2></a>
<p>Arrays are laid out so that the <code>nth</code> element of the array is offset from the
start of the array by <code>n * the size of the type</code> bytes. An array of <code>[T; n]</code>
has a size of <code>size_of::&lt;T&gt;() * n</code> and the same alignment of <code>T</code>.</p>
<a class="header" href="print.html#slice-layout" id="slice-layout"><h2>Slice Layout</h2></a>
<p>Slices have the same layout as the section of the array they slice.</p>
<blockquote>
<p>Note: This is about the raw <code>[T]</code> type, not pointers (<code>&amp;[T]</code>, <code>Box&lt;[T]&gt;</code>,
etc.) to slices.</p>
</blockquote>
<a class="header" href="print.html#tuple-layout" id="tuple-layout"><h2>Tuple Layout</h2></a>
<p>Tuples do not have any guarantees about their layout.</p>
<p>The exception to this is the unit tuple (<code>()</code>) which is guaranteed as a
zero-sized type to have a size of 0 and an alignment of 1.</p>
<a class="header" href="print.html#trait-object-layout" id="trait-object-layout"><h2>Trait Object Layout</h2></a>
<p>Trait objects have the same layout as the value the trait object is of.</p>
<blockquote>
<p>Note: This is about the raw trait object types, not pointers (<code>&amp;Trait</code>,
<code>Box&lt;Trait&gt;</code>, etc.) to trait objects.</p>
</blockquote>
<a class="header" href="print.html#closure-layout" id="closure-layout"><h2>Closure Layout</h2></a>
<p>Closures have no layout guarantees.</p>
<a class="header" href="print.html#representations" id="representations"><h2>Representations</h2></a>
<p>All user-defined composite types (<code>struct</code>s, <code>enum</code>s, and <code>union</code>s) have a
<em>representation</em> that specifies what the layout is for the type.</p>
<p>The possible representations for a type are the default representation, <code>C</code>, the
primitive representations, and <code>packed</code>. Multiple representations can be applied
to a single type.</p>
<p>The representation of a type can be changed by applying the [<code>repr</code> attribute]
to it. The following example shows a struct with a <code>C</code> representation.</p>
<pre><code>#[repr(C)]
struct ThreeInts {
    first: i16,
    second: i8,
    third: i32
}
</code></pre>
<blockquote>
<p>Note: As a consequence of the representation being an attribute on the item,
the representation does not depend on generic parameters. Any two types with
the same name have the same representation. For example, <code>Foo&lt;Bar&gt;</code> and
<code>Foo&lt;Baz&gt;</code> both have the same representation.</p>
</blockquote>
<p>The representation of a type does not change the layout of its fields. For
example, a struct with a <code>C</code> representation that contains a struct <code>Inner</code> with
the default representation will not change the layout of Inner.</p>
<a class="header" href="print.html#the-default-representation" id="the-default-representation"><h3>The Default Representation</h3></a>
<p>Nominal types without a <code>repr</code> attribute have the default representation.
Informally, this representation is also called the <code>rust</code> representation.</p>
<p>There are no guarantees of data layout made by this representation.</p>
<a class="header" href="print.html#the-c-representation" id="the-c-representation"><h3>The <code>C</code> Representation</h3></a>
<p>The <code>C</code> representation is designed for dual purposes. One purpose is for
creating types that are interoptable with the C Language. The second purpose is
to create types that you can soundly performing operations that rely on data
layout such as reinterpreting values as a different type.</p>
<p>Because of this dual purpose, it is possible to create types that are not useful
for interfacing with the C programming language.</p>
<p>This representation can be applied to structs, unions, and enums.</p>
<a class="header" href="print.html#reprc-structs" id="reprc-structs"><h4>#[repr(C)] Structs</h4></a>
<p>The alignment of the struct is the alignment of the most-aligned field in it.</p>
<p>The size and offset of fields is determined by the following algorithm.</p>
<p>Start with a current offset of 0 bytes.</p>
<p>For each field in declaration order in the struct, first determine the size and
alignment of the field. If the current offset is not a multiple of the field's
alignment, then add padding bytes to the current offset until it is a multiple
of the field's alignment. The offset for the field is what the current offset
is now. Then increase the current offset by the size of the field.</p>
<p>Finally, the size of the struct is the current offset rounded up to the nearest
multiple of the struct's alignment.</p>
<p>Here is this algorithm described in pseudocode.</p>
<pre><code class="language-rust ignore">struct.alignment = struct.fields().map(|field| field.alignment).max();

let current_offset = 0;

for field in struct.fields_in_declaration_order() {
    // Increase the current offset so that it's a multiple of the alignment
    // of this field. For the first field, this will always be zero.
    // The skipped bytes are called padding bytes.
    current_offset += field.alignment % current_offset;

    struct[field].offset = current_offset;

    current_offset += field.size;
}

struct.size = current_offset + current_offset % struct.alignment;
</code></pre>
<blockquote>
<p>Note: This algorithm can produce zero-sized structs. This differs from
C where structs without data still have a size of one byte.</p>
</blockquote>
<a class="header" href="print.html#reprc-unions" id="reprc-unions"><h4>#[repr(C)] Unions</h4></a>
<p>A union declared with <code>#[repr(C)]</code> will have the same size and alignment as an
equivalent C union declaration in the C language for the target platform.
The union will have a size of the maximum size of all of its fields rounded to
its alignment, and an alignment of the maximum alignment of all of its fields.
These maximums may come from different fields.</p>
<pre><code>#[repr(C)]
union Union {
    f1: u16,
    f2: [u8; 4],
}

assert_eq!(std::mem::size_of::&lt;Union&gt;(), 4);  // From f2
assert_eq!(std::mem::align_of::&lt;Union&gt;(), 2); // From f1

#[repr(C)]
union SizeRoundedUp {
   a: u32,
   b: [u16; 3],
}

assert_eq!(std::mem::size_of::&lt;SizeRoundedUp&gt;(), 8);  // Size of 6 from b,
                                                      // rounded up to 8 from
                                                      // alignment of a.
assert_eq!(std::mem::align_of::&lt;SizeRoundedUp&gt;(), 4); // From a
</code></pre>
<a class="header" href="print.html#reprc-enums" id="reprc-enums"><h4>#[repr(C)] Enums</h4></a>
<p>For <a href="items/enumerations.html#custom-discriminant-values-for-field-less-enumerations">C-like enumerations</a>, the <code>C</code> representation has the size and alignment of
the default <code>enum</code> size and alignment for the target platform's C ABI.</p>
<blockquote>
<p>Note: The enum representation in C is implementation defined, so this is
really a &quot;best guess&quot;. In particular, this may be incorrect when the C code
of interest is compiled with certain flags.</p>
</blockquote>
<blockquote>
<p>Warning: There are crucial differences between an <code>enum</code> in the C language and
Rust's C-like enumerations with this representation. An <code>enum</code> in  C is
mostly a <code>typedef</code> plus some named constants; in other words, an object of an
<code>enum</code> type can hold any integer value. For example, this is often used for
bitflags in <code>C</code>. In contrast, Rust’s C-like enumerations can only legally hold
the discriminant values, everything else is undefined behaviour. Therefore,
using a C-like enumeration in FFI to model a C <code>enum</code> is often wrong.</p>
</blockquote>
<p>It is an error for <a href="items/enumerations.html#zero-variant-enums">zero-variant enumerations</a> to have the <code>C</code> representation.</p>
<p>For all other enumerations, the layout is unspecified.</p>
<p>Likewise, combining the <code>C</code> representation with a primitive representation, the
layout is unspecified.</p>
<a class="header" href="print.html#primitive-representations" id="primitive-representations"><h3>Primitive representations</h3></a>
<p>The <em>primitive representations</em> are the representations with the same names as
the primitive integer types. That is: <code>u8</code>, <code>u16</code>, <code>u32</code>, <code>u64</code>, <code>usize</code>, <code>i8</code>,
<code>i16</code>, <code>i32</code>, <code>i64</code>, and <code>isize</code>.</p>
<p>Primitive representations can only be applied to enumerations.</p>
<p>For <a href="items/enumerations.html#custom-discriminant-values-for-field-less-enumerations">C-like enumerations</a>, they set the size and alignment to be the same as the
primitive type of the same name. For example, a C-like enumeration with a <code>u8</code>
representation can only have discriminants between 0 and 255 inclusive.</p>
<p>It is an error for <a href="items/enumerations.html#zero-variant-enums">zero-variant enumerations</a> to have a primitive
representation.</p>
<p>For all other enumerations, the layout is unspecified.</p>
<p>Likewise, combining two primitive representations together is unspecified.</p>
<a class="header" href="print.html#the-align-representation" id="the-align-representation"><h3>The <code>align</code> Representation</h3></a>
<p>The <code>align</code> representation can be used on <code>struct</code>s and <code>union</code>s to raise the
alignment of the type to a given value.</p>
<p>Alignment is specified as a parameter in the form of <code>#[repr(align(x))]</code>. The
alignment value must be a power of two of type <code>u32</code>. The <code>align</code> representation
can raise the alignment of a type to be greater than it's primitive alignment,
it cannot lower the alignment of a type.</p>
<p>The <code>align</code> and <code>packed</code> representations cannot be applied on the same type and
a <code>packed</code> type cannot transitively contain another <code>align</code>ed type.</p>
<a class="header" href="print.html#the-packed-representation" id="the-packed-representation"><h3>The <code>packed</code> Representation</h3></a>
<p>The <code>packed</code> representation can only be used on <code>struct</code>s and <code>union</code>s.</p>
<p>It modifies the representation (either the default or <code>C</code>) by removing any
padding bytes and forcing the alignment of the type to <code>1</code>.</p>
<p>The <code>align</code> and <code>packed</code> representations cannot be applied on the same type and
a <code>packed</code> type cannot transitively contain another <code>align</code>ed type.</p>
<blockquote>
<p>Warning: Dereferencing an unaligned pointer is [undefined behaviour] and it is
possible to <a href="https://github.com/rust-lang/rust/issues/27060">safely create unaligned pointers to <code>packed</code> fields</a>.
Like all ways to create undefined behavior in safe Rust, this is a bug.</p>
</blockquote>
<a class="header" href="print.html#interior-mutability" id="interior-mutability"><h1>Interior Mutability</h1></a>
<p>Sometimes a type needs be mutated while having multiple aliases. In Rust this
is achieved using a pattern called <em>interior mutability</em>. A type has interior
mutability if its internal state can be changed through a <a href="types.html#shared-references-">shared reference</a> to
it. This goes against the usual <a href="behavior-considered-undefined.html">requirement</a> that the value pointed to by a
shared reference is not mutated.</p>
<p><a href="../std/cell/struct.UnsafeCell.html"><code>std::cell::UnsafeCell&lt;T&gt;</code></a> type is the only allowed way in Rust to disable
this requirement. When <code>UnsafeCell&lt;T&gt;</code> is immutably aliased, it is still safe to
mutate, or obtain a mutable reference to, the <code>T</code> it contains. As with all
other types, it is undefined behavior to have multiple <code>&amp;mut UnsafeCell&lt;T&gt;</code>
aliases.</p>
<p>Other types with interior mutability can be created by using <code>UnsafeCell&lt;T&gt;</code> as
a field. The standard library provides a variety of types that provide safe
interior mutability APIs. For example, <a href="../std/cell/struct.RefCell.html"><code>std::cell::RefCell&lt;T&gt;</code></a> uses run-time
borrow checks to ensure the usual rules around multiple references. The
<a href="../std/sync/atomic/index.html"><code>std::sync::atomic</code></a> module contains types that wrap a value that is only
accessed with atomic operations, allowing the value to be shared and mutated
across threads.</p>
<a class="header" href="print.html#subtyping-and-variance" id="subtyping-and-variance"><h1>Subtyping and Variance</h1></a>
<p>Subtyping is implicit and can occur at any stage in type checking or
inference. Subtyping in Rust is very restricted and occurs only due to
variance with respect to lifetimes and between types with higher ranked
lifetimes. If we were to erase lifetimes from types, then the only subtyping
would be due to type equality.</p>
<p>Consider the following example: string literals always have <code>'static</code>
lifetime. Nevertheless, we can assign <code>s</code> to <code>t</code>:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn bar&lt;'a&gt;() {
    let s: &amp;'static str = &quot;hi&quot;;
    let t: &amp;'a str = s;
}
#}</code></pre></pre>
<p>Since <code>'static</code> outlives the lifetime parameter <code>'a</code>, <code>&amp;'static str</code> is a
subtype of <code>&amp;'a str</code>.</p>
<p><a href="../nomicon/hrtb.html">Higher-ranked</a> <a href="types.html#function-pointer-types">function pointers</a> and <a href="types.html#trait-objects">trait objects</a> have another
subtype relation. They are subtypes of types that are given by substitutions of
the higher-ranked lifetimes. Some examples:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// Here 'a is substituted for 'static
let subtype: &amp;(for&lt;'a&gt; fn(&amp;'a i32) -&gt; &amp;'a i32) = &amp;((|x| x) as fn(&amp;_) -&gt; &amp;_);
let supertype: &amp;(fn(&amp;'static i32) -&gt; &amp;'static i32) = subtype;

// This works similarly for trait objects
let subtype: &amp;(for&lt;'a&gt; Fn(&amp;'a i32) -&gt; &amp;'a i32) = &amp;|x| x;
let supertype: &amp;(Fn(&amp;'static i32) -&gt; &amp;'static i32) = subtype;

// We can also substitute one higher-ranked lifetime for another
let subtype: &amp;(for&lt;'a, 'b&gt; fn(&amp;'a i32, &amp;'b i32))= &amp;((|x, y| {}) as fn(&amp;_, &amp;_));
let supertype: &amp;for&lt;'c&gt; fn(&amp;'c i32, &amp;'c i32) = subtype;
#}</code></pre></pre>
<a class="header" href="print.html#variance" id="variance"><h2>Variance</h2></a>
<p>Variance is a property that generic types have with respect to their arguments.
A generic type's <em>variance</em> in a parameter is how the subtyping of the
parameter affects the subtyping of the type.</p>
<ul>
<li><code>F&lt;T&gt;</code> is <em>covariant</em> over <code>T</code> if <code>T</code> being a subtype of <code>U</code> implies that
<code>F&lt;T&gt;</code> is a subtype of <code>F&lt;U&gt;</code> (subtyping &quot;passes through&quot;)</li>
<li><code>F&lt;T&gt;</code> is <em>contravariant</em> over <code>T</code> if <code>T</code> being a subtype of <code>U</code> implies that
<code>F&lt;U&gt;</code> is a subtype of <code>F&lt;T&gt;</code></li>
<li><code>F&lt;T&gt;</code> is <em>invariant</em> over <code>T</code> otherwise (no subtyping relation can be
derived)</li>
</ul>
<p>Variance of types is automatically determined as follows</p>
<table><thead><tr><th> Type                          </th><th> Variance in <code>'a</code>  </th><th> Variance in <code>T</code>   </th></tr></thead><tbody>
<tr><td> <code>&amp;'a T</code>                       </td><td> covariant         </td><td> covariant         </td></tr>
<tr><td> <code>&amp;'a mut T</code>                   </td><td> covariant         </td><td> invariant         </td></tr>
<tr><td> <code>*const T</code>                    </td><td>                   </td><td> covariant         </td></tr>
<tr><td> <code>*mut T</code>                      </td><td>                   </td><td> invariant         </td></tr>
<tr><td> <code>[T]</code> and <code>[T; n]</code>            </td><td>                   </td><td> covariant         </td></tr>
<tr><td> <code>fn() -&gt; T</code>                   </td><td>                   </td><td> covariant         </td></tr>
<tr><td> <code>fn(T) -&gt; ()</code>                 </td><td>                   </td><td> contravariant     </td></tr>
<tr><td> <code>std::cell::UnsafeCell&lt;T&gt;</code>    </td><td>                   </td><td> invariant         </td></tr>
<tr><td> <code>std::marker::PhantomData&lt;T&gt;</code> </td><td>                   </td><td> covariant         </td></tr>
<tr><td> <code>Trait&lt;T&gt; + 'a</code>               </td><td> covariant         </td><td> invariant         </td></tr>
</tbody></table>
<p>The variance of other <code>struct</code>, <code>enum</code>, <code>union</code> and tuple types is decided by
looking at the variance of the types of their fields. If the parameter is used
in positions with different variances then the parameter is invariant. For
example the following struct is covariant in <code>'a</code> and <code>T</code> and invariant in <code>'b</code>
and <code>U</code>.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
use std::cell::UnsafeCell;
struct Variance&lt;'a, 'b, T, U: 'a&gt; {
    x: &amp;'a U,               // This makes `Variance` covariant in 'a, and would
                            // make it covariant in U, but U is used later
    y: *const T,            // Covariant in T
    z: UnsafeCell&lt;&amp;'b f64&gt;, // Invariant in 'b
    w: *mut U,              // Invariant in U, makes the whole struct invariant
}
#}</code></pre></pre>
<a class="header" href="print.html#trait-and-lifetime-bounds" id="trait-and-lifetime-bounds"><h1>Trait and lifetime bounds</h1></a>
<blockquote>
<p><strong><sup>Syntax</sup></strong><br />
<em>TypeParamBounds</em> :<br />
   <em>TypeParamBound</em> ( <code>+</code> <em>TypeParamBound</em> )<sup>*</sup> <code>+</code><sup>?</sup></p>
<p><em>TypeParamBound</em> :<br />
      <em>Lifetime</em> | <em>TraitBound</em></p>
<p><em>TraitBound</em> :<br />
      <code>?</code><sup>?</sup>
<a href="print.html#higher-ranked-trait-bounds"><em>ForLifetimes</em></a><sup>?</sup> <a href="paths.html"><em>TraitPath</em></a><br />
   | <code>(</code> <code>?</code><sup>?</sup>
<a href="print.html#higher-ranked-trait-bounds"><em>ForLifetimes</em></a><sup>?</sup> <a href="paths.html"><em>TraitPath</em></a> <code>)</code></p>
<p><em>LifetimeBounds</em> :<br />
   ( <em>Lifetime</em> <code>+</code> )<sup>*</sup> <em>Lifetime</em><sup>?</sup></p>
<p><em>Lifetime</em> :<br />
      <a href="tokens.html#lifetimes-and-loop-labels">LIFETIME_OR_LABEL</a><br />
   | <code>'static</code><br />
   | <code>'_</code></p>
</blockquote>
<p><a href="items/traits.html#trait-bounds">Trait</a> and lifetime bounds provide a way for <a href="items/generics.html">generic items</a> to
restrict which types and lifetimes are used as their parameters. Bounds can be
provided on any type in a <a href="items/generics.html#where-clauses">where clause</a>. There are also shorter forms for
certain common cases:</p>
<ul>
<li>Bounds written after declaring a <a href="items/generics.html">generic parameter</a>:
<code>fn f&lt;A: Copy&gt;() {}</code> is the same as <code>fn f&lt;A&gt; where A: Copy () {}</code>.</li>
<li>In trait declarations as <a href="items/traits.html#supertraits">supertraits</a>: <code>trait Circle : Shape {}</code> is
equivalent to <code>trait Circle where Self : Shape {}</code>.</li>
<li>In trait declarations as bounds on <a href="items/associated-items.html#associated-types">associated types</a>:
<code>trait A { type B: Copy; }</code> is equivalent to
<code>trait A where Self::B: Copy { type B; }</code>.</li>
</ul>
<p>Bounds on an item must be satisfied when using the item. When type checking and
borrow checking a generic item, the bounds can be used to determine that a
trait is implemented for a type. For example, given <code>Ty: Trait</code></p>
<ul>
<li>In the body of a generic function, methods from <code>Trait</code> can be called on <code>Ty</code>
values. Likewise associated constants on the <code>Trait</code> can be used.</li>
<li>Associated types from <code>Trait</code> can be used.</li>
<li>Generic functions and types with a <code>T: Trait</code> bounds can be used with <code>Ty</code>
being used for <code>T</code>.</li>
</ul>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
# type Surface = i32;
trait Shape {
    fn draw(&amp;self, Surface);
    fn name() -&gt; &amp;'static str;
}

fn draw_twice&lt;T: Shape&gt;(surface: Surface, sh: T) {
    sh.draw(surface);           // Can call method because T: Shape
    sh.draw(surface);
}

fn copy_and_draw_twice&lt;T: Copy&gt;(surface: Surface, sh: T) where T: Shape {
    let shape_copy = sh;        // doesn't move sh because T: Copy
    draw_twice(surface, sh);    // Can use generic function because T: Shape
}

struct Figure&lt;S: Shape&gt;(S, S);

fn name_figure&lt;U: Shape&gt;(
    figure: Figure&lt;U&gt;,          // Type Figure&lt;U&gt; is well-formed because U: Shape
) {
    println!(
        &quot;Figure of two {}&quot;,
        U::name(),              // Can use associated function
    );
}
#}</code></pre></pre>
<p>Trait and lifetime bounds are also used to name <a href="types.html#trait-objects">trait objects</a>.</p>
<a class="header" href="print.html#sized" id="sized"><h2><code>?Sized</code></h2></a>
<p><code>?</code> is only used to declare that the <a href="special-types-and-traits.html#sized"><code>Sized</code></a> trait may not be
implemented for a type parameter or associated type. <code>?Sized</code> may
not be used as a bound for other types.</p>
<a class="header" href="print.html#lifetime-bounds" id="lifetime-bounds"><h2>Lifetime bounds</h2></a>
<p>Lifetime bounds can be applied to types or other lifetimes. The bound <code>'a: 'b</code>
is usually read as <code>'a</code> <em>outlives</em> <code>'b</code>. <code>'a: 'b</code> means that <code>'a</code> lasts longer
than <code>'b</code>, so a reference <code>&amp;'a ()</code> is valid whenever <code>&amp;'b ()</code> is valid.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn f&lt;'a, 'b&gt;(x: &amp;'a i32, mut y: &amp;'b i32) where 'a: 'b {
    y = x;                      // &amp;'a i32 is a subtype of &amp;'b i32 because 'a: 'b
    let r: &amp;'b &amp;'a i32 = &amp;&amp;0;   // &amp;'b &amp;'a i32 is well formed because 'a: 'b
}
#}</code></pre></pre>
<p><code>T: 'a</code> means that all lifetime parameters of <code>T</code> outlive <code>'a</code>. For example if
<code>'a</code> is an unconstrained lifetime parameter then <code>i32: 'static</code> and
<code>&amp;'static str: 'a</code> are satisfied but <code>Vec&lt;&amp;'a ()&gt;: 'static</code> is not.</p>
<a class="header" href="print.html#higher-ranked-trait-bounds" id="higher-ranked-trait-bounds"><h2>Higher-ranked trait bounds</h2></a>
<p>Type bounds may be <em>higher ranked</em> over lifetimes. These bounds specify a bound
is true <em>for all</em> lifetimes. For example, a bound such as <code>for&lt;'a&gt; &amp;'a T: PartialEq&lt;i32&gt;</code> would require an implementation like</p>
<pre><code class="language-rust ignore">impl&lt;'a&gt; PartialEq&lt;i32&gt; for &amp;'a T {
    // ...
}
</code></pre>
<p>and could then be used to compare a <code>&amp;'a T</code> with any lifetime to an <code>i32</code>.</p>
<p>Only a higher-ranked bound can be used here as the lifetime of the reference is
shorter than a lifetime parameter on the function:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn call_on_ref_zero&lt;F&gt;(f: F) where for&lt;'a&gt; F: Fn(&amp;'a i32) {
    let zero = 0;
    f(&amp;zero);
}
#}</code></pre></pre>
<p>Higher-ranked lifetimes may also be specified just before the trait, the only
end of the following trait instead of the whole bound. This function is
difference is the scope of the lifetime parameter, which extends only to the
equivalent to the last one.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn call_on_ref_zero&lt;F&gt;(f: F) where F: for&lt;'a&gt; Fn(&amp;'a i32) {
    let zero = 0;
    f(&amp;zero);
}
#}</code></pre></pre>
<blockquote>
<p>Warning: lifetime bounds are allowed on lifetimes in a <code>for</code> binder, but have
no effect: <code>for&lt;'a, 'b: 'a&gt;</code> is no different to <code>for&lt;'a, 'b&gt;</code>.</p>
</blockquote>
<a class="header" href="print.html#type-coercions" id="type-coercions"><h1>Type coercions</h1></a>
<p>Coercions are defined in <a href="https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md">RFC 401</a>. <a href="https://github.com/rust-lang/rfcs/blob/master/text/1558-closure-to-fn-coercion.md">RFC 1558</a> then expanded on that.
A coercion is implicit and has no syntax.</p>
<a class="header" href="print.html#coercion-sites" id="coercion-sites"><h2>Coercion sites</h2></a>
<p>A coercion can only occur at certain coercion sites in a program; these are
typically places where the desired type is explicit or can be derived by
propagation from explicit types (without type inference). Possible coercion
sites are:</p>
<ul>
<li>
<p><code>let</code> statements where an explicit type is given.</p>
<p>For example, <code>42</code> is coerced to have type <code>i8</code> in the following:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
let _: i8 = 42;
#}</code></pre></pre>
</li>
<li>
<p><code>static</code> and <code>const</code> statements (similar to <code>let</code> statements).</p>
</li>
<li>
<p>Arguments for function calls</p>
<p>The value being coerced is the actual parameter, and it is coerced to
the type of the formal parameter.</p>
<p>For example, <code>42</code> is coerced to have type <code>i8</code> in the following:</p>
<pre><pre class="playpen"><code class="language-rust">fn bar(_: i8) { }

fn main() {
    bar(42);
}
</code></pre></pre>
<p>For method calls, the receiver (<code>self</code> parameter) can only take advantage
of <a href="print.html#unsized-coercions">unsized coercions</a>.</p>
</li>
<li>
<p>Instantiations of struct or variant fields</p>
<p>For example, <code>42</code> is coerced to have type <code>i8</code> in the following:</p>
<pre><pre class="playpen"><code class="language-rust">struct Foo { x: i8 }

fn main() {
    Foo { x: 42 };
}
</code></pre></pre>
</li>
<li>
<p>Function results, either the final line of a block if it is not
semicolon-terminated or any expression in a <code>return</code> statement</p>
<p>For example, <code>42</code> is coerced to have type <code>i8</code> in the following:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
fn foo() -&gt; i8 {
    42
}
#}</code></pre></pre>
</li>
</ul>
<p>If the expression in one of these coercion sites is a coercion-propagating
expression, then the relevant sub-expressions in that expression are also
coercion sites. Propagation recurses from these new coercion sites.
Propagating expressions and their relevant sub-expressions are:</p>
<ul>
<li>
<p>Array literals, where the array has type <code>[U; n]</code>. Each sub-expression in
the array literal is a coercion site for coercion to type <code>U</code>.</p>
</li>
<li>
<p>Array literals with repeating syntax, where the array has type <code>[U; n]</code>. The
repeated sub-expression is a coercion site for coercion to type <code>U</code>.</p>
</li>
<li>
<p>Tuples, where a tuple is a coercion site to type <code>(U_0, U_1, ..., U_n)</code>.
Each sub-expression is a coercion site to the respective type, e.g. the
zeroth sub-expression is a coercion site to type <code>U_0</code>.</p>
</li>
<li>
<p>Parenthesized sub-expressions (<code>(e)</code>): if the expression has type <code>U</code>, then
the sub-expression is a coercion site to <code>U</code>.</p>
</li>
<li>
<p>Blocks: if a block has type <code>U</code>, then the last expression in the block (if
it is not semicolon-terminated) is a coercion site to <code>U</code>. This includes
blocks which are part of control flow statements, such as <code>if</code>/<code>else</code>, if
the block has a known type.</p>
</li>
</ul>
<a class="header" href="print.html#coercion-types" id="coercion-types"><h2>Coercion types</h2></a>
<p>Coercion is allowed between the following types:</p>
<ul>
<li>
<p><code>T</code> to <code>U</code> if <code>T</code> is a subtype of <code>U</code> (<em>reflexive case</em>)</p>
</li>
<li>
<p><code>T_1</code> to <code>T_3</code> where <code>T_1</code> coerces to <code>T_2</code> and <code>T_2</code> coerces to <code>T_3</code>
(<em>transitive case</em>)</p>
<p>Note that this is not fully supported yet</p>
</li>
<li>
<p><code>&amp;mut T</code> to <code>&amp;T</code></p>
</li>
<li>
<p><code>*mut T</code> to <code>*const T</code></p>
</li>
<li>
<p><code>&amp;T</code> to <code>*const T</code></p>
</li>
<li>
<p><code>&amp;mut T</code> to <code>*mut T</code></p>
</li>
<li>
<p><code>&amp;T</code> or <code>&amp;mut T</code> to <code>&amp;U</code> if <code>T</code> implements <code>Deref&lt;Target = U&gt;</code>. For example:</p>
<pre><pre class="playpen"><code class="language-rust">use std::ops::Deref;

struct CharContainer {
    value: char,
}

impl Deref for CharContainer {
    type Target = char;

    fn deref&lt;'a&gt;(&amp;'a self) -&gt; &amp;'a char {
        &amp;self.value
    }
}

fn foo(arg: &amp;char) {}

fn main() {
    let x = &amp;mut CharContainer { value: 'y' };
    foo(x); //&amp;mut CharContainer is coerced to &amp;char.
}
</code></pre></pre>
</li>
<li>
<p><code>&amp;mut T</code> to <code>&amp;mut U</code> if <code>T</code> implements <code>DerefMut&lt;Target = U&gt;</code>.</p>
</li>
<li>
<p>TyCtor(<code>T</code>) to TyCtor(<code>U</code>), where TyCtor(<code>T</code>) is one of</p>
<ul>
<li><code>&amp;T</code></li>
<li><code>&amp;mut T</code></li>
<li><code>*const T</code></li>
<li><code>*mut T</code></li>
<li><code>Box&lt;T&gt;</code></li>
</ul>
<p>and where <code>T</code> can obtained from <code>U</code> by <a href="print.html#unsized-coercions">unsized coercion</a>.</p>
  <!--In the future, coerce_inner will be recursively extended to tuples and
  structs. In addition, coercions from sub-traits to super-traits will be
  added. See [RFC 401] for more details.-->
</li>
<li>
<p>Non capturing closures to <code>fn</code> pointers</p>
</li>
<li>
<p><code>!</code> to any <code>T</code></p>
</li>
</ul>
<a class="header" href="print.html#unsized-coercions" id="unsized-coercions"><h3>Unsized Coercions</h3></a>
<p>The following coercions are called <code>unsized coercions</code>, since they
relate to converting sized types to unsized types, and are permitted in a few
cases where other coercions are not, as described above. They can still happen
anywhere else a coercion can occur.</p>
<p>Two traits, [<code>Unsize</code>] and [<code>CoerceUnsized</code>], are used
to assist in this process and expose it for library use. The compiler following
coercions are built-in and, if <code>T</code> can be coerced to <code>U</code> with one of the, then
the compiler will provide an implementation of <code>Unsize&lt;U&gt;</code> for <code>T</code>:</p>
<ul>
<li>
<p><code>[T; n]</code> to <code>[T]</code>.</p>
</li>
<li>
<p><code>T</code> to <code>U</code>, when <code>U</code> is a trait object type and either <code>T</code> implements <code>U</code> or
<code>T</code> is a trait object for a subtrait of <code>U</code>.</p>
</li>
<li>
<p><code>Foo&lt;..., T, ...&gt;</code> to <code>Foo&lt;..., U, ...&gt;</code>, when:</p>
<ul>
<li><code>Foo</code> is a struct.</li>
<li><code>T</code> implements <code>Unsize&lt;U&gt;</code>.</li>
<li>The last field of <code>Foo</code> has a type involving <code>T</code>.</li>
<li>If that field has type <code>Bar&lt;T&gt;</code>, then <code>Bar&lt;T&gt;</code> implements <code>Unsized&lt;Bar&lt;U&gt;&gt;</code>.</li>
<li>T is not part of the type of any other fields.</li>
</ul>
</li>
</ul>
<p>Additionally, a type <code>Foo&lt;T&gt;</code> can implement <code>CoerceUnsized&lt;Foo&lt;U&gt;&gt;</code> when <code>T</code>
implements <code>Unsize&lt;U&gt;</code> or <code>CoerceUnsized&lt;Foo&lt;U&gt;&gt;</code>. This allows it to provide a
unsized coercion to <code>Foo&lt;U&gt;</code>.</p>
<blockquote>
<p>Note: While the definition of the unsized coercions and their implementation
has been stabilized, the traits themselves are not yet stable and therefore
can't be used directly in stable Rust.</p>
</blockquote>
<a class="header" href="print.html#destructors" id="destructors"><h1>Destructors</h1></a>
<p>When an <a href="glossary.html#initialized">initialized</a> <a href="variables.html">variable</a> in Rust goes out of scope or a <a href="expressions.html#temporary-lifetimes">temporary</a>
is no longer needed its <em>destructor</em> is run. <a href="expressions/operator-expr.html#assignment-expressions">Assignment</a> also runs the
destructor of its left-hand operand, unless it's an uninitialized variable. If a
<a href="types.html#struct-types">struct</a> variable has been partially initialized, only its initialized fields
are dropped.</p>
<p>The destructor of a type consists of</p>
<ol>
<li>Calling its <a href="../std/ops/trait.Drop.html"><code>std::ops::Drop::drop</code></a> method, if it has one.</li>
<li>Recursively running the destructor of all of its fields.
<ul>
<li>The fields of a <a href="types.html#struct-types">struct</a>, <a href="types.html#tuple-types">tuple</a> or <a href="types.html#enumerated-types">enum variant</a> are dropped in
declaration order. *</li>
<li>The elements of an <a href="types.html#array-and-slice-types">array</a> or owned <a href="types.html#array-and-slice-types">slice</a> are dropped from the
first element to the last. *</li>
<li>The captured values of a <a href="types.html#closure-types">closure</a> are dropped in an unspecified order.</li>
<li><a href="types.html#trait-objects">Trait objects</a> run the destructor of the underlying type.</li>
<li>Other types don't result in any further drops.</li>
</ul>
</li>
</ol>
<p>* This order was stabilized in <a href="https://github.com/rust-lang/rfcs/blob/master/text/1857-stabilize-drop-order.md">RFC 1857</a>.</p>
<p>Variables are dropped in reverse order of declaration. Variables declared in
the same pattern drop in an unspecified ordered.</p>
<p>If a destructor must be run manually, such as when implementing your own smart
pointer, <a href="../std/ptr/fn.drop_in_place.html"><code>std::ptr::drop_in_place</code></a> can be used.</p>
<p>Some examples:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
struct ShowOnDrop(&amp;'static str);

impl Drop for ShowOnDrop {
    fn drop(&amp;mut self) {
        println!(&quot;{}&quot;, self.0);
    }
}

{
    let mut overwritten = ShowOnDrop(&quot;Drops when overwritten&quot;);
    overwritten = ShowOnDrop(&quot;drops when scope ends&quot;);
}
# println!(&quot;&quot;);
{
    let declared_first = ShowOnDrop(&quot;Dropped last&quot;);
    let declared_last = ShowOnDrop(&quot;Dropped first&quot;);
}
# println!(&quot;&quot;);
{
    // Tuple elements drop in forwards order
    let tuple = (ShowOnDrop(&quot;Tuple first&quot;), ShowOnDrop(&quot;Tuple second&quot;));
}
# println!(&quot;&quot;);
loop {
    // Tuple expression doesn't finish evaluating so temporaries drop in reverse order:
    let partial_tuple = (ShowOnDrop(&quot;Temp first&quot;), ShowOnDrop(&quot;Temp second&quot;), break);
}
# println!(&quot;&quot;);
{
    let moved;
    // No destructor run on assignment.
    moved = ShowOnDrop(&quot;Drops when moved&quot;);
    // drops now, but is then uninitialized
    moved;
    let uninitialized: ShowOnDrop;
    // Only first element drops
    let mut partially_initialized: (ShowOnDrop, ShowOnDrop);
    partially_initialized.0 = ShowOnDrop(&quot;Partial tuple first&quot;);
}
#}</code></pre></pre>
<a class="header" href="print.html#not-running-destructors" id="not-running-destructors"><h2>Not running destructors</h2></a>
<p>Not running destructors in Rust is safe even if it has a type that isn't
<code>'static</code>. <a href="../std/mem/union.ManuallyDrop.html"><code>std::mem::ManuallyDrop</code></a> provides a wrapper to prevent a
variable or field from being dropped automatically.</p>
<a class="header" href="print.html#lifetime-elision" id="lifetime-elision"><h1>Lifetime elision</h1></a>
<p>Rust has rules that allow lifetimes to be elided in various places where the
compiler can infer a sensible default choice.</p>
<a class="header" href="print.html#lifetime-elision-in-functions" id="lifetime-elision-in-functions"><h2>Lifetime elision in functions</h2></a>
<p>In order to make common patterns more ergonomic, lifetime arguments can be
<em>elided</em> in <a href="types.html#function-item-types">function item</a>, <a href="types.html#function-pointer-types">function pointer</a> and <a href="types.html#closure-types">closure trait</a> signatures.
The following rules are used to infer lifetime parameters for elided lifetimes.
It is an error to elide lifetime parameters that cannot be inferred. The
placeholder lifetime, <code>'_</code>, can also be used to have a lifetime inferred in the
same way. For lifetimes in paths, using <code>'_</code> is preferred. Trait object
lifetimes follow different rules discussed
<a href="print.html#default-trait-object-lifetimes">below</a>.</p>
<ul>
<li>Each elided lifetime in the parameters becomes a distinct lifetime parameter.</li>
<li>If there is exactly one lifetime used in the parameters (elided or not), that
lifetime is assigned to <em>all</em> elided output lifetimes.</li>
</ul>
<p>In method signatures there is another rule</p>
<ul>
<li>If the receiver has type <code>&amp;Self</code>  or <code>&amp;mut Self</code>, then the lifetime of that
reference to <code>Self</code> is assigned to all elided output lifetime parameters.</li>
</ul>
<p>Examples:</p>
<pre><code class="language-rust ignore">fn print(s: &amp;str);                                      // elided
fn print(s: &amp;'_ str);                                   // also elided
fn print&lt;'a&gt;(s: &amp;'a str);                               // expanded

fn debug(lvl: usize, s: &amp;str);                          // elided
fn debug&lt;'a&gt;(lvl: usize, s: &amp;'a str);                   // expanded

fn substr(s: &amp;str, until: usize) -&gt; &amp;str;               // elided
fn substr&lt;'a&gt;(s: &amp;'a str, until: usize) -&gt; &amp;'a str;     // expanded

fn get_str() -&gt; &amp;str;                                   // ILLEGAL

fn frob(s: &amp;str, t: &amp;str) -&gt; &amp;str;                      // ILLEGAL

fn get_mut(&amp;mut self) -&gt; &amp;mut T;                        // elided
fn get_mut&lt;'a&gt;(&amp;'a mut self) -&gt; &amp;'a mut T;              // expanded

fn args&lt;T: ToCStr&gt;(&amp;mut self, args: &amp;[T]) -&gt; &amp;mut Command;                  // elided
fn args&lt;'a, 'b, T: ToCStr&gt;(&amp;'a mut self, args: &amp;'b [T]) -&gt; &amp;'a mut Command; // expanded

fn new(buf: &amp;mut [u8]) -&gt; BufWriter&lt;'_&gt;;                // elided - preferred
fn new(buf: &amp;mut [u8]) -&gt; BufWriter;                    // elided
fn new&lt;'a&gt;(buf: &amp;'a mut [u8]) -&gt; BufWriter&lt;'a&gt;;         // expanded

type FunPtr = fn(&amp;str) -&gt; &amp;str;                         // elided
type FunPtr = for&lt;'a&gt; fn(&amp;'a str) -&gt; &amp;'a str;           // expanded

type FunTrait = dyn Fn(&amp;str) -&gt; &amp;str;                   // elided
type FunTrait = dyn for&lt;'a&gt; Fn(&amp;'a str) -&gt; &amp;'a str;     // expanded
</code></pre>
<a class="header" href="print.html#default-trait-object-lifetimes" id="default-trait-object-lifetimes"><h2>Default trait object lifetimes</h2></a>
<p>The assumed lifetime of references held by a <a href="types.html#trait-objects">trait object</a> is called its
<em>default object lifetime bound</em>. These were defined in <a href="https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md">RFC 599</a> and amended in
<a href="https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md">RFC 1156</a>.</p>
<p>These default object lifetime bounds are used instead of the lifetime parameter
elision rules defined above when the lifetime bound is omitted entirely. If
<code>'_</code> is used as the lifetime bound then the bound follows the usual elision
rules.</p>
<p>If the trait object is used as a type argument of a generic type then the
containing type is first used to try to infer a bound.</p>
<ul>
<li>If there is a unique bound from the containing type then that is the default</li>
<li>If there is more than one bound from the containing type then an explicit
bound must be specified</li>
</ul>
<p>If neither of those rules apply, then the bounds on the trait are used:</p>
<ul>
<li>If the trait is defined with a single lifetime <em>bound</em> then that bound is
used.</li>
<li>If <code>'static</code> is used for any lifetime bound then <code>'static</code> is used.</li>
<li>If the trait has no lifetime bounds, then the lifetime is inferred in
expressions and is <code>'static</code> outside of expressions.</li>
</ul>
<pre><code class="language-rust ignore">// For the following trait...
trait Foo { }

// These two are the same as Box&lt;T&gt; has no lifetime bound on T
Box&lt;dyn Foo&gt;
Box&lt;dyn Foo + 'static&gt;

// ...and so are these:
impl dyn Foo {}
impl dyn Foo + 'static {}

// ...so are these, because &amp;'a T requires T: 'a
&amp;'a dyn Foo
&amp;'a (dyn Foo + 'a)

// std::cell::Ref&lt;'a, T&gt; also requires T: 'a, so these are the same
std::cell::Ref&lt;'a, dyn Foo&gt;
std::cell::Ref&lt;'a, dyn Foo + 'a&gt;

// This is an error:
struct TwoBounds&lt;'a, 'b, T: ?Sized + 'a + 'b&gt;
TwoBounds&lt;'a, 'b, dyn Foo&gt; // Error: the lifetime bound for this object type
                           // cannot be deduced from context
</code></pre>
<p>Note that the innermost object sets the bound, so <code>&amp;'a Box&lt;dyn Foo&gt;</code> is still
<code>&amp;'a Box&lt;dyn Foo + 'static&gt;</code>.</p>
<pre><code class="language-rust ignore">// For the following trait...
trait Bar&lt;'a&gt;: 'a { }

// ...these two are the same:
Box&lt;dyn Bar&lt;'a&gt;&gt;
Box&lt;dyn Bar&lt;'a&gt; + 'a&gt;

// ...and so are these:
impl&lt;'a&gt; dyn Foo&lt;'a&gt; {}
impl&lt;'a&gt; dyn Foo&lt;'a&gt; + 'a {}

// This is still an error:
struct TwoBounds&lt;'a, 'b, T: ?Sized + 'a + 'b&gt;
TwoBounds&lt;'a, 'b, dyn Foo&lt;'c&gt;&gt;
</code></pre>
<a class="header" href="print.html#static-lifetime-elision" id="static-lifetime-elision"><h2><code>'static</code> lifetime elision</h2></a>
<p>Both <a href="items/constant-items.html">constant</a> and <a href="items/static-items.html">static</a> declarations of reference types have <em>implicit</em>
<code>'static</code> lifetimes unless an explicit lifetime is specified. As such, the
constant declarations involving <code>'static</code> above may be written without the
lifetimes.</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
// STRING: &amp;'static str
const STRING: &amp;str = &quot;bitstring&quot;;

struct BitsNStrings&lt;'a&gt; {
    mybits: [u32; 2],
    mystring: &amp;'a str,
}

// BITS_N_STRINGS: BitsNStrings&lt;'static&gt;
const BITS_N_STRINGS: BitsNStrings&lt;'_&gt; = BitsNStrings {
    mybits: [1, 2],
    mystring: STRING,
};
#}</code></pre></pre>
<p>Note that if the <code>static</code> or <code>const</code> items include function or closure
references, which themselves include references, the compiler will first try
the standard elision rules. If it is unable to resolve the lifetimes by its
usual rules, then it will error. By way of example:</p>
<pre><code class="language-rust ignore">// Resolved as `fn&lt;'a&gt;(&amp;'a str) -&gt; &amp;'a str`.
const RESOLVED_SINGLE: fn(&amp;str) -&gt; &amp;str = ..

// Resolved as `Fn&lt;'a, 'b, 'c&gt;(&amp;'a Foo, &amp;'b Bar, &amp;'c Baz) -&gt; usize`.
const RESOLVED_MULTIPLE: &amp;dyn Fn(&amp;Foo, &amp;Bar, &amp;Baz) -&gt; usize = ..

// There is insufficient information to bound the return reference lifetime
// relative to the argument lifetimes, so this is an error.
const RESOLVED_STATIC: &amp;dyn Fn(&amp;Foo, &amp;Bar) -&gt; &amp;Baz = ..
</code></pre>
<a class="header" href="print.html#special-types-and-traits" id="special-types-and-traits"><h1>Special types and traits</h1></a>
<p>Certain types and traits that exist in <a href="../std/index.html">the standard library</a> are known to the
Rust compiler. This chapter documents the special features of these types and
traits.</p>
<a class="header" href="print.html#boxt" id="boxt"><h2><code>Box&lt;T&gt;</code></h2></a>
<p><a href="../std/boxed/struct.Box.html"><code>Box&lt;T&gt;</code></a> has a few special features that Rust doesn't currently allow for user
defined types.</p>
<ul>
<li>The <a href="expressions/operator-expr.html#the-dereference-operator">dereference operator</a> for <code>Box&lt;T&gt;</code> produces a place which can be moved
from. This means that the <code>*</code> operator and the destructor of <code>Box&lt;T&gt;</code> are
built-in to the language.</li>
<li><a href="items/associated-items.html#associated-functions-and-methods">Methods</a> can take <code>Box&lt;Self&gt;</code> as a receiver.</li>
<li>A trait may be implemented for <code>Box&lt;T&gt;</code> in the same crate as <code>T</code>, which the
<a href="items/implementations.html#trait-implementation-coherence">orphan rules</a> prevent for other generic types.</li>
</ul>
<a class="header" href="print.html#unsafecellt" id="unsafecellt"><h2><code>UnsafeCell&lt;T&gt;</code></h2></a>
<p><a href="../std/cell/struct.UnsafeCell.html"><code>std::cell::UnsafeCell&lt;T&gt;</code></a> is used for <a href="interior-mutability.html">interior mutability</a>. It ensures that
the compiler doesn't perform optimisations that are incorrect for such types.
It also ensures that <a href="items/static-items.html"><code>static</code> items</a> which have a type with interior
mutability aren't placed in memory marked as read only.</p>
<a class="header" href="print.html#phantomdatat" id="phantomdatat"><h2><code>PhantomData&lt;T&gt;</code></h2></a>
<p><a href="../std/marker/struct.PhantomData.html"><code>std::marker::PhantomData&lt;T&gt;</code></a> is a zero-sized, minimum alignment, type that
is considered to own a <code>T</code> for the purposes of <a href="subtyping.html#variance">variance</a>, <a href="../nomicon/dropck.html">drop check</a> and
<a href="print.html#auto-traits">auto traits</a>.</p>
<a class="header" href="print.html#operator-traits" id="operator-traits"><h2>Operator Traits</h2></a>
<p>The traits in <a href="../std/ops/index.html"><code>std::ops</code></a> and <a href="../std/cmp/index.html"><code>std::cmp</code></a> are used to overload <a href="expressions/operator-expr.html">operators</a>,
<a href="expressions/array-expr.html#array-and-slice-indexing-expressions">indexing expressions</a> and <a href="expressions/call-expr.html">call expressions</a>.</p>
<a class="header" href="print.html#deref-and-derefmut" id="deref-and-derefmut"><h2><code>Deref</code> and <code>DerefMut</code></h2></a>
<p>As well as overloading the unary <code>*</code> operator, <a href="../std/ops/trait.Deref.html"><code>Deref</code></a> and <a href="../std/ops/trait.DerefMut.html"><code>DerefMut</code></a> are
also used in <a href="expressions/method-call-expr.html">method resolution</a> and <a href="type-coercions.html#coercion-types">deref coercions</a>.</p>
<a class="header" href="print.html#drop" id="drop"><h2><code>Drop</code></h2></a>
<p>The <a href="../std/ops/trait.Drop.html"><code>Drop</code></a> trait provides a <a href="destructors.html">destructor</a>, to be run whenever a value of this
type is to be destroyed.</p>
<a class="header" href="print.html#copy" id="copy"><h2><code>Copy</code></h2></a>
<p>The <a href="../std/marker/trait.Copy.html"><code>Copy</code></a> trait changes the semantics of a type implementing it. Values
whose type implements <code>Copy</code> are copied rather than moved upon assignment.
<code>Copy</code> cannot be implemented for types which implement <code>Drop</code>, or which have
fields that are not <code>Copy</code>. <code>Copy</code> is implemented by the compiler for</p>
<ul>
<li><a href="types.html#numeric-types">Numeric types</a></li>
<li><code>char</code>, <code>bool</code> and <a href="types.html#never-type"><code>!</code></a></li>
<li><a href="types.html#tuple-types">Tuples</a> of <code>Copy</code> types</li>
<li><a href="types.html#array-and-slice-types">Arrays</a> of <code>Copy</code> types</li>
<li><a href="types.html#shared-references-">Shared references</a></li>
<li><a href="types.html#raw-pointers-const-and-mut">Raw pointers</a></li>
<li><a href="types.html#function-pointer-types">Function pointers</a> and <a href="types.html#function-item-types">function item types</a></li>
</ul>
<a class="header" href="print.html#clone" id="clone"><h2><code>Clone</code></h2></a>
<p>The <a href="../std/clone/trait.Clone.html"><code>Clone</code></a> trait is a supertrait of <code>Copy</code>, so it also needs compiler
generated implementations. It is implemented by the compiler for the following
types:</p>
<ul>
<li>Types with a built-in <code>Copy</code> implementation (see above)</li>
<li><a href="types.html#tuple-types">Tuples</a> of <code>Clone</code> types</li>
<li><a href="types.html#array-and-slice-types">Arrays</a> of <code>Clone</code> types</li>
</ul>
<a class="header" href="print.html#send" id="send"><h2><code>Send</code></h2></a>
<p>The <a href="../std/marker/trait.Send.html"><code>Send</code></a> trait indicates that a value of this type is safe to send from one
thread to another.</p>
<a class="header" href="print.html#sync" id="sync"><h2><code>Sync</code></h2></a>
<p>The <a href="../std/marker/trait.Sync.html"><code>Sync</code></a> trait indicates that a value of this type is safe to share between
multiple threads. This trait must be implemented for all types used in
immutable <a href="items/static-items.html"><code>static</code> items</a>.</p>
<a class="header" href="print.html#auto-traits" id="auto-traits"><h2>Auto traits</h2></a>
<p>The <a href="../std/marker/trait.Send.html"><code>Send</code></a>, <a href="../std/marker/trait.Sync.html"><code>Sync</code></a>, <a href="../std/panic/trait.UnwindSafe.html"><code>UnwindSafe</code></a> and <a href="../std/panic/trait.RefUnwindSafe.html"><code>RefUnwindSafe</code></a> traits are <em>auto
traits</em>. Auto traits have special properties.</p>
<p>If no explicit implementation or negative implementation is written out for an
auto trait for a given type, then the compiler implements it automatically
according to the following rules:</p>
<ul>
<li><code>&amp;T</code>, <code>&amp;mut T</code>, <code>*const T</code>, <code>*mut T</code>, <code>[T; n]</code> and <code>[T]</code> implement the trait
if <code>T</code> does.</li>
<li>Function item types and function pointers automatically implement the trait.</li>
<li>Structs, enums, unions and tuples implement the trait if all of their fields
do.</li>
<li>Closures implement the trait if the types of all of their captures do. A
closure that captures a <code>T</code> by shared reference and a <code>U</code> by value implements
any auto traits that both <code>&amp;T</code> and <code>U</code> do.</li>
</ul>
<p>For generic types (counting the built-in types above as generic over <code>T</code>), if an
generic implementation is available, then the compiler does not automatically
implement it for types that could use the implementation except that they do not
meet the requisite trait bounds. For instance, the standard library implements
<code>Send</code> for all <code>&amp;T</code> where <code>T</code> is <code>Sync</code>; this means that the compiler will not
implement <code>Send</code> for <code>&amp;T</code> if <code>T</code> is <code>Send</code> but not <code>Sync</code>.</p>
<p>Auto traits can also have negative implementations, shown as <code>impl !AutoTrait for T</code> in the standard library documentation, that override the automatic
implementations. For example <code>*mut T</code> has a negative implementation of <code>Send</code>,
and so <code>*mut T</code> is not <code>Send</code>, even if <code>T</code> is. There is currently no stable way
to specify additional negative implementations; they exist only in the standard
library.</p>
<p>Auto traits may be added as an additional bound to any <a href="types.html#trait-objects">trait object</a>, even
though normally only one trait is allowed. For instance, <code>Box&lt;dyn Debug + Send + UnwindSafe&gt;</code> is a valid type.</p>
<a class="header" href="print.html#sized-1" id="sized-1"><h2><code>Sized</code></h2></a>
<p>The <a href="../std/marker/trait.Sized.html"><code>Sized</code></a> trait indicates that the size of this type is known at
compile-time; that is, it's not a <a href="dynamically-sized-types.html">dynamically sized type</a>. <a href="types.html#type-parameters">Type parameters</a>
are <code>Sized</code> by default. <code>Sized</code> is always implemented automatically by the
compiler, not by <a href="items/implementations.html">implementation items</a>.</p>
<a class="header" href="print.html#memory-model" id="memory-model"><h1>Memory model</h1></a>
<p>A Rust program's memory consists of a static set of <em>items</em> and a <em>heap</em>.
Immutable portions of the heap may be safely shared between threads, mutable
portions may not be safely shared, but several mechanisms for effectively-safe
sharing of mutable values, built on unsafe code but enforcing a safe locking
discipline, exist in the standard library.</p>
<p>Allocations in the stack consist of <em>variables</em>, and allocations in the heap
consist of <em>boxes</em>.</p>
<a class="header" href="print.html#memory-allocation-and-lifetime" id="memory-allocation-and-lifetime"><h1>Memory allocation and lifetime</h1></a>
<p>The <em>items</em> of a program are those functions, modules and types that have their
value calculated at compile-time and stored uniquely in the memory image of the
rust process. Items are neither dynamically allocated nor freed.</p>
<p>The <em>heap</em> is a general term that describes boxes.  The lifetime of an
allocation in the heap depends on the lifetime of the box values pointing to
it. Since box values may themselves be passed in and out of frames, or stored
in the heap, heap allocations may outlive the frame they are allocated within.
An allocation in the heap is guaranteed to reside at a single location in the
heap for the whole lifetime of the allocation - it will never be relocated as
a result of moving a box value.</p>
<a class="header" href="print.html#memory-ownership" id="memory-ownership"><h2>Memory ownership</h2></a>
<p>When a stack frame is exited, its local allocations are all released, and its
references to boxes are dropped.</p>
<a class="header" href="print.html#variables" id="variables"><h1>Variables</h1></a>
<p>A <em>variable</em> is a component of a stack frame, either a named function parameter,
an anonymous <a href="expressions.html#temporary-lifetimes">temporary</a>, or a named local
variable.</p>
<p>A <em>local variable</em> (or <em>stack-local</em> allocation) holds a value directly,
allocated within the stack's memory. The value is a part of the stack frame.</p>
<p>Local variables are immutable unless declared otherwise. For example: <code>let mut x = ...</code>.</p>
<p>Function parameters are immutable unless declared with <code>mut</code>. The <code>mut</code> keyword
applies only to the following parameter. For example: <code>|mut x, y|</code> and <code>fn f(mut x: Box&lt;i32&gt;, y: Box&lt;i32&gt;)</code> declare one mutable variable <code>x</code> and one immutable
variable <code>y</code>.</p>
<p>Methods that take either <code>self</code> or <code>Box&lt;Self&gt;</code> can optionally place them in a
mutable variable by prefixing them with <code>mut</code> (similar to regular arguments). For example:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
trait Changer: Sized {
    fn change(mut self) {}
    fn modify(mut self: Box&lt;Self&gt;) {}
}
#}</code></pre></pre>
<p>Local variables are not initialized when allocated. Instead, the entire frame worth of
local variables are allocated, on frame-entry, in an uninitialized
state. Subsequent statements within a function may or may not initialize the
local variables. Local variables can be used only after they have been
initialized; this is enforced by the compiler.</p>
<a class="header" href="print.html#linkage" id="linkage"><h1>Linkage</h1></a>
<p>The Rust compiler supports various methods to link crates together both
statically and dynamically. This section will explore the various methods to
link Rust crates together, and more information about native libraries can be
found in the <a href="../book/ffi.html">FFI section of the book</a>.</p>
<p>In one session of compilation, the compiler can generate multiple artifacts
through the usage of either command line flags or the <code>crate_type</code> attribute.
If one or more command line flags are specified, all <code>crate_type</code> attributes will
be ignored in favor of only building the artifacts specified by command line.</p>
<ul>
<li>
<p><code>--crate-type=bin</code>, <code>#[crate_type = &quot;bin&quot;]</code> - A runnable executable will be
produced. This requires that there is a <code>main</code> function in the crate which
will be run when the program begins executing. This will link in all Rust and
native dependencies, producing a distributable binary.</p>
</li>
<li>
<p><code>--crate-type=lib</code>, <code>#[crate_type = &quot;lib&quot;]</code> - A Rust library will be produced.
This is an ambiguous concept as to what exactly is produced because a library
can manifest itself in several forms. The purpose of this generic <code>lib</code> option
is to generate the &quot;compiler recommended&quot; style of library. The output library
will always be usable by rustc, but the actual type of library may change from
time-to-time. The remaining output types are all different flavors of
libraries, and the <code>lib</code> type can be seen as an alias for one of them (but the
actual one is compiler-defined).</p>
</li>
<li>
<p><code>--crate-type=dylib</code>, <code>#[crate_type = &quot;dylib&quot;]</code> - A dynamic Rust library will
be produced. This is different from the <code>lib</code> output type in that this forces
dynamic library generation. The resulting dynamic library can be used as a
dependency for other libraries and/or executables. This output type will
create <code>*.so</code> files on linux, <code>*.dylib</code> files on osx, and <code>*.dll</code> files on
windows.</p>
</li>
<li>
<p><code>--crate-type=staticlib</code>, <code>#[crate_type = &quot;staticlib&quot;]</code> - A static system
library will be produced. This is different from other library outputs in that
the Rust compiler will never attempt to link to <code>staticlib</code> outputs. The
purpose of this output type is to create a static library containing all of
the local crate's code along with all upstream dependencies. The static
library is actually a <code>*.a</code> archive on linux and osx and a <code>*.lib</code> file on
windows. This format is recommended for use in situations such as linking
Rust code into an existing non-Rust application because it will not have
dynamic dependencies on other Rust code.</p>
</li>
<li>
<p><code>--crate-type=cdylib</code>, <code>#[crate_type = &quot;cdylib&quot;]</code> - A dynamic system
library will be produced.  This is used when compiling Rust code as
a dynamic library to be loaded from another language.  This output type will
create <code>*.so</code> files on Linux, <code>*.dylib</code> files on macOS, and <code>*.dll</code> files on
Windows.</p>
</li>
<li>
<p><code>--crate-type=rlib</code>, <code>#[crate_type = &quot;rlib&quot;]</code> - A &quot;Rust library&quot; file will be
produced. This is used as an intermediate artifact and can be thought of as a
&quot;static Rust library&quot;. These <code>rlib</code> files, unlike <code>staticlib</code> files, are
interpreted by the Rust compiler in future linkage. This essentially means
that <code>rustc</code> will look for metadata in <code>rlib</code> files like it looks for metadata
in dynamic libraries. This form of output is used to produce statically linked
executables as well as <code>staticlib</code> outputs.</p>
</li>
<li>
<p><code>--crate-type=proc-macro</code>, <code>#[crate_type = &quot;proc-macro&quot;]</code> - The output
produced is not specified, but if a <code>-L</code> path is provided to it then the
compiler will recognize the output artifacts as a macro and it can be loaded
for a program. If a crate is compiled with the <code>proc-macro</code> crate type it
will forbid exporting any items in the crate other than those functions
tagged <code>#[proc_macro_derive]</code> and those functions must also be placed at the
crate root. Finally, the compiler will automatically set the
<code>cfg(proc_macro)</code> annotation whenever any crate type of a compilation is the
<code>proc-macro</code> crate type.</p>
</li>
</ul>
<p>Note that these outputs are stackable in the sense that if multiple are
specified, then the compiler will produce each form of output at once without
having to recompile. However, this only applies for outputs specified by the
same method. If only <code>crate_type</code> attributes are specified, then they will all
be built, but if one or more <code>--crate-type</code> command line flags are specified,
then only those outputs will be built.</p>
<p>With all these different kinds of outputs, if crate A depends on crate B, then
the compiler could find B in various different forms throughout the system. The
only forms looked for by the compiler, however, are the <code>rlib</code> format and the
dynamic library format. With these two options for a dependent library, the
compiler must at some point make a choice between these two formats. With this
in mind, the compiler follows these rules when determining what format of
dependencies will be used:</p>
<ol>
<li>
<p>If a static library is being produced, all upstream dependencies are
required to be available in <code>rlib</code> formats. This requirement stems from the
reason that a dynamic library cannot be converted into a static format.</p>
<p>Note that it is impossible to link in native dynamic dependencies to a static
library, and in this case warnings will be printed about all unlinked native
dynamic dependencies.</p>
</li>
<li>
<p>If an <code>rlib</code> file is being produced, then there are no restrictions on what
format the upstream dependencies are available in. It is simply required that
all upstream dependencies be available for reading metadata from.</p>
<p>The reason for this is that <code>rlib</code> files do not contain any of their upstream
dependencies. It wouldn't be very efficient for all <code>rlib</code> files to contain a
copy of <code>libstd.rlib</code>!</p>
</li>
<li>
<p>If an executable is being produced and the <code>-C prefer-dynamic</code> flag is not
specified, then dependencies are first attempted to be found in the <code>rlib</code>
format. If some dependencies are not available in an rlib format, then
dynamic linking is attempted (see below).</p>
</li>
<li>
<p>If a dynamic library or an executable that is being dynamically linked is
being produced, then the compiler will attempt to reconcile the available
dependencies in either the rlib or dylib format to create a final product.</p>
<p>A major goal of the compiler is to ensure that a library never appears more
than once in any artifact. For example, if dynamic libraries B and C were
each statically linked to library A, then a crate could not link to B and C
together because there would be two copies of A. The compiler allows mixing
the rlib and dylib formats, but this restriction must be satisfied.</p>
<p>The compiler currently implements no method of hinting what format a library
should be linked with. When dynamically linking, the compiler will attempt to
maximize dynamic dependencies while still allowing some dependencies to be
linked in via an rlib.</p>
<p>For most situations, having all libraries available as a dylib is recommended
if dynamically linking. For other situations, the compiler will emit a
warning if it is unable to determine which formats to link each library with.</p>
</li>
</ol>
<p>In general, <code>--crate-type=bin</code> or <code>--crate-type=lib</code> should be sufficient for
all compilation needs, and the other options are just available if more
fine-grained control is desired over the output format of a Rust crate.</p>
<a class="header" href="print.html#static-and-dynamic-c-runtimes" id="static-and-dynamic-c-runtimes"><h2>Static and dynamic C runtimes</h2></a>
<p>The standard library in general strives to support both statically linked and
dynamically linked C runtimes for targets as appropriate. For example the
<code>x86_64-pc-windows-msvc</code> and <code>x86_64-unknown-linux-musl</code> targets typically come
with both runtimes and the user selects which one they'd like. All targets in
the compiler have a default mode of linking to the C runtime. Typically targets
are linked dynamically by default, but there are exceptions which are static by
default such as:</p>
<ul>
<li><code>arm-unknown-linux-musleabi</code></li>
<li><code>arm-unknown-linux-musleabihf</code></li>
<li><code>armv7-unknown-linux-musleabihf</code></li>
<li><code>i686-unknown-linux-musl</code></li>
<li><code>x86_64-unknown-linux-musl</code></li>
</ul>
<p>The linkage of the C runtime is configured to respect the <code>crt-static</code> target
feature. These target features are typically configured from the command line
via flags to the compiler itself. For example to enable a static runtime you
would execute:</p>
<pre><code class="language-notrust">rustc -C target-feature=+crt-static foo.rs
</code></pre>
<p>whereas to link dynamically to the C runtime you would execute:</p>
<pre><code class="language-notrust">rustc -C target-feature=-crt-static foo.rs
</code></pre>
<p>Targets which do not support switching between linkage of the C runtime will
ignore this flag. It's recommended to inspect the resulting binary to ensure
that it's linked as you would expect after the compiler succeeds.</p>
<p>Crates may also learn about how the C runtime is being linked. Code on MSVC, for
example, needs to be compiled differently (e.g. with <code>/MT</code> or <code>/MD</code>) depending
on the runtime being linked. This is exported currently through the
<code>target_feature</code> attribute (note this is a nightly feature):</p>
<pre><code class="language-rust ignore">#[cfg(target_feature = &quot;crt-static&quot;)]
fn foo() {
    println!(&quot;the C runtime should be statically linked&quot;);
}

#[cfg(not(target_feature = &quot;crt-static&quot;))]
fn foo() {
    println!(&quot;the C runtime should be dynamically linked&quot;);
}
</code></pre>
<p>Also note that Cargo build scripts can learn about this feature through
<a href="http://doc.crates.io/environment-variables.html#environment-variables-cargo-sets-for-build-scripts">environment variables</a>. In a build script you can detect the linkage
via:</p>
<pre><pre class="playpen"><code class="language-rust">use std::env;

fn main() {
    let linkage = env::var(&quot;CARGO_CFG_TARGET_FEATURE&quot;).unwrap_or(String::new());

    if linkage.contains(&quot;crt-static&quot;) {
        println!(&quot;the C runtime will be statically linked&quot;);
    } else {
        println!(&quot;the C runtime will be dynamically linked&quot;);
    }
}
</code></pre></pre>
<p>To use this feature locally, you typically will use the <code>RUSTFLAGS</code> environment
variable to specify flags to the compiler through Cargo. For example to compile
a statically linked binary on MSVC you would execute:</p>
<pre><code class="language-ignore notrust">RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-msvc
</code></pre>
<a class="header" href="print.html#unsafety" id="unsafety"><h1>Unsafety</h1></a>
<p>Unsafe operations are those that potentially violate the memory-safety
guarantees of Rust's static semantics.</p>
<p>The following language level features cannot be used in the safe subset of
Rust:</p>
<ul>
<li>Dereferencing a <a href="types.html#pointer-types">raw pointer</a>.</li>
<li>Reading or writing a <a href="items/static-items.html#mutable-statics">mutable static variable</a>.</li>
<li>Reading a field of a <a href="items/unions.html"><code>union</code></a>, or writing to a field of a
union that isn't <a href="special-types-and-traits.html#copy"><code>Copy</code></a>.</li>
<li>Calling an unsafe function (including an intrinsic or foreign function).</li>
<li>Implementing an unsafe trait.</li>
</ul>
<a class="header" href="print.html#unsafe-functions" id="unsafe-functions"><h1>Unsafe functions</h1></a>
<p>Unsafe functions are functions that are not safe in all contexts and/or for all
possible inputs. Such a function must be prefixed with the keyword <code>unsafe</code> and
can only be called from an <code>unsafe</code> block or another <code>unsafe</code> function.</p>
<a class="header" href="print.html#unsafe-blocks-1" id="unsafe-blocks-1"><h1>Unsafe blocks</h1></a>
<p>A block of code can be prefixed with the <code>unsafe</code> keyword, to permit calling
<code>unsafe</code> functions or dereferencing raw pointers within a safe function.</p>
<p>When a programmer has sufficient conviction that a sequence of potentially
unsafe operations is actually safe, they can encapsulate that sequence (taken
as a whole) within an <code>unsafe</code> block. The compiler will consider uses of such
code safe, in the surrounding context.</p>
<p>Unsafe blocks are used to wrap foreign libraries, make direct use of hardware
or implement features not directly present in the language. For example, Rust
provides the language features necessary to implement memory-safe concurrency
in the language but the implementation of threads and message passing is in the
standard library.</p>
<p>Rust's type system is a conservative approximation of the dynamic safety
requirements, so in some cases there is a performance cost to using safe code.
For example, a doubly-linked list is not a tree structure and can only be
represented with reference-counted pointers in safe code. By using <code>unsafe</code>
blocks to represent the reverse links as raw pointers, it can be implemented
with only boxes.</p>
<a class="header" href="print.html#behavior-considered-undefined" id="behavior-considered-undefined"><h2>Behavior considered undefined</h2></a>
<p>Rust code, including within <code>unsafe</code> blocks and <code>unsafe</code> functions is incorrect
if it exhibits any of the behaviors in the following list. It is the
programmer's responsibility when writing <code>unsafe</code> code that it is not possible
to let <code>safe</code> code exhibit these behaviors.</p>
<ul>
<li>Data races.</li>
<li>Dereferencing a null or dangling raw pointer.</li>
<li>Unaligned pointer reading and writing outside of <a href="https://doc.rust-lang.org/std/ptr/fn.read_unaligned.html"><code>read_unaligned</code></a>
and <a href="https://doc.rust-lang.org/std/ptr/fn.write_unaligned.html"><code>write_unaligned</code></a>.</li>
<li>Reads of <a href="http://llvm.org/docs/LangRef.html#undefined-values">undef</a> (uninitialized) memory.</li>
<li>Breaking the <a href="http://llvm.org/docs/LangRef.html#pointer-aliasing-rules">pointer aliasing rules</a> on accesses through raw pointers;
a subset of the rules used by C.</li>
<li><code>&amp;mut T</code> and <code>&amp;T</code> follow LLVM’s scoped <a href="http://llvm.org/docs/LangRef.html#noalias">noalias</a> model, except if the <code>&amp;T</code>
contains an <a href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html"><code>UnsafeCell&lt;U&gt;</code></a>.</li>
<li>Mutating non-mutable data — that is, data reached through a shared
reference or data owned by a <code>let</code> binding), unless that data is contained
within an <a href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html"><code>UnsafeCell&lt;U&gt;</code></a>.</li>
<li>Invoking undefined behavior via compiler intrinsics:
<ul>
<li>Indexing outside of the bounds of an object with <a href="https://doc.rust-lang.org/std/primitive.pointer.html#method.offset"><code>offset</code></a> with
the exception of one byte past the end of the object.</li>
<li>Using <a href="https://doc.rust-lang.org/std/ptr/fn.copy_nonoverlapping.html"><code>std::ptr::copy_nonoverlapping_memory</code></a>, a.k.a. the <code>memcpy32</code>and
<code>memcpy64</code> intrinsics, on overlapping buffers.</li>
</ul>
</li>
<li>Invalid values in primitive types, even in private fields and locals:
<ul>
<li>Dangling or null references and boxes.</li>
<li>A value other than <code>false</code> (<code>0</code>) or <code>true</code> (<code>1</code>) in a <code>bool</code>.</li>
<li>A discriminant in an <code>enum</code> not included in the type definition.</li>
<li>A value in a <code>char</code> which is a surrogate or above <code>char::MAX</code>.</li>
<li>Non-UTF-8 byte sequences in a <code>str</code>.</li>
</ul>
</li>
</ul>
<a class="header" href="print.html#behavior-not-considered-unsafe" id="behavior-not-considered-unsafe"><h2>Behavior not considered <code>unsafe</code></h2></a>
<p>The Rust compiler does not consider the following behaviors <em>unsafe</em>,
though a programmer may (should) find them undesirable, unexpected,
or erroneous.</p>
<a class="header" href="print.html#deadlocks" id="deadlocks"><h5>Deadlocks</h5></a>
<a class="header" href="print.html#leaks-of-memory-and-other-resources" id="leaks-of-memory-and-other-resources"><h5>Leaks of memory and other resources</h5></a>
<a class="header" href="print.html#exiting-without-calling-destructors" id="exiting-without-calling-destructors"><h5>Exiting without calling destructors</h5></a>
<a class="header" href="print.html#exposing-randomized-base-addresses-through-pointer-leaks" id="exposing-randomized-base-addresses-through-pointer-leaks"><h5>Exposing randomized base addresses through pointer leaks</h5></a>
<a class="header" href="print.html#integer-overflow" id="integer-overflow"><h5>Integer overflow</h5></a>
<p>If a program contains arithmetic overflow, the programmer has made an
error. In the following discussion, we maintain a distinction between
arithmetic overflow and wrapping arithmetic. The first is erroneous,
while the second is intentional.</p>
<p>When the programmer has enabled <code>debug_assert!</code> assertions (for
example, by enabling a non-optimized build), implementations must
insert dynamic checks that <code>panic</code> on overflow. Other kinds of builds
may result in <code>panics</code> or silently wrapped values on overflow, at the
implementation's discretion.</p>
<p>In the case of implicitly-wrapped overflow, implementations must
provide well-defined (even if still considered erroneous) results by
using two's complement overflow conventions.</p>
<p>The integral types provide inherent methods to allow programmers
explicitly to perform wrapping arithmetic. For example,
<code>i32::wrapping_add</code> provides two's complement, wrapping addition.</p>
<p>The standard library also provides a <code>Wrapping&lt;T&gt;</code> newtype which
ensures all standard arithmetic operations for <code>T</code> have wrapping
semantics.</p>
<p>See <a href="https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md">RFC 560</a> for error conditions, rationale, and more details about
integer overflow.</p>
<a class="header" href="print.html#influences" id="influences"><h1>Influences</h1></a>
<p>Rust is not a particularly original language, with design elements coming from
a wide range of sources. Some of these are listed below (including elements
that have since been removed):</p>
<ul>
<li>SML, OCaml: algebraic data types, pattern matching, type inference,
semicolon statement separation</li>
<li>C++: references, RAII, smart pointers, move semantics, monomorphization,
memory model</li>
<li>ML Kit, Cyclone: region based memory management</li>
<li>Haskell (GHC): typeclasses, type families</li>
<li>Newsqueak, Alef, Limbo: channels, concurrency</li>
<li>Erlang: message passing, thread failure, <strike>linked thread failure</strike>,
<strike>lightweight concurrency</strike></li>
<li>Swift: optional bindings</li>
<li>Scheme: hygienic macros</li>
<li>C#: attributes</li>
<li>Ruby: <strike>block syntax</strike></li>
<li>NIL, Hermes: <strike>typestate</strike></li>
<li><a href="http://www.unicode.org/reports/tr31/">Unicode Annex #31</a>: identifier and
pattern syntax</li>
</ul>
<a class="header" href="print.html#as-yet-undocumented-features" id="as-yet-undocumented-features"><h1>As-yet-undocumented Features</h1></a>
<p>Several accepted, stabilized, and implemented RFCs lack documentation in this
reference, The Book, <em>Rust by Example</em>, or some combination of those three.
Until we have written reference documentation for these features, we provide
links to other sources of information about them. Therefore, expect this list
to shrink!</p>
<ul>
<li><a href="https://github.com/rust-lang/rfcs/pull/40"><code>libstd</code> facade</a></li>
<li><a href="https://github.com/rust-lang/rfcs/pull/48">Trait reform</a> – some partial documentation exists (the use of <code>Self</code>), but
not for everything: e.g. coherence and orphan rules.</li>
<li><a href="https://github.com/rust-lang/rfcs/pull/49">Attributes on <code>match</code> arms</a> – the underlying idea is documented in the
[Attributes] section, but the applicability to internal items is never
specified.</li>
<li><a href="https://github.com/rust-lang/rfcs/pull/131">Flexible target specification</a> - Some---but not all---flags are documented
in <a href="attributes.html#conditional-compilation">Conditional compilation</a></li>
<li>[Require parentheses for chained comparisons]</li>
<li><a href="https://github.com/rust-lang/rfcs/pull/1717"><code>dllimport</code></a> - one element mentioned but not explained at <a href="attributes.html#ffi-attributes">FFI attributes</a></li>
<li><a href="https://github.com/rust-lang/rfcs/pull/1721">define <code>crt_link</code></a></li>
<li><a href="https://github.com/rust-lang/rfcs/pull/1725">define <code>unaligned_access</code></a></li>
</ul>
<a class="header" href="print.html#glossary" id="glossary"><h1>Glossary</h1></a>
<a class="header" href="print.html#abstract-syntax-tree" id="abstract-syntax-tree"><h3>Abstract Syntax Tree</h3></a>
<p>An ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of
the structure of the program when the compiler is compiling it.</p>
<a class="header" href="print.html#alignment" id="alignment"><h3>Alignment</h3></a>
<p>The alignment of a value specifies what addresses values are preferred to
start at. Always a power of two. References to a value must be aligned.
<a href="type-layout.html#size-and-alignment">More</a>.</p>
<a class="header" href="print.html#arity" id="arity"><h3>Arity</h3></a>
<p>Arity refers to the number of arguments a function or operator takes.
For some examples, <code>f(2, 3)</code> and <code>g(4, 6)</code> have arity 2, while <code>h(8, 2, 6)</code>
has arity 3. The <code>!</code> operator has arity 1.</p>
<a class="header" href="print.html#array" id="array"><h3>Array</h3></a>
<p>An array, sometimes also called a fixed-size array or an inline array, is a value
describing a collection of elements, each selected by an index that can be computed
at run time by the program. It occupies a contiguous region of memory.</p>
<a class="header" href="print.html#associated-item" id="associated-item"><h3>Associated Item</h3></a>
<p>An associated item is an item that is associated with another item. Associated
items are defined in <a href="items/implementations.html">implementations</a> and declared in <a href="items/traits.html">traits</a>. Only functions,
constants, and type aliases can be associated.</p>
<a class="header" href="print.html#bound" id="bound"><h3>Bound</h3></a>
<p>Bounds are constraints on a type or trait. For example, if a bound
is placed on the argument a function takes, types passed to that function
must abide by that constraint.</p>
<a class="header" href="print.html#combinator" id="combinator"><h3>Combinator</h3></a>
<p>Combinators are higher-order functions that apply only functions and
earlier defined combinators to provide a result from its arguments.
They can be used to manage control flow in a modular fashion.</p>
<a class="header" href="print.html#dispatch" id="dispatch"><h3>Dispatch</h3></a>
<p>Dispatch is the mechanism to determine which specific version of code is actually
run when it involves polymorphism. Two major forms of dispatch are static dispatch and
dynamic dispatch. While Rust favors static dispatch, it also supports dynamic dispatch
through a mechanism called ‘trait objects’.</p>
<a class="header" href="print.html#dynamically-sized-type" id="dynamically-sized-type"><h3>Dynamically Sized Type</h3></a>
<p>A dynamically sized type (DST) is a type without a statically known size or alignment.</p>
<a class="header" href="print.html#expression" id="expression"><h3>Expression</h3></a>
<p>An expression is a combination of values, constants, variables, operators
and functions that evaluate to a single value, with or without side-effects.</p>
<p>For example, <code>2 + (3 * 4)</code> is an expression that returns the value 14.</p>
<a class="header" href="print.html#initialized" id="initialized"><h3>Initialized</h3></a>
<p>A variable is initialized if it has been assigned a value and hasn't since been
moved from. All other memory locations are assumed to be initialized. Only
unsafe Rust can create such a memory without initializing it.</p>
<a class="header" href="print.html#nominal-types" id="nominal-types"><h3>Nominal Types</h3></a>
<p>Types that can be referred to by a path directly. Specifically <a href="items/enumerations.html">enums</a>,
<a href="items/structs.html">structs</a>, <a href="items/unions.html">unions</a>, and <a href="types.html#trait-objects">trait objects</a>.</p>
<a class="header" href="print.html#object-safe-traits" id="object-safe-traits"><h3>Object Safe Traits</h3></a>
<p><a href="items/traits.html">Traits</a> that can be used as <a href="types.html#trait-objects">trait objects</a>. Only traits that follow specific
<a href="items/traits.html#object-safety">rules</a> are object safe.</p>
<a class="header" href="print.html#prelude" id="prelude"><h3>Prelude</h3></a>
<p>Prelude, or The Rust Prelude, is a small collection of items - mostly traits - that are
imported into every module of every crate. The traits in the prelude are pervasive.</p>
<a class="header" href="print.html#size" id="size"><h3>Size</h3></a>
<p>The size of a value has two definitions.</p>
<p>The first is that it is how much memory must be allocated to store that value.</p>
<p>The second is that it is the offset in bytes between successive elements in an
array with that item type.</p>
<p>It is a multiple of the alignment, including zero. The size can change
depending on compiler version (as new optimizations are made) and target
platform (similar to how <code>usize</code> varies per-platform).</p>
<p><a href="type-layout.html#size-and-alignment">More</a>.</p>
<a class="header" href="print.html#slice" id="slice"><h3>Slice</h3></a>
<p>A slice is dynamically-sized view into a contiguous sequence, written as <code>[T]</code>.</p>
<p>It is often seen in its borrowed forms, either mutable or shared. The shared
slice type is <code>&amp;[T]</code>, while the mutable slice type is <code>&amp;mut [T]</code>, where <code>T</code> represents
the element type.</p>
<a class="header" href="print.html#statement" id="statement"><h3>Statement</h3></a>
<p>A statement is the smallest standalone element of a programming language
that commands a computer to perform an action.</p>
<a class="header" href="print.html#string-literal" id="string-literal"><h3>String literal</h3></a>
<p>A string literal is a string stored directly in the final binary, and so will be
valid for the <code>'static</code> duration.</p>
<p>Its type is <code>'static</code> duration borrowed string slice, <code>&amp;'static str</code>.</p>
<a class="header" href="print.html#string-slice" id="string-slice"><h3>String slice</h3></a>
<p>A string slice is the most primitive string type in Rust, written as <code>str</code>. It is
often seen in its borrowed forms, either mutable or shared. The shared
string slice type is <code>&amp;str</code>, while the mutable string slice type is <code>&amp;mut str</code>.</p>
<p>Strings slices are always valid UTF-8.</p>
<a class="header" href="print.html#trait" id="trait"><h3>Trait</h3></a>
<p>A trait is a language item that is used for describing the functionalities a type must provide.
It allows a type to make certain promises about its behavior.</p>
<p>Generic functions and generic structs can use traits to constrain, or bound, the types they accept.</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        

                        

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

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                

                
            </nav>

        </div>

        

        

        
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                window.print();
            })
        </script>
        

        

        
        <script src="searchindex.js" type="text/javascript" charset="utf-8"></script>
        
        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

    </body>
</html>