Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 564935689ab5527f955e5449ded02799 > files > 2545

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

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Appendix: As-yet-undocumented Features - 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">

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

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

        <!-- MathJax -->
        <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

        <!-- Fetch JQuery from CDN but have a local fallback -->
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script>
            if (typeof jQuery == 'undefined') {
                document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
            }
        </script>
    </head>
    <body class="light">
        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme = localStorage.getItem('theme');
            if (theme == null) { theme = 'light'; }
            $('body').removeClass().addClass(theme);
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var sidebar = localStorage.getItem('sidebar');
            if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
            else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
        </script>

        <div id="sidebar" class="sidebar">
            <ul class="chapter"><li class="affix"><a href="introduction.html">Introduction</a></li><li><a href="notation.html"><strong>1.</strong> Notation</a></li><li><ul class="section"><li><a href="unicode-productions.html"><strong>1.1.</strong> Unicode productions</a></li><li><a href="string-table-productions.html"><strong>1.2.</strong> String table productions</a></li></ul></li><li><a href="lexical-structure.html"><strong>2.</strong> Lexical structure</a></li><li><ul class="section"><li><a href="input-format.html"><strong>2.1.</strong> Input format</a></li><li><a href="identifiers.html"><strong>2.2.</strong> Identifiers</a></li><li><a href="comments.html"><strong>2.3.</strong> Comments</a></li><li><a href="whitespace.html"><strong>2.4.</strong> Whitespace</a></li><li><a href="tokens.html"><strong>2.5.</strong> Tokens</a></li><li><a href="paths.html"><strong>2.6.</strong> Paths</a></li></ul></li><li><a href="macros.html"><strong>3.</strong> Macros</a></li><li><ul class="section"><li><a href="macros-by-example.html"><strong>3.1.</strong> Macros By Example</a></li><li><a href="procedural-macros.html"><strong>3.2.</strong> Procedural Macros</a></li></ul></li><li><a href="crates-and-source-files.html"><strong>4.</strong> Crates and source files</a></li><li><a href="items-and-attributes.html"><strong>5.</strong> Items and attributes</a></li><li><ul class="section"><li><a href="items.html"><strong>5.1.</strong> Items</a></li><li><a href="visibility-and-privacy.html"><strong>5.2.</strong> Visibility and Privacy</a></li><li><a href="attributes.html"><strong>5.3.</strong> Attributes</a></li></ul></li><li><a href="statements-and-expressions.html"><strong>6.</strong> Statements and expressions</a></li><li><ul class="section"><li><a href="statements.html"><strong>6.1.</strong> Statements</a></li><li><a href="expressions.html"><strong>6.2.</strong> Expressions</a></li></ul></li><li><a href="type-system.html"><strong>7.</strong> Type system</a></li><li><ul class="section"><li><a href="types.html"><strong>7.1.</strong> Types</a></li><li><a href="subtyping.html"><strong>7.2.</strong> Subtyping</a></li><li><a href="type-coercions.html"><strong>7.3.</strong> Type coercions</a></li></ul></li><li><a href="special-traits.html"><strong>8.</strong> Special traits</a></li><li><ul class="section"><li><a href="the-copy-trait.html"><strong>8.1.</strong> The Copy trait</a></li><li><a href="the-sized-trait.html"><strong>8.2.</strong> The Sized trait</a></li><li><a href="the-drop-trait.html"><strong>8.3.</strong> The Drop trait</a></li><li><a href="the-deref-trait.html"><strong>8.4.</strong> The Deref trait</a></li><li><a href="the-send-trait.html"><strong>8.5.</strong> The Send trait</a></li><li><a href="the-sync-trait.html"><strong>8.6.</strong> The Sync trait</a></li></ul></li><li><a href="memory-model.html"><strong>9.</strong> Memory model</a></li><li><ul class="section"><li><a href="memory-allocation-and-lifetime.html"><strong>9.1.</strong> Memory allocation and lifetime</a></li><li><a href="memory-ownership.html"><strong>9.2.</strong> Memory ownership</a></li><li><a href="variables.html"><strong>9.3.</strong> Variables</a></li></ul></li><li><a href="linkage.html"><strong>10.</strong> Linkage</a></li><li><a href="unsafety.html"><strong>11.</strong> Unsafety</a></li><li><ul class="section"><li><a href="unsafe-functions.html"><strong>11.1.</strong> Unsafe functions</a></li><li><a href="unsafe-blocks.html"><strong>11.2.</strong> Unsafe blocks</a></li><li><a href="behavior-considered-undefined.html"><strong>11.3.</strong> Behavior considered undefined</a></li><li><a href="behavior-not-considered-unsafe.html"><strong>11.4.</strong> Behavior not considered unsafe</a></li></ul></li><li><a href="influences.html">Appendix: Influences</a></li><li class="affix"><a href="undocumented.html">Appendix: As-yet-undocumented Features</a></li></ul>
        </div>

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

            <div class="page">
                <div id="menu-bar" class="menu-bar">
                    <div class="left-buttons">
                        <i id="sidebar-toggle" class="fa fa-bars"></i>
                        <i id="theme-toggle" class="fa fa-paint-brush"></i>
                    </div>

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

                    <div class="right-buttons">
                        <i id="print-button" class="fa fa-print" title="Print this book"></i>
                    </div>
                </div>

                <div id="content" class="content">
                    <a class="header" href="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>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>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"><h1>Unicode productions</h1></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"><h1>String table productions</h1></a>
<p>Some rules in the grammar — notably <a href="expressions.html#borrow-operators">unary
operators</a>, <a href="expressions.html#arithmetic-and-logical-binary-operators">binary operators</a>, and <a href="../grammar.html#keywords">keywords</a> — are
given in a simplified form: as a listing of a table of unquoted, printable
whitespace-separated 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 DFA, operating over the
disjunction of all such string table entries.</p>
<p>When such a string enclosed in double-quotes (<code>&quot;</code>) 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#identifiers" id="identifiers"><h1>Identifiers</h1></a>
<p>An identifier is any nonempty Unicode<sup class="footnote-reference"><a href="print.html#non_ascii_idents">1</a></sup> string of the following form:</p>
<p>Either</p>
<ul>
<li>The first character has property <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&amp;abb=on&amp;g=&amp;i="><code>XID_start</code></a></li>
<li>The remaining characters have property <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&amp;abb=on&amp;g=&amp;i="><code>XID_continue</code></a></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 have property <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&amp;abb=on&amp;g=&amp;i="><code>XID_continue</code></a></li>
</ul>
<p>that does <em>not</em> occur in the set of <a href="../grammar.html#keywords">keywords</a>.</p>
<blockquote>
<p><strong>Note</strong>: <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Start%3A%5D&amp;abb=on&amp;g=&amp;i="><code>XID_start</code></a> and <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5B%3AXID_Continue%3A%5D&amp;abb=on&amp;g=&amp;i="><code>XID_continue</code></a> as character properties cover the
character ranges used to form the more familiar C and Java language-family
identifiers.</p>
</blockquote>
<div class="footnote-definition" id="non_ascii_idents"><sup class="footnote-definition-label">1</sup>
<p>Non-ASCII characters in identifiers are currently feature
gated. This is expected to improve soon.</p>
</div>
<a class="header" href="print.html#comments" id="comments"><h1>Comments</h1></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>Line comments beginning with exactly <em>three</em> slashes (<code>///</code>), and block
comments (<code>/** ... */</code>), 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>.</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>Non-doc comments are interpreted as a form of whitespace.</p>
<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="string-table-productions.html">string table
production</a> form, and occur in the rest of the
grammar as double-quoted strings. 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 constant expression, so is evaluated (primarily) at compile time.</p>
<a class="header" href="print.html#examples" id="examples"><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><td>                                              </td><td> Example         </td><td> <code>#</code> sets   </td><td> Characters  </td><td> Escapes             </td></tr></thead>
<tr><td> <a href="print.html#character-literals">Character</a>             </td><td> <code>'H'</code>           </td><td> <code>N/A</code>      </td><td> All Unicode </td><td> <a href="print.html#quote-escapes">Quote</a> &amp; <a href="print.html#byte-escapes">Byte</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> <code>N/A</code>      </td><td> All Unicode </td><td> <a href="print.html#quote-escapes">Quote</a> &amp; <a href="print.html#byte-escapes">Byte</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> <code>0...</code>     </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> <code>N/A</code>      </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> <code>N/A</code>      </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> <code>0...</code>     </td><td> All ASCII   </td><td> <code>N/A</code>                                                      </td></tr>
</table>
<a class="header" href="print.html#byte-escapes" id="byte-escapes"><h4>Byte escapes</h4></a>
<table><thead><tr><td>   </td><td> Name </td></tr></thead>
<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>
</table>
<a class="header" href="print.html#unicode-escapes" id="unicode-escapes"><h4>Unicode escapes</h4></a>
<table><thead><tr><td>   </td><td> Name </td></tr></thead>
<tr><td> <code>\u{7FFF}</code> </td><td> 24-bit Unicode character code (up to 6 digits) </td></tr>
</table>
<a class="header" href="print.html#quote-escapes" id="quote-escapes"><h4>Quote escapes</h4></a>
<table><thead><tr><td>   </td><td> Name </td></tr></thead>
<tr><td> <code>\'</code> </td><td> Single quote </td></tr>
<tr><td> <code>\&quot;</code> </td><td> Double quote </td></tr>
</table>
<a class="header" href="print.html#numbers" id="numbers"><h4>Numbers</h4></a>
<table><thead><tr><td> <a href="print.html#number-literals">Number literals</a><code>*</code> </td><td> Example </td><td> Exponentiation </td><td> Suffixes </td></tr></thead>
<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>
</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><td> Integer </td><td> Floating-point </td></tr></thead>
<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>isize</code>, <code>usize</code> </td><td> <code>f32</code>, <code>f64</code> </td></tr>
</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>
<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>
<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>An <em>8-bit code point escape</em> starts with <code>U+0078</code> (<code>x</code>) and is
followed by exactly two <em>hex digits</em>. It denotes the Unicode code point
equal to the provided hex value.</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 <em>itself</em>.</li>
</ul>
<a class="header" href="print.html#raw-string-literals" id="raw-string-literals"><h4>Raw string literals</h4></a>
<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>
<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>
<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. A byte string literal of length <code>n</code> is equivalent to a <code>&amp;'static [u8; n]</code> borrowed fixed-sized array
of unsigned 8-bit integers.</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>
<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>
<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>hex literal</em> starts with the character sequence <code>U+0030</code> <code>U+0078</code>
(<code>0x</code>) and continues as any mixture 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 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 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>isize</code>, or <code>usize</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() {
123i32;                            // type i32
123u32;                            // type u32
123_u32;                           // type u32
0xff_u8;                           // type u8
0o70_i16;                          // type i16
0b1111_1111_1001_0000_i32;         // type i32
0usize;                            // type usize

#}</code></pre></pre>
<p>Note that the Rust syntax considers <code>-1i8</code> as an application of the <a href="expressions.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>
<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>
<p>The two values of the boolean type are written <code>true</code> and <code>false</code>.</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.html#borrow-operators">unary operators</a>, <a href="expressions.html#arithmetic-and-logical-binary-operators">binary
operators</a>, or <a href="../grammar.html#keywords">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 qualifier (<code>::</code>). If a path consists of only one component, it may
refer 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 refers to an item.</p>
<p>Every item has a <em>canonical path</em> within its crate, but the path naming an item
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>
<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 symbol (<code>&lt;</code>). 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#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>Users of <code>rustc</code> can define new macros in two ways:</p>
<ul>
<li><a href="../book/macros.html">Macros</a> define new syntax in a higher-level,
declarative way.</li>
<li><a href="../book/procedural-macros.html">Procedural Macros</a> can be used to implement custom derive.</li>
</ul>
<p>And one unstable way: <a href="../unstable-book/language-features/plugin.html">compiler plugins</a>.</p>
<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.html#block-expressions">block</a></li>
<li><code>stmt</code>: a <a href="statements.html">statement</a></li>
<li><code>pat</code>: a <a href="expressions.html#match-expressions">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></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>
</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>&quot;Procedural macros&quot; are the second way to implement a macro. For now, the only
thing they can be used for is to implement derive on your own types. See
<a href="../book/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>
<p>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>
<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.html#modules">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.html#modules">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="items-and-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> function can be compiled to an executable. If a
<code>main</code> function is present, its return type must be <code>()</code>
(&quot;<a href="types.html#tuple-types">unit</a>&quot;) and it must take no arguments.</p>
<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="print.html#modules">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 item:</p>
<ul>
<li><a href="print.html#extern-crate-declarations"><code>extern crate</code> declarations</a></li>
<li><a href="print.html#use-declarations"><code>use</code> declarations</a></li>
<li><a href="print.html#modules">modules</a></li>
<li><a href="print.html#functions">function definitions</a></li>
<li><a href="print.html#external-blocks"><code>extern</code> blocks</a></li>
<li><a href="print.html#type-aliases">type definitions</a></li>
<li><a href="print.html#structs">struct definitions</a></li>
<li><a href="print.html#enumerations">enumeration definitions</a></li>
<li><a href="print.html#unions">union definitions</a></li>
<li><a href="print.html#constant-items">constant items</a></li>
<li><a href="print.html#static-items">static items</a></li>
<li><a href="print.html#traits">trait definitions</a></li>
<li><a href="print.html#implementations">implementations</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#type-parameters" id="type-parameters"><h2>Type Parameters</h2></a>
<p>All items except modules, constants and statics may be <em>parameterized</em> by type.
Type parameters are given as a comma-separated list of identifiers enclosed in
angle brackets (<code>&lt;...&gt;</code>), after the name of the item and before its definition.
The type parameters of an item are considered &quot;part of the name&quot;, not part of
the type of the item. A referencing <a href="paths.html">path</a> must (in principle) provide
type arguments as a list of comma-separated types enclosed within angle
brackets, in order to refer to the type-parameterized item. In practice, the
type-inference system can usually infer such argument types from context. There
are no general type-parametric types, only type-parametric items. That is, Rust
has no notion of type abstraction: there are no higher-ranked (or &quot;forall&quot;) types
abstracted over other types, though higher-ranked types do exist for lifetimes.</p>
<a class="header" href="print.html#modules" id="modules"><h2>Modules</h2></a>
<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, or type parameter can't shadow the name of a module
in scope, or vice versa.</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"><h3>Extern crate declarations</h3></a>
<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"><h3>Use declarations</h3></a>
<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="print.html#modules">modules</a> and <a href="../grammar.html#block-expressions">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="print.html#extern-crate-declarations"><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 differing only in their final element,
using the glob-like brace syntax <code>use a::b::{c,d,e,f};</code></li>
<li>Simultaneously binding a list of paths differing only in their final element
and their immediate parent module, using the <code>self</code> keyword, such as
<code>use a::b::{self, c, d};</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>
</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"><h2>Functions</h2></a>
<p>A <em>function item</em> defines a sequence of <a href="statements.html">statements</a> and a
final <a href="expressions.html">expression</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>A function may also be copied into a first-class <em>value</em>, in which case the
value has the corresponding <a href="types.html#function-types"><em>function type</em></a>, and can be used
otherwise exactly as a function item (with a minor additional cost of calling
the function indirectly).</p>
<p>Every control path in a function logically ends with a <code>return</code> expression or a
diverging expression. If the outermost block of a function has a
value-producing expression in its final-expression position, that expression is
interpreted as an implicit <code>return</code> expression applied to the final-expression.</p>
<p>An example of a function:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn add(x: i32, y: i32) -&gt; i32 {
    x + y
}

#}</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>
<a class="header" href="print.html#generic-functions" id="generic-functions"><h3>Generic functions</h3></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><code class="language-rust ignore">// foo is generic over A and B

fn foo&lt;A, B&gt;(x: A, y: B) {
</code></pre>
<p>Inside the function signature and body, the name of the type parameter can be
used as a type name. <a href="print.html#traits">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><code class="language-rust ignore">fn foo&lt;T&gt;(x: T) where T: Debug {
</code></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#diverging-functions" id="diverging-functions"><h3>Diverging functions</h3></a>
<p>A special kind of function can be declared with a <code>!</code> character where the
output type would normally be. For example:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn my_err(s: &amp;str) -&gt; ! {
    println!(&quot;{}&quot;, s);
    panic!();
}

#}</code></pre></pre>
<p>We call such functions &quot;diverging&quot; because they never return a value to the
caller. Every control path in a diverging function must end with a <code>panic!()</code>,
a loop expression without an associated break expression, or a call to another
diverging function on every control path. The <code>!</code> annotation does <em>not</em> denote
a type.</p>
<p>It might be necessary to declare a diverging function because as mentioned
previously, the typechecker checks that every control path in a function ends
with a <a href="expressions.html#return-expressions"><code>return</code></a> or diverging expression. So, if <code>my_err</code>
were declared without the <code>!</code> annotation, the following code would not
typecheck:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# fn my_err(s: &amp;str) -&gt; ! { panic!() }

fn f(i: i32) -&gt; i32 {
    if i == 42 {
        return 42;
    }
    else {
        my_err(&quot;Bad number!&quot;);
    }
}

#}</code></pre></pre>
<p>This will not compile without the <code>!</code> annotation on <code>my_err</code>, since the <code>else</code>
branch of the conditional in <code>f</code> does not return an <code>i32</code>, as required by the
signature of <code>f</code>. Adding the <code>!</code> annotation to <code>my_err</code> informs the
typechecker that, should control ever enter <code>my_err</code>, no further type judgments
about <code>f</code> need to hold, since control will never resume in any context that
relies on those judgments. Thus the return type on <code>f</code> only needs to reflect
the <code>if</code> branch of the conditional.</p>
<a class="header" href="print.html#extern-functions" id="extern-functions"><h3>Extern functions</h3></a>
<p>Extern functions are part of Rust's foreign function interface, providing the
opposite functionality to <a href="print.html#external-blocks">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
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>Extern functions may be called directly from Rust code as Rust uses large,
contiguous stack segments like C.</p>
<a class="header" href="print.html#type-aliases" id="type-aliases"><h2>Type aliases</h2></a>
<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"><h2>Structs</h2></a>
<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"><h2>Enumerations</h2></a>
<p>An <em>enumeration</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>Enumeration 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.</p>
<p>Each enum value has a <em>discriminant</em> which is an integer associated to it. You
can specify it explicitly:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
enum Foo {
    Bar = 123,
}

#}</code></pre></pre>
<p>The right hand side of the specification is interpreted as an <code>isize</code> value,
but the compiler is allowed to use a smaller type in the actual memory layout.
The <a href="attributes.html#ffi-attributes"><code>repr</code> attribute</a> can be added in order to change
the type of the right hand side and specify the memory layout.</p>
<p>If a discriminant isn't specified, they start at zero, and add one for each
variant, in order.</p>
<p>You can cast an enum to get its discriminant:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# enum Foo { Bar = 123 }
let x = Foo::Bar as u32; // x is now 123u32

#}</code></pre></pre>
<p>This only works as long as none of the variants have data attached. If
it were <code>Bar(i32)</code>, this is disallowed.</p>
<a class="header" href="print.html#unions" id="unions"><h2>Unions</h2></a>
<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"><h2>Constant items</h2></a>
<p>A <em>constant item</em> is a named <em>constant value</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>Constant values must not have destructors, and otherwise permit most forms of
data. 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 below on <a href="print.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>
<p>Constants must be explicitly typed. The type may be <code>bool</code>, <code>char</code>, a number, or
a type derived from those primitive types. The derived types are references with
the <code>static</code> lifetime, fixed-size arrays, tuples, enum variants, and structs.</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#static-items" id="static-items"><h2>Static items</h2></a>
<p>A <em>static item</em> is similar to a <em>constant</em>, except that it represents a precise
memory location in the program. A static is never &quot;inlined&quot; at the usage site,
and all references to it refer to the same memory location. Static items have
the <code>static</code> lifetime, which outlives all other lifetimes in a Rust program.
Static items may be placed in read-only memory if they do not contain any
interior mutability.</p>
<p>Statics may contain interior mutability through the <code>UnsafeCell</code> language item.
All access to a static is safe, but there are a number of restrictions on
statics:</p>
<ul>
<li>Statics may not contain any destructors.</li>
<li>The types of static values must ascribe to <code>Sync</code> to allow thread-safe access.</li>
<li>Statics may not refer to other statics by value, only by reference.</li>
<li>Constants cannot refer to statics.</li>
</ul>
<p>Constants should in general be preferred over statics, unless large amounts of
data are being stored, or single-address and mutability properties are required.</p>
<a class="header" href="print.html#mutable-statics" id="mutable-statics"><h3>Mutable statics</h3></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 of the value is not required to ascribe to <code>Sync</code>.</p>
<a class="header" href="print.html#static-lifetime-elision" id="static-lifetime-elision"><h4><code>'static</code> lifetime elision</h4></a>
<p>Both constant and static 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. Returning to our previous example:</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;str = &quot;bitstring&quot;;

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

const BITS_N_STRINGS: BitsNStrings = BitsNStrings {
    mybits: BITS,
    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 (<a href="../nomicon/lifetime-elision.html">see discussion in the nomicon</a>). If it
is unable to resolve the lifetimes by its usual rules, it will default to using
the <code>'static</code> lifetime. 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: 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 the signature is resolved as
// `Fn(&amp;'static Foo, &amp;'static Bar) -&gt; &amp;'static Baz`.
const RESOLVED_STATIC: Fn(&amp;Foo, &amp;Bar) -&gt; &amp;Baz = ..
</code></pre>
<a class="header" href="print.html#traits" id="traits"><h3>Traits</h3></a>
<p>A <em>trait</em> describes an abstract interface that types can
implement. This interface consists of associated items, which come in
three varieties:</p>
<ul>
<li>functions</li>
<li>constants</li>
<li>types</li>
</ul>
<p>Associated functions whose first parameter is named <code>self</code> are called
methods and may be invoked using <code>.</code> notation (e.g., <code>x.foo()</code>).</p>
<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 as usual.</p>
<p>Trait bounds on <code>Self</code> are considered &quot;supertraits&quot;. These are
required to be acyclic.  Supertraits are somewhat different from other
constraints in that they affect what methods are available in the
vtable when the trait is used as a <a href="types.html#trait-objects">trait object</a>.</p>
<p>Traits are implemented for specific types through separate
<a href="print.html#implementations">implementations</a>.</p>
<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="print.html#implementations">implementations</a> of this trait in scope can have their
<code>draw</code> and <code>bounding_box</code> methods called, using <code>value.bounding_box()</code>
<a href="expressions.html#method-call-expressions">syntax</a>.</p>
<p>Traits can include default implementations of methods, as in:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
trait Foo {
    fn bar(&amp;self);
    fn baz(&amp;self) { println!(&quot;We called baz.&quot;); }
}

#}</code></pre></pre>
<p>Here the <code>baz</code> method has a default implementation, so types that implement
<code>Foo</code> need only implement <code>bar</code>. It is also possible for implementing types
to override a method that has a default implementation.</p>
<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="print.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>
<p>It is also possible to define associated types for a trait. Consider the
following example of a <code>Container</code> trait. Notice how 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>
<p>Generic functions may use traits as <em>bounds</em> on their type parameters. This
will have two effects:</p>
<ul>
<li>Only types that have the trait may instantiate the parameter.</li>
<li>Within the generic function, the methods of the trait can be
called on values that have the parameter's type.</li>
</ul>
<p>For example:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# type Surface = i32;
# trait Shape { fn draw(&amp;self, Surface); }
fn draw_twice&lt;T: Shape&gt;(surface: Surface, sh: T) {
    sh.draw(surface);
    sh.draw(surface);
}

#}</code></pre></pre>
<p>Traits also define a <a href="types.html#trait-objects">trait object</a> with the same
name as the trait. Values of this type are created by coercing from a
pointer of some specific type to a pointer of trait type. For example,
<code>&amp;T</code> could be coerced to <code>&amp;Shape</code> if <code>T: Shape</code> holds (and similarly
for <code>Box&lt;T&gt;</code>). This coercion can either be implicit or
<a href="expressions.html#type-cast-expressions">explicit</a>. Here is an example of an explicit
coercion:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
trait Shape { }
impl Shape for i32 { }
let mycircle = 0i32;
let myshape: Box&lt;Shape&gt; = Box::new(mycircle) as Box&lt;Shape&gt;;

#}</code></pre></pre>
<p>The resulting value is a box containing the value that was cast, along with
information that identifies the methods of the implementation that was used.
Values with a trait type can have <a href="expressions.html#method-call-expressions">methods called</a> on
them, for any method in the trait, and can be used to instantiate type
parameters that are bounded by the trait.</p>
<p>Trait methods may be static, which means that they lack a <code>self</code> argument.
This means that they can only be called with function call syntax (<code>f(x)</code>) and
not method call syntax (<code>obj.f()</code>). The way to refer to the name of a static
method is to qualify it with the trait name, treating the trait name like a
module. For example:</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 }
}
let x: f64 = Num::from_i32(42);

#}</code></pre></pre>
<p>Traits may inherit from other traits. Consider the following example:</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>The syntax <code>Circle : Shape</code> means that types that implement <code>Circle</code> must also
have an implementation for <code>Shape</code>. Multiple supertraits are separated by <code>+</code>,
<code>trait Circle : Shape + PartialEq { }</code>. In an implementation of <code>Circle</code> for a
given type <code>T</code>, methods can refer to <code>Shape</code> methods, since the typechecker
checks that any type with an implementation of <code>Circle</code> also has an
implementation of <code>Shape</code>:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
struct Foo;

trait Shape { fn area(&amp;self) -&gt; f64; }
trait Circle : Shape { fn radius(&amp;self) -&gt; f64; }
impl Shape for Foo {
    fn area(&amp;self) -&gt; f64 {
        0.0
    }
}
impl Circle for Foo {
    fn radius(&amp;self) -&gt; f64 {
        println!(&quot;calling area: {}&quot;, self.area());

        0.0
    }
}

let c = Foo;
c.radius();

#}</code></pre></pre>
<p>In type-parameterized functions, methods of the supertrait may be called on
values of subtrait-bound type parameters. Referring to the previous example of
<code>trait Circle : 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 : Shape { fn radius(&amp;self) -&gt; f64; }
fn radius_times_area&lt;T: Circle&gt;(c: T) -&gt; f64 {
    // `c` is both a Circle and a Shape
    c.radius() * c.area()
}

#}</code></pre></pre>
<p>Likewise, supertrait methods may also be called on trait objects.</p>
<pre><code class="language-rust ignore"># trait Shape { fn area(&amp;self) -&gt; f64; }
# trait Circle : Shape { fn radius(&amp;self) -&gt; f64; }
# impl Shape for i32 { fn area(&amp;self) -&gt; f64 { 0.0 } }
# impl Circle for i32 { fn radius(&amp;self) -&gt; f64 { 0.0 } }
# let mycircle = 0i32;
let mycircle = Box::new(mycircle) as Box&lt;Circle&gt;;
let nonsense = mycircle.radius() * mycircle.area();
</code></pre>
<a class="header" href="print.html#implementations" id="implementations"><h3>Implementations</h3></a>
<p>An <em>implementation</em> is an item that implements a <a href="print.html#traits">trait</a> for a
specific type.</p>
<p>Implementations are defined with the keyword <code>impl</code>.</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>
<p>It is possible to define an implementation without referring to a trait. The
methods in such an implementation can only be used as direct calls on the values
of the type that the implementation targets. In such an implementation, the
trait type and <code>for</code> after <code>impl</code> are omitted. Such implementations are limited
to nominal types (enums, structs, trait objects), and the implementation must
appear in the same crate as the <code>self</code> type:</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>
<p>When a trait <em>is</em> specified in an <code>impl</code>, all methods declared as part of the
trait must be implemented, with matching types and type parameter counts.</p>
<p>An implementation can take type parameters, which can be different from the
type parameters taken by the trait it implements. Implementation parameters
are written 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"><h3>External blocks</h3></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#visibility-and-privacy" id="visibility-and-privacy"><h1>Visibility and Privacy</h1></a>
<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 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" id="attributes"><h1>Attributes</h1></a>
<p>Any item declaration may have an <em>attribute</em> applied to it. Attributes in Rust
are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
(C#). An attribute 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 list of sub-attribute arguments</li>
</ul>
<p>Attributes with a bang (&quot;!&quot;) after the hash (&quot;#&quot;) apply to the item that the
attribute is declared within. Attributes that do not have a bang after the hash
apply to the item that follows 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>
<blockquote>
<p><strong>Note:</strong> At some point in the future, the compiler will distinguish between
language-reserved and user-available attributes. Until then, there is
effectively no difference between an attribute handled by a loadable syntax
extension and the compiler.</p>
</blockquote>
<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>feature</code> - see <a href="print.html#compiler-features">compiler features</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>plugin</code> - load a list of named crates as compiler plugins, e.g.
<code>#![plugin(foo, bar)]</code>. Optional arguments for each plugin,
i.e. <code>#![plugin(foo(... args ...))]</code>, are provided to the plugin's
registrar function.  The <code>plugin</code> feature gate is required to use
this attribute.</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"><h3>Module-only attributes</h3></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>main</code> - indicates that this function should be passed to the entry point,
rather than the function in the crate root named <code>main</code>.</li>
<li><code>plugin_registrar</code> - mark this function as the registration point for
[compiler plugins][plugin], such as loadable syntax extensions.</li>
<li><code>start</code> - indicates that this function should be used as the entry point,
overriding the &quot;start&quot; language item. See the &quot;start&quot; <a href="print.html#language-items">language
item</a> for more details.</li>
<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>
<li><code>naked</code> - The function utilizes a custom ABI or custom inline ASM that requires
epilogue and prologue to be skipped.</li>
</ul>
<a class="header" href="print.html#static-only-attributes" id="static-only-attributes"><h2>Static-only attributes</h2></a>
<ul>
<li><code>thread_local</code> - on a <code>static mut</code>, this signals that the value of this
static may change depending on the current thread. The exact consequences of
this are implementation-defined.</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.html#external-blocks">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>On <code>enum</code>s:</p>
<ul>
<li><code>repr</code> - on C-like enums, this sets the underlying type used for
representation. Takes one argument, which is the primitive
type this enum should be represented for, or <code>C</code>, which specifies that it
should be the default <code>enum</code> size of the C ABI for that platform. Note that
enum representation in C is undefined, and this may be incorrect when the C
code is compiled with certain flags.</li>
</ul>
<p>On <code>struct</code>s:</p>
<ul>
<li><code>repr</code> - specifies the representation to use for this struct. Takes a list
of options. The currently accepted ones are <code>C</code> and <code>packed</code>, which may be
combined. <code>C</code> will use a C ABI compatible struct layout, and <code>packed</code> will
remove any padding between fields (note that this is very fragile and may
break platforms which require aligned access).</li>
</ul>
<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
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>deprecated</code> - mark the item as deprecated; the full attribute is
<code>#[deprecated(since = &quot;crate version&quot;, note = &quot;...&quot;)</code>, where both arguments
are optional.</li>
<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>
<li><code>simd</code> - on certain tuple structs, derive the arithmetic operators, which
lower to the target's SIMD instructions, if any; the <code>simd</code> feature gate
is necessary to use this attribute.</li>
<li><code>unsafe_destructor_blind_to_params</code> - on <code>Drop::drop</code> method, asserts that the
destructor code (and all potential specializations of that code) will
never attempt to read from nor write to any references with lifetimes
that come in via generic parameters. This is a constraint we cannot
currently express via the type system, and therefore we rely on the
programmer to assert that it holds. Adding this to a Drop impl causes
the associated destructor to be considered &quot;uninteresting&quot; by the
Drop-Check rule, and thus it can help sidestep data ordering
constraints that would otherwise be introduced by the Drop-Check
rule. Such sidestepping of the constraints, if done incorrectly, can
lead to undefined behavior (in the form of reading or writing to data
outside of its dynamic extent), and thus this attribute has the word
&quot;unsafe&quot; in its name. To use this, the
<code>unsafe_destructor_blind_to_params</code> feature gate must be enabled.</li>
<li><code>doc</code> - Doc comments such as <code>/// foo</code> are equivalent to <code>#[doc = &quot;foo&quot;]</code>.</li>
<li><code>rustc_on_unimplemented</code> - Write a custom note to be shown along with the error
when the trait is found to be unimplemented on a type.
You may use format arguments like <code>{T}</code>, <code>{A}</code> to correspond to the
types at the point of use corresponding to the type parameters of the
trait of the same name. <code>{Self}</code> will be replaced with the type that is supposed
to implement the trait but doesn't. To use this, the <code>on_unimplemented</code> feature gate
must be enabled.</li>
<li><code>must_use</code> - on structs and enums, will warn if a value of this type isn't used or
assigned to a variable. You may also include an optional message by using
<code>#[must_use = &quot;message&quot;]</code> which will be given alongside the warning.</li>
</ul>
<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><code class="language-rust ignore">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>
<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><code class="language-rust ignore">#[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>
<a class="header" href="print.html#language-items" id="language-items"><h3>Language items</h3></a>
<p>Some primitive Rust operations are defined in Rust code, rather than being
implemented directly in C or assembly language. The definitions of these
operations have to be easy for the compiler to find. The <code>lang</code> attribute
makes it possible to declare these operations. For example, the <code>str</code> module
in the Rust standard library defines the string equality function:</p>
<pre><code class="language-rust ignore">#[lang = &quot;str_eq&quot;]
pub fn eq_slice(a: &amp;str, b: &amp;str) -&gt; bool {
    // details elided
}
</code></pre>
<p>The name <code>str_eq</code> has a special meaning to the Rust compiler, and the presence
of this definition means that it will use this definition when generating calls
to the string equality function.</p>
<p>The set of language items is currently considered unstable. A complete
list of the built-in language items will be added in the future.</p>
<a class="header" href="print.html#inline-attributes" id="inline-attributes"><h3>Inline attributes</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#compiler-features" id="compiler-features"><h3>Compiler Features</h3></a>
<p>Certain aspects of Rust may be implemented in the compiler, but they're not
necessarily ready for every-day use. These features are often of &quot;prototype
quality&quot; or &quot;almost production ready&quot;, but may not be stable enough to be
considered a full-fledged language feature.</p>
<p>For this reason, Rust recognizes a special crate-level attribute of the form:</p>
<pre><code class="language-rust ignore">#![feature(feature1, feature2, feature3)]
</code></pre>
<p>This directive informs the compiler that the feature list: <code>feature1</code>,
<code>feature2</code>, and <code>feature3</code> should all be enabled. This is only recognized at a
crate-level, not at a module-level. Without this directive, all features are
considered off, and using the features will result in a compiler error.</p>
<p>The currently implemented features of the reference compiler are documented in
<a href="https://doc.rust-lang.org/nightly/unstable-book/">The Unstable Book</a>.</p>
<p>If a feature is promoted to a language feature, then all existing programs will
start to receive compilation warnings about <code>#![feature]</code> directives which enabled
the new feature (because the directive is no longer necessary). However, if a
feature is decided to be removed from the language, errors will be issued (if
there isn't a parser error first). The directive in this case is no longer
necessary, and it's likely that existing code will break if the feature isn't
removed.</p>
<p>If an unknown feature is found in a directive, it results in a compiler error.
An unknown feature is one which has never been recognized by the compiler.</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 block, which is in turn a component of an
outer <a href="expressions.html">expression</a> or <a href="items.html#functions">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
items.</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</a> declaration within a module. Declaring an item — a
function, enumeration, struct, type, static, trait, implementation or module
— locally within a statement block is simply a way of restricting its
scope to a narrow region containing all of its uses; it is otherwise identical
in meaning to declaring the item outside the statement block.</p>
<blockquote>
<p><strong>Note</strong>: there is no implicit capture of the function's dynamic environment when
declaring a function-local item.</p>
</blockquote>
<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. The type of an
expression statement <code>e;</code> is always <code>()</code>, regardless of the type of <code>e</code>. As a
rule, an expression statement's purpose is to trigger the effects of evaluating
its expression. An expression that consists of only a <a href="expressions.html#block-expressions">block
expression</a> or control flow expression,
that doesn't end a block and evaluates to <code>()</code> can also be used as an
expression statement by omitting the trailing semicolon.</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>
<a class="header" href="print.html#expressions" id="expressions"><h1>Expressions</h1></a>
<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#lvalues-and-rvalues" id="lvalues-and-rvalues"><h2>Lvalues and rvalues</h2></a>
<p>Expressions are divided into two main categories: <em>lvalues</em> and <em>rvalues</em>.
Likewise within each expression, sub-expressions may occur in <em>lvalue context</em>
or <em>rvalue context</em>. The evaluation of an expression depends both on its own
category and the context it occurs within.</p>
<p>An lvalue is an expression that represents a memory location. These expressions
are <a href="print.html#path-expressions">paths</a> which refer to local variables, function and
method arguments, or static variables,
<a href="print.html#the-dereference-operator">dereferences</a> (<code>*expr</code>), <a href="print.html#index-expressions">indexing
expressions</a> (<code>expr[expr]</code>), <a href="print.html#field-expressions">field
references</a> (<code>expr.f</code>) and parenthesized lvalue
expressions. All other expressions are rvalues.</p>
<p>The left operand of an <a href="print.html#assignment-expressions">assignment</a> or
<a href="print.html#compound-assignment-expressions">compound-assignment</a> expression is an lvalue
context, as is the single operand of a unary <a href="print.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="print.html#match-expressions">match expression</a> and right side of a <code>let</code>
binding may be an lvalue context, if ref bindings are made, but is otherwise an
rvalue context. All other expression contexts are rvalue contexts.</p>
<a class="header" href="print.html#moved-and-copied-types" id="moved-and-copied-types"><h3>Moved and copied types</h3></a>
<p>When an lvalue is evaluated in an <em>rvalue context</em>, it denotes the value held
<em>in</em> that memory location. If value is of a type that implements <code>Copy</code>, then
the value will be copied. In the remaining situations if the type of the value
is <a href="the-sized-trait.html"><code>Sized</code></a> it may be possible to move the value. Only
the following lvalues 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="print.html#field-expressions">Fields</a> of an lvalue which can be moved out of and
doesn't implement <a href="the-drop-trait.html"><code>Drop</code></a>.</li>
<li>The result of <a href="print.html#the-dereference-operator">dereferencing</a> an expression with
type <code>Box&lt;T&gt;</code> and that can also be moved out of.</li>
</ul>
<p>Moving out of an lvalue deinitializes that location (if it comes from a local
variable), so that it can't be read from again. In all other cases, trying to
use an lvalue in an rvalue context is an error.</p>
<a class="header" href="print.html#mutability" id="mutability"><h3>Mutability</h3></a>
<p>For an lvalue to be <a href="print.html#assignment-expressions">assigned</a> to, <a href="print.html#borrow-operators">mutably
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
contexts <em>mutable</em> lvalue contexts, other lvalue contexts are called
<em>immutable</em>.</p>
<p>The following expressions can create mutable lvalues:</p>
<ul>
<li>Mutable <a href="variables.html">variables</a>, which are not currently borrowed.</li>
<li><a href="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="print.html#field-expressions">Fields</a>, this evaluates the subexpression in a mutable
lvalue context.</li>
<li><a href="print.html#the-dereference-operator">Dereferenes</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 for 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 lvalue context.</li>
<li><a href="print.html#index-expressions">Indexing</a> of a type that implements <code>DerefMut</code>, this
then evalutes the value being indexed (but not the index) in mutable lvalue
context.</li>
</ul>
<a class="header" href="print.html#temporary-lifetimes" id="temporary-lifetimes"><h3>Temporary lifetimes</h3></a>
<p>When using an rvalue in most lvalue contexts, a temporary unnamed lvalue is
created and used instead. The lifetime of temporary values is typically the
innermost enclosing statement; the tail expression of a block is considered
part of the statement that encloses the block.</p>
<p>When a temporary rvalue is being created that is assigned into a <code>let</code>
declaration, however, the temporary is created with the lifetime of the
enclosing block instead, as using the enclosing statement (the <code>let</code>
declaration) 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 an rvalue. As it
is being borrowed, a temporary is created which will be freed after
the innermost enclosing statement (the <code>let</code> declaration, in this case).</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 = &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 an lvalue by implicitly
borrowing it. For example, it is possible to compare two unsized
<a href="types.html#array-and-slice-types">slices</a> 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="print.html#method-call-expressions">method-call expressions</a>.</li>
<li>Left operand in <a href="print.html#field-expressions">field expressions</a>.</li>
<li>Left operand in <a href="print.html#call-expressions">call expressions</a>.</li>
<li>Left operand in <a href="print.html#index-expressions">index expressions</a>.</li>
<li>Operand of the <a href="print.html#the-dereference-operator">dereference</a> (<code>*</code>) operator.</li>
<li>Operands of <a href="print.html#comparison-operators">comparison operators</a>.</li>
<li>Left operands of the <a href="print.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.html#constant-items">constants</a> and <a href="items.html#static-items">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="print.html#index-expressions">array access</a> or <a href="print.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:</p>
<ul>
<li><a href="print.html#literal-expressions">Literals</a>.</li>
<li><a href="print.html#path-expressions">Paths</a> to <a href="items.html#functions">functions</a> and constants.
Recursively defining constants is not allowed.</li>
<li>Paths to statics, so long as only their address, not their value, is used.
This includes using their value indirectly through a compilicated expression.
*</li>
<li><a href="print.html#tuple-expressions">Tuple expressions</a>.</li>
<li><a href="print.html#array-expressions">Array expressions</a>.</li>
<li><a href="print.html#struct-expressions">Struct expressions</a>, where the type does not implement
<a href="the-drop-trait.html"><code>Drop</code></a>.</li>
<li><a href="print.html#enumeration-variant-expressions">Variant expressions</a>, where the
enumeration type does not implement <code>Drop</code>.</li>
<li><a href="print.html#block-expressions">Block expressions</a> (and <code>unsafe</code> blocks) which contain
only items and possibly a (constant) tail expression.</li>
<li><a href="print.html#field-expressions">Field expressions</a>.</li>
<li><a href="print.html#index-expressions">Index expressions</a>, indexing a <a href="types.html#array-and-slice-types">array or
slice</a> with a <code>usize</code>.</li>
<li><a href="print.html#range-expressions">Range expressions</a>.</li>
<li><a href="print.html#closure-expressions">Closure expressions</a> which don't capture variables
from the environment.</li>
<li>Built in <a href="print.html#negation-operators">negation</a>, <a href="print.html#arithmetic-and-logical-binary-operators">arithmetic,
logical</a>,
<a href="print.html#comparison-operators">comparison</a> or <a href="print.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="print.html#borrow-operators">borrow expressions</a>.</li>
<li>The <a href="print.html#the-dereference-operator">dereference operator</a>, but not to circumvent the
rule on statics.</li>
<li><a href="print.html#grouped-expressions">Grouped expressions</a>.</li>
<li><a href="print.html#type-cast-expressions">Cast expressions</a>, except pointer to address and
function pointer to address casts.</li>
</ul>
<p>* Only in static items.</p>
<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 here 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"><h2>Literal expressions</h2></a>
<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,
boolean value, or the unit value.</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
();        // unit type
&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"><h2>Path expressions</h2></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#lvalues-and-rvalues">lvalues</a>, other paths
are rvalues. Using a <code>static mut</code> variable requires an <a href="print.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#tuple-expressions" id="tuple-expressions"><h2>Tuple expressions</h2></a>
<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#struct-expressions" id="struct-expressions"><h2>Struct expressions</h2></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.html#structs">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.</p>
<p>Struct expressions can't be used directly in the head of a <a href="print.html#loops">loop</a> or an
<a href="print.html#if-expressions"><code>if</code></a>, <a href="print.html#if-let-expressions"><code>if let</code></a> or
<a href="print.html#match-expressions"><code>match</code></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"><h4>Struct field init shorthand</h4></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"><h3>Enumeration Variant expressions</h3></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#block-expressions" id="block-expressions"><h2>Block expressions</h2></a>
<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 expression. 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#lvalues-and-rvalues">rvalues</a> and evaluate the last
expression in rvalue 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"><h3><code>unsafe</code> blocks</h3></a>
<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.</p>
<a class="header" href="print.html#method-call-expressions" id="method-call-expressions"><h2>Method-call expressions</h2></a>
<p>A <em>method call</em> consists of an expression followed by a single dot, an
<a href="identifiers.html">identifier</a>, and a parenthesized expression-list. Method
calls are resolved to methods 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>. Method call expressions will automatically
take a shared or mutable borrow of the receiver if needed.</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 resolving method calls on an expression of type <code>A</code>, Rust will use the
following order:</p>
<ol>
<li>Inherent methods, with receiver of type <code>A</code>, <code>&amp;A</code>, <code>&amp;mut A</code>.</li>
<li>Trait methods with receiver of type <code>A</code>.</li>
<li>Trait methods with receiver of type <code>&amp;A</code>.</li>
<li>Trait methods with receiver of type <code>&amp;mut A</code>.</li>
<li>If it's possible, Rust will then repeat steps 1-5 with
<code>&lt;A as std::ops::Deref&gt;::Target</code>, and insert a dereference operator.</li>
<li>If <code>A</code> is now an <a href="types.html#array-and-slice-types">array</a> type, then
repeat steps 1-4 with the corresponding slice type.</li>
</ol>
<p>Note: that in steps 1-4 the receiver is used, not the type of <code>Self</code> nor the
type of <code>A</code>. For example</p>
<pre><code class="language-rust ignore">// `Self` is `&amp;A`, receiver is `&amp;A`.
impl&lt;'a&gt; Trait for &amp;'a A {
    fn method(self) {}
}
// If `A` is `&amp;B`, then `Self` is `B` and the receiver is `A`.
impl B {
    fn method(&amp;self) {}
}
</code></pre>
<p>Another note: this process does not use the mutability or lifetime of the
receiver, or whether <code>unsafe</code> methods can currently be called to resolve
methods. These constraints instead lead to compiler errors.</p>
<p>If a step is reached where there is more than one possible method (where
generic methods or traits are considered the same), then it is a compiler
error. These cases require a <a href="print.html#disambiguating-function-calls">more specific
syntax.</a> for method and function invocation.</p>
<a class="header" href="print.html#field-expressions" id="field-expressions"><h2>Field expressions</h2></a>
<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="print.html#method-call-expressions">method call
expression</a>). A field expression denotes a field of a
<a href="types.html#struct-types">struct</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 an <a href="expressions.html#lvalues-and-rvalues">lvalue</a> referring to the value of
that field. When the subexpression is <a href="print.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, a reference to a struct are treated as separate
entities when borrowing. If the struct does not implement
<a href="the-drop-trait.html"><code>Drop</code></a> this also applies to moving out of each of its fields
where possible. 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 {
#     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#tuple-indexing-expressions" id="tuple-indexing-expressions"><h3>Tuple indexing expressions</h3></a>
<p><a href="types.html#tuple-types">Tuples</a> and <a href="items.html#structs">struct tuples</a> can be
indexed using the number corresponding to the possition 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#call-expressions" id="call-expressions"><h2>Call expressions</h2></a>
<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-types">non-function types</a>, the expression f(...) uses the
method on one of the <code>std::ops::Fn</code>, <code>std::ops::FnMut</code> or <code>std::ops::FnOnce</code>
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"><h3>Disambiguating Function Calls</h3></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#closure-expressions" id="closure-expressions"><h2>Closure expressions</h2></a>
<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="print.html#block-expressions">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.html#functions">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="the-send-trait.html"><code>Send</code></a> and/or <a href="the-sync-trait.html"><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#array-expressions" id="array-expressions"><h2>Array expressions</h2></a>
<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="print.html#constant-expressions">constant expression</a>, such as a
<a href="tokens.html#literals">literal</a> or a <a href="items.html#constant-items">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="the-copy-trait.html"><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];

#}</code></pre></pre>
<a class="header" href="print.html#index-expressions" id="index-expressions"><h2>Index expressions</h2></a>
<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 (the index) after them.
When the array is mutable, the resulting
<a href="expressions.html#lvalues-and-rvalues">lvalue</a> can be assigned to.
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::opsIndexMut::index_mut(&amp;mut a, b)</code>
in a mutable lvalue 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, and are of type <code>usize</code> for arrays and slices. Array
access is a <a href="print.html#constant-expressions">constant expression</a>, so bounds can be
checked at compile-time for constant arrays 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() {
([1, 2, 3, 4])[2];        // Evaluates to 3

let x = ([&quot;a&quot;, &quot;b&quot;])[10]; // warning: const index-expr is 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];                  // panics

#}</code></pre></pre>
<a class="header" href="print.html#range-expressions" id="range-expressions"><h2>Range expressions</h2></a>
<p>The <code>..</code> operator will construct an object of one of the <code>std::ops::Range</code> (or
<code>core::ops::Range</code>) variants.</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

#}</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>
<a class="header" href="print.html#operator-expressions" id="operator-expressions"><h2>Operator expressions</h2></a>
<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"><h3>Overflow</h3></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"><h3>Borrow operators</h3></a>
<p>The <code>&amp;</code> (shared borrow) and <code>&amp;mut</code> (mutable borrow) operators are unary prefix
operators. When applied to an lvalue produce a reference (pointer) to the
location that the value refers to. The lvalue is also placed into a borrowed
state for the duration of the reference. For a shared borrow (<code>&amp;</code>), this
implies that the lvalue may not be mutated, but it may be read or shared again.
For a mutable borrow (<code>&amp;mut</code>), the lvalue may not be accessed in any way until
the borrow expires. <code>&amp;mut</code> evaluates its operand in a mutable lvalue context.
If the <code>&amp;</code> or <code>&amp;mut</code> operators are applied to an rvalue, a temporary value is
created; the lifetime of this temporary value is defined by <a href="print.html#temporary-lifetimes">syntactic
rules</a>. 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>
<a class="header" href="print.html#the-dereference-operator" id="the-dereference-operator"><h3>The dereference operator</h3></a>
<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 variance or is a mutable lvalue, then the
resulting <a href="expressions.html#lvalues-and-rvalues">lvalue</a> 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="print.html#mutability">immutable lvalue context</a> and <code>*std::ops::Deref::deref_mut(&amp;mut x)</code> in a mutable lvalue 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--operator" id="the--operator"><h3>The <code>?</code> operator.</h3></a>
<p>The <code>?</code> (&quot;question mark&quot;) operator can be applied to values of the <code>Result&lt;T, E&gt;</code> type to propagate errors. If applied to <code>Err(e)</code> it will return
<code>Err(From::from(e))</code> from the enclosing function or closure. If applied to
<code>Ok(x)</code> it will unwrap the value to return <code>x</code>. Unlike other unary operators
<code>?</code> is written in postfix notation. <code>?</code> cannot be overloaded.</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>
<a class="header" href="print.html#negation-operators" id="negation-operators"><h3>Negation operators</h3></a>
<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
rvalue context so are moved or copied.</p>
<table><thead><tr><td> Symbol </td><td> Integer     </td><td> <code>bool</code>      </td><td> Floating Point </td><td> Overloading Trait  </td></tr></thead>
<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>
</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"><h3>Arithmetic and Logical Binary Operators</h3></a>
<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 rvalue
context so are moved or copied.</p>
<table><thead><tr><td> Symbol </td><td> Integer                 </td><td> <code>bool</code>      </td><td> Floating Point </td><td> Overloading Trait  </td></tr></thead>
<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>
</table>
<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"><h3>Comparison Operators</h3></a>
<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 lvalue context:</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><td> Symbol </td><td> Meaning                  </td><td> Overloading method         </td></tr></thead>
<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>
</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"><h3>Lazy boolean operators</h3></a>
<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"><h3>Type cast expressions</h3></a>
<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><td> Type of <code>e</code>           </td><td> <code>U</code>                   </td><td> Cast performed by <code>e as U</code>       </td></tr></thead>
<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-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>
</table>
<p>* or <code>T</code> and <code>V</code> are compatible unsized types, e.g., both slices, both the
same trait object.</p>
<a class="header" href="print.html#semantics" id="semantics"><h4>Semantics</h4></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"><h3>Assignment expressions</h3></a>
<p>An <em>assignment expression</em> consists of an
<a href="expressions.html#lvalues-and-rvalues">lvalue</a> expression followed
by an equals sign (<code>=</code>) and an
<a href="expressions.html#lvalues-and-rvalues">rvalue</a> expression.</p>
<p>Evaluating an assignment expression <a href="print.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 an lvalue: using an rvalue 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"><h3>Compound assignment expressions</h3></a>
<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>lval OP= val</code> is equivalent to
<code>lval = lval 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></a> type.
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>lval</code> must be an lvalue.</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#operator-precedence" id="operator-precedence"><h3>Operator precedence</h3></a>
<p>The precedence of Rust operators is ordered as follows, going from strong to
weak. Binary Operators at the same precedence level are evaluated in the order
given by their associativity.</p>
<table><thead><tr><td> Operator                    </td><td> Associativity       </td></tr></thead>
<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> <code>:</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>&lt;-</code>                        </td><td> right to left       </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>
</table>
<a class="header" href="print.html#grouped-expressions" id="grouped-expressions"><h2>Grouped expressions</h2></a>
<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>
<a class="header" href="print.html#loops" id="loops"><h2>Loops</h2></a>
<p>Rust supports three 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#iterator-loops"><code>for</code> expression</a> extracts values from an iterator,
looping until the iterator is empty.</li>
</ul>
<p>All three 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"><h3>Infinite loops</h3></a>
<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
<a href="items.html#diverging-functions">diverging</a>, and doesn't
return anything. 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"><h3>Predicate loops</h3></a>
<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#iterator-loops" id="iterator-loops"><h3>Iterator loops</h3></a>
<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"><h3>Loop labels</h3></a>
<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"><h3><code>break</code> expressions</h3></a>
<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"><h3><code>continue</code> expressions</h3></a>
<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"><h3><code>break</code> and loop values</h3></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#if-expressions" id="if-expressions"><h2><code>if</code> expressions</h2></a>
<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#match-expressions" id="match-expressions"><h2><code>match</code> expressions</h2></a>
<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 an <a href="expressions.html#lvalues-and-rvalues">lvalue or an rvalue</a>.
If the head expression is an rvalue, 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 an lvalue, the match does not allocate a temporary
location (however, a by-value binding may copy or move from the lvalue). When
possible, it is preferable to match on lvalues, as the lifetime of these
matches inherits the lifetime of the lvalue, 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. A 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 = 2;
let message = match x {
    0 | 1  =&gt; &quot;not many&quot;,
    2 ... 9 =&gt; &quot;a few&quot;,
    _      =&gt; &quot;lots&quot;
};

#}</code></pre></pre>
<p>Range patterns only work on scalar types (like integers and characters; not
like arrays and structs, which have sub-components). A range pattern may not be
a sub-range of another range pattern inside the same <code>match</code>.</p>
<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#if-let-expressions" id="if-let-expressions"><h2><code>if let</code> expressions</h2></a>
<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>
<a class="header" href="print.html#while-let-loops" id="while-let-loops"><h2><code>while let</code> loops</h2></a>
<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> and an 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#return-expressions" id="return-expressions"><h2><code>return</code> expressions</h2></a>
<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 and type-constructors 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>The primitive types are the following:</p>
<ul>
<li>The boolean type <code>bool</code> with values <code>true</code> and <code>false</code>.</li>
<li>The machine types (integer and floating-point).</li>
<li>The machine-dependent integer types.</li>
<li>Arrays</li>
<li>Tuples</li>
<li>Slices</li>
<li>Function pointers</li>
</ul>
<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> and <code>u64</code>, with values drawn from
the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1] and
[0, 2^64 - 1] respectively.</p>
</li>
<li>
<p>The signed two's complement word types <code>i8</code>, <code>i16</code>, <code>i32</code> and <code>i64</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]
respectively.</p>
</li>
<li>
<p>The IEEE 754-2008 <code>binary32</code> and <code>binary64</code> 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> array is effectively an 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 of
unknown size, 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#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>&amp;[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 'view' into an array. It doesn't own the data it points
to, it borrows it.</p>
<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
let vector: Vec&lt;i32&gt; = vec![1, 2, 3];

// A slice into an array
let slice: &amp;[i32] = &amp;vector[..];

#}</code></pre></pre>
<p>As you can see, the <code>vec!</code> macro allows you to create a <code>Vec&lt;T&gt;</code> easily. The
<code>vec!</code> macro is also part of the standard library, rather than the language.</p>
<p>All in-bounds elements of arrays and slices are always initialized, and access
to an array or slice is always bounds-checked.</p>
<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>
<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>
<p>New instances of a <code>struct</code> can be constructed with a <a href="expressions.html#struct-expressions">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.html#struct-expressions">struct
expression</a> is the only value that inhabits such a
type.</p>
<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.html#enumerations"><code>enum</code> item</a>. <sup class="footnote-reference"><a href="print.html#enumtype">2</a></sup></p>
</div>
<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>
<p>An <a href="items.html#enumerations"><code>enum</code> item</a> declares both the type and a number of <em>variant
constructors</em>, each of which is independently named and takes an optional tuple
of arguments.</p>
<p>New instances of an <code>enum</code> can be constructed by calling one of the variant
constructors, in a <a href="expressions.html#call-expressions">call expression</a>.</p>
<p>Any <code>enum</code> value consumes as much memory as the largest variant constructor for
its corresponding <code>enum</code> type.</p>
<p>Enum types cannot be denoted <em>structurally</em> as types, but must be denoted by
named reference to an <a href="items.html#enumerations"><code>enum</code> item</a>.</p>
<a class="header" href="print.html#recursive-types" id="recursive-types"><h2>Recursive types</h2></a>
<p>Nominal types — <a href="print.html#enumerated-types">enumerations</a> and
<a href="print.html#struct-types">structs</a> — may be recursive. That is, each <code>enum</code>
constructor or <code>struct</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>).</li>
<li>A recursive <code>enum</code> item must have at least one non-recursive constructor
(in order to give the recursion a basis case).</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 copied,
stored into data structs, and returned from functions. There are two
varieties of pointer in Rust:</p>
<ul>
<li>
<p>References (<code>&amp;</code>)
: These point to memory <em>owned by some other value</em>.
A 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.
Releasing a reference has no effect on the value it points to,
but a reference of a temporary value will keep it alive during the scope
of the reference itself.</p>
</li>
<li>
<p>Raw pointers (<code>*</code>)
: 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 or converting it to any other
pointer type is an <a href="unsafe-functions.html"><code>unsafe</code> operation</a>.
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>
</li>
</ul>
<p>The standard library contains additional 'smart pointer' types beyond references
and raw pointers.</p>
<a class="header" href="print.html#function-types" id="function-types"><h2>Function types</h2></a>
<p>The function type constructor <code>fn</code> forms new function types. A function 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 of a <code>fn</code> 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#function-types-for-specific-items" id="function-types-for-specific-items"><h3>Function types for specific items</h3></a>
<p>Internal to the compiler, there are also function types that are specific to a particular
function item. In the following snippet, for example, the internal types of the functions
<code>foo</code> and <code>bar</code> are different, despite the fact that they have the same signature:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn foo() { }
fn bar() { }

#}</code></pre></pre>
<p>The types of <code>foo</code> and <code>bar</code> can both be implicitly coerced to the fn
pointer type <code>fn()</code>. There is currently no syntax for unique fn types,
though the compiler will emit a type like <code>fn() {foo}</code> in error
messages to indicate &quot;the unique fn type for the function <code>foo</code>&quot;.</p>
<a class="header" href="print.html#closure-types" id="closure-types"><h2>Closure types</h2></a>
<p>A <a href="expressions.html#closure-expressions">closure expression</a> produces a closure
value with a unique, anonymous type that cannot be written out.</p>
<p>Depending on the requirements of the closure, its type implements one or
more of the closure traits:</p>
<ul>
<li>
<p><code>FnOnce</code>
: The closure can be called once. A closure called as <code>FnOnce</code>
can move out values from its environment.</p>
</li>
<li>
<p><code>FnMut</code>
: The closure can be called multiple times as mutable. A closure called as
<code>FnMut</code> can mutate values from its environment. <code>FnMut</code> inherits from
<code>FnOnce</code> (i.e. anything implementing <code>FnMut</code> also implements <code>FnOnce</code>).</p>
</li>
<li>
<p><code>Fn</code>
: The closure can be called multiple times through a shared reference.
A closure called as <code>Fn</code> can neither move out from nor mutate values
from its environment, but read-only access to such values is allowed.
<code>Fn</code> inherits from <code>FnMut</code>, which itself inherits from <code>FnOnce</code>.</p>
</li>
</ul>
<p>Closures that don't use anything from their environment (&quot;non capturing closures&quot;)
can be coerced to function pointers (<code>fn</code>) with the matching signature.
To adopt the example from the section above:</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#trait-objects" id="trait-objects"><h2>Trait objects</h2></a>
<p>In Rust, a type like <code>&amp;SomeTrait</code> or <code>Box&lt;SomeTrait&gt;</code> is called a <em>trait object</em>.
Each instance of 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> 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>Note that for a trait object to be instantiated, the trait must be
<em>object-safe</em>. Object safety rules are defined in <a href="https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md">RFC 255</a>.</p>
<p>Given a pointer-typed expression <code>E</code> of type <code>&amp;T</code> or <code>Box&lt;T&gt;</code>, where <code>T</code>
implements trait <code>R</code>, casting <code>E</code> to the corresponding pointer type <code>&amp;R</code> or
<code>Box&lt;R&gt;</code> results in a value of the <em>trait object</em> <code>R</code>. This result is
represented as a pair of pointers: the vtable pointer for the <code>T</code>
implementation of <code>R</code>, and the pointer value of <code>E</code>.</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;Printable&gt;) {
    println!(&quot;{}&quot;, a.stringify());
}

fn main() {
    print(Box::new(10) as Box&lt;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>
<p>Since a trait object can contain references, the lifetimes of those references
need to be expressed as part of the trait object. The assumed lifetime of
references held by a trait object 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>For traits that themselves have no lifetime parameters, the default bound is
based on what kind of trait object is used:</p>
<pre><code class="language-rust ignore">// For the following trait...
trait Foo { }

// ...these two are the same:
Box&lt;Foo&gt;
Box&lt;Foo + 'static&gt;

// ...and so are these:
&amp;'a Foo
&amp;'a (Foo + 'a)
</code></pre>
<p>The <code>+ 'static</code> and <code>+ 'a</code> refer to the default bounds of those kinds of trait
objects, and also to how you can directly override them. Note that the innermost
object sets the bound, so <code>&amp;'a Box&lt;Foo&gt;</code> is still <code>&amp;'a Box&lt;Foo + 'static&gt;</code>.</p>
<p>For traits that have lifetime parameters of their own, the default bound is
based on that lifetime parameter:</p>
<pre><code class="language-rust ignore">// For the following trait...
trait Bar&lt;'a&gt;: 'a { }

// ...these two are the same:
Box&lt;Bar&lt;'a&gt;&gt;
Box&lt;Bar&lt;'a&gt; + 'a&gt;
</code></pre>
<p>The default for user-defined trait objects is based on the object type itself.
If a type parameter has a lifetime bound, then that lifetime bound becomes the
default bound for trait objects of that type. For example, <code>std::cell::Ref&lt;'a, T&gt;</code> contains a <code>T: 'a</code> bound, therefore trait objects of type <code>Ref&lt;'a, SomeTrait&gt;</code> are the same as <code>Ref&lt;'a, (SomeTrait + 'a)&gt;</code>.</p>
<a class="header" href="print.html#type-parameters-1" id="type-parameters-1"><h3>Type parameters</h3></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#self-types" id="self-types"><h2>Self types</h2></a>
<p>The special type <code>Self</code> has a meaning within traits and impls. In a trait definition, it refers
to an implicit type parameter representing the &quot;implementing&quot; type. In an impl,
it is an alias for 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>
<p>The notation <code>&amp;self</code> is a shorthand for <code>self: &amp;Self</code>. In this case,
in the impl, <code>Self</code> refers to the value of type <code>String</code> that is the
receiver for a call to the method <code>make_string</code>.</p>
</div>
<a class="header" href="print.html#subtyping" id="subtyping"><h1>Subtyping</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> &quot;lives longer&quot; than <code>'a</code>, <code>&amp;'static str</code> is a subtype of
<code>&amp;'a str</code>.</p>
<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>
</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> 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(coerce_inner(<code>T</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</p>
<ul>
<li>coerce_inner(<code>[T, ..n]</code>) = <code>[T]</code></li>
<li>coerce_inner(<code>T</code>) = <code>U</code> where <code>T</code> is a concrete type which implements the
trait <code>U</code>.</li>
</ul>
<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 <a href="https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md">RFC 401</a> for more details.</p>
</li>
<li>
<p>Non capturing closures to <code>fn</code> pointers</p>
</li>
</ul>
<a class="header" href="print.html#special-traits" id="special-traits"><h1>Special traits</h1></a>
<p>Several traits define special evaluation behavior.</p>
<a class="header" href="print.html#the-copy-trait" id="the-copy-trait"><h1>The <code>Copy</code> trait</h1></a>
<p>The <code>Copy</code> trait changes the semantics of a type implementing it. Values whose
type implements <code>Copy</code> are copied rather than moved upon assignment.</p>
<a class="header" href="print.html#the-sized-trait" id="the-sized-trait"><h1>The <code>Sized</code> trait</h1></a>
<p>The <code>Sized</code> trait indicates that the size of this type is known at compile-time.</p>
<a class="header" href="print.html#the-drop-trait" id="the-drop-trait"><h1>The <code>Drop</code> trait</h1></a>
<p>The <code>Drop</code> trait provides a destructor, to be run whenever a value of this type
is to be destroyed.</p>
<a class="header" href="print.html#the-deref-trait" id="the-deref-trait"><h1>The <code>Deref</code> trait</h1></a>
<p>The <code>Deref&lt;Target = U&gt;</code> trait allows a type to implicitly implement all the methods
of the type <code>U</code>. When attempting to resolve a method call, the compiler will search
the top-level type for the implementation of the called method. If no such method is
found, <code>.deref()</code> is called and the compiler continues to search for the method
implementation in the returned type <code>U</code>.</p>
<a class="header" href="print.html#the-send-trait" id="the-send-trait"><h1>The <code>Send</code> trait</h1></a>
<p>The <code>Send</code> trait indicates that a value of this type is safe to send from one
thread to another.</p>
<a class="header" href="print.html#the-sync-trait" id="the-sync-trait"><h1>The <code>Sync</code> trait</h1></a>
<p>The <code>Sync</code> trait indicates that a value of this type is safe to share between
multiple threads.</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. Typicall targets
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.html#mutable-statics">mutable static variable</a>.</li>
<li>Calling an unsafe function (including an intrinsic or foreign function).</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>The following is a list of behavior which is forbidden in all Rust code,
including within <code>unsafe</code> blocks and <code>unsafe</code> functions. Type checking provides
the guarantee that these issues are never caused by safe code.</p>
<ul>
<li>Data races</li>
<li>Dereferencing a null/dangling raw pointer</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>
with 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 <code>UnsafeCell&lt;U&gt;</code>. Unsafe code must not violate these aliasing
guarantees.</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 <code>UnsafeCell&lt;U&gt;</code>.</li>
<li>Invoking undefined behavior via compiler intrinsics:
<ul>
<li>Indexing outside of the bounds of an object with <code>std::ptr::offset</code>
(<code>offset</code> intrinsic), with
the exception of one byte past the end which is permitted.</li>
<li>Using <code>std::ptr::copy_nonoverlapping_memory</code> (<code>memcpy32</code>/<code>memcpy64</code>
intrinsics) on overlapping buffers</li>
</ul>
</li>
<li>Invalid values in primitive types, even in private fields/locals:
<ul>
<li>Dangling/null references or boxes</li>
<li>A value other than <code>false</code> (0) or <code>true</code> (1) 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>
<li>Unwinding into Rust from foreign code or unwinding from Rust into foreign
code. Rust's failure system is not compatible with exception handling in
other languages. Unwinding must be caught and handled at FFI boundaries.</li>
</ul>
<a class="header" href="print.html#behavior-not-considered-unsafe" id="behavior-not-considered-unsafe"><h2>Behavior not considered unsafe</h2></a>
<p>This is a list of behavior not considered <em>unsafe</em> in Rust terms, but that may
be undesired.</p>
<ul>
<li>Deadlocks</li>
<li>Leaks of memory and other resources</li>
<li>Exiting without calling destructors</li>
<li>Integer overflow
<ul>
<li>Overflow is considered &quot;unexpected&quot; behavior and is always user-error,
unless the <code>wrapping</code> primitives are used. In non-optimized builds, the compiler
will insert debug checks that panic on overflow, but in optimized builds overflow
instead results in wrapped values. See <a href="https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md">RFC 560</a> for the rationale and more details.</li>
</ul>
</li>
</ul>
<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><a href="https://github.com/rust-lang/rfcs/pull/558">Require parentheses for chained comparisons</a></li>
<li><a href="https://github.com/rust-lang/rfcs/pull/560">Integer overflow not <code>unsafe</code></a> - documented with a reference to the RFC, but
requires further details</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>

                </div>

                <!-- Mobile navigation buttons -->
                

                

            </div>

            

            

        </div>


        <!-- Local fallback for Font Awesome -->
        <script>
            if ($(".fa").css("font-family") !== "FontAwesome") {
                $('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
            }
        </script>

        <!-- Livereload script (if served using the cli tool) -->
        

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