Sophie

Sophie

distrib > Mageia > 6 > x86_64 > media > core-updates > by-pkgid > f9731dfa50015223ad228047cd6e9424 > files > 3003

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

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Items - 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://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/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="keywords.html"><strong>2.2.</strong> Keywords</a></li><li><a href="identifiers.html"><strong>2.3.</strong> Identifiers</a></li><li><a href="comments.html"><strong>2.4.</strong> Comments</a></li><li><a href="whitespace.html"><strong>2.5.</strong> Whitespace</a></li><li><a href="tokens.html"><strong>2.6.</strong> Tokens</a></li><li><a href="paths.html"><strong>2.7.</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" class="active"><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><li class="affix"><a href="glossory.html">Appendix: Glossory</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="items.html#items" id="items"><h1>Items</h1></a>
<p>An <em>item</em> is a component of a crate. Items are organized within a crate by a
nested set of <a href="items.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="items.html#modules">modules</a></li>
<li><a href="items.html#extern-crate-declarations"><code>extern crate</code> declarations</a></li>
<li><a href="items.html#use-declarations"><code>use</code> declarations</a></li>
<li><a href="items.html#functions">function definitions</a></li>
<li><a href="items.html#type-aliases">type definitions</a></li>
<li><a href="items.html#structs">struct definitions</a></li>
<li><a href="items.html#enumerations">enumeration definitions</a></li>
<li><a href="items.html#unions">union definitions</a></li>
<li><a href="items.html#constant-items">constant items</a></li>
<li><a href="items.html#static-items">static items</a></li>
<li><a href="items.html#traits">trait definitions</a></li>
<li><a href="items.html#implementations">implementations</a></li>
<li><a href="items.html#external-blocks"><code>extern</code> blocks</a></li>
</ul>
<p>Some items form an implicit scope for the declaration of sub-items. In other
words, within a function or module, declarations of items can (in many cases)
be mixed with the statements, control blocks, and similar artifacts that
otherwise compose the item body. The meaning of these scoped items is the same
as if the item was declared outside the scope — it is still a static item
— except that the item's <em>path name</em> within the module namespace is
qualified by the name of the enclosing item, or is private to the enclosing
item (in the case of functions). The grammar specifies the exact locations in
which sub-item declarations may appear.</p>
<a class="header" href="items.html#type-parameters" id="type-parameters"><h2>Type Parameters</h2></a>
<p>Functions, type aliases, structs, enumerations, unions, traits and
implementations 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 (except for implementations, where they come directly
after <code>impl</code>) and before its definition.</p>
<p>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="items.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, union, type parameter or crate can't shadow the name of a
module in scope, or vice versa. Items brought into scope with <code>use</code> also have
this restriction.</p>
<p>A module without a body is loaded from an external file, by default with the
same name as the module, plus the <code>.rs</code> extension. When a nested submodule is
loaded from an external file, it is loaded from a subdirectory path that
mirrors the module hierarchy.</p>
<pre><code class="language-rust ignore">// Load the `vec` module from `vec.rs`
mod vec;

mod thread {
    // Load the `local_data` module from `thread/local_data.rs`
    // or `thread/local_data/mod.rs`.
    mod local_data;
}
</code></pre>
<p>The directories and files used for loading external file modules can be
influenced with the <code>path</code> attribute.</p>
<pre><code class="language-rust ignore">#[path = &quot;thread_files&quot;]
mod thread {
    // Load the `local_data` module from `thread_files/tls.rs`
    #[path = &quot;tls.rs&quot;]
    mod local_data;
}
</code></pre>
<a class="header" href="items.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="items.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="items.html#modules">modules</a>
and <a href="expressions.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="items.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="items.html#functions" id="functions"><h2>Functions</h2></a>
<p>A <em>function</em> consists of a <a href="expressions.html#block-expressions">block</a>, along with a name and a set of parameters.
Other than a name, all these are optional. Functions are declared with the
keyword <code>fn</code>. Functions may declare a set of <em>input</em> <a href="variables.html"><em>variables</em></a>
as parameters, through which the caller passes arguments into the function, and
the <em>output</em> <a href="types.html"><em>type</em></a> of the value the function will return to its caller
on completion.</p>
<p>When referred to, a <em>function</em> yields a first-class <em>value</em> of the
corresponding zero-sized <a href="types.html#function-item-types"><em>function item type</em></a>, which
when called evaluates to a direct call to the function.</p>
<p>For example, this is a simple function:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn answer_to_life_the_universe_and_everything() -&gt; i32 {
    return 42;
}

#}</code></pre></pre>
<p>As with <code>let</code> bindings, function arguments are irrefutable patterns, so any
pattern that is valid in a let binding is also valid as an argument:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
fn first((value, _): (i32, i32)) -&gt; i32 { value }

#}</code></pre></pre>
<p>The block of a function is conceptually wrapped in a block that binds the
argument patterns and then <code>return</code>s the value of the function's block. This
means that the tail expression of the block, if evaluated, ends up being
returned to the caller. As usual, an explicit return expression within
the body of the function will short-cut that implicit return, if reached.</p>
<p>For example, the function above behaves as if it was written as:</p>
<pre><code class="language-rust ignore">// argument_0 is the actual first argument passed from the caller
let (value, _) = argument_0;
return {
    value
};
</code></pre>
<a class="header" href="items.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><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
// foo is generic over A and B

fn foo&lt;A, B&gt;(x: A, y: B) {
# }

#}</code></pre></pre>
<p>Inside the function signature and body, the name of the type parameter can be
used as a type name. <a href="items.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><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# use std::fmt::Debug;
fn foo&lt;T&gt;(x: T) where T: Debug {
# }

#}</code></pre></pre>
<p>When a generic function is referenced, its type is instantiated based on the
context of the reference. For example, calling the <code>foo</code> function here:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
use std::fmt::Debug;

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

foo(&amp;[1, 2]);

#}</code></pre></pre>
<p>will instantiate type parameter <code>T</code> with <code>i32</code>.</p>
<p>The type parameters can also be explicitly supplied in a trailing <a href="paths.html">path</a>
component after the function name. This might be necessary if there is not
sufficient context to determine the type parameters. For example,
<code>mem::size_of::&lt;u32&gt;() == 4</code>.</p>
<a class="header" href="items.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="items.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="items.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
# #[cfg(target_arch = &quot;x86_64&quot;)]
extern &quot;stdcall&quot; fn new_i32_stdcall() -&gt; i32 { 0 }

#}</code></pre></pre>
<p>Unlike normal functions, extern fns have type <code>extern &quot;ABI&quot; fn()</code>. This is the
same type as the functions declared in an extern block.</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# extern fn new_i32() -&gt; i32 { 0 }
let fptr: extern &quot;C&quot; fn() -&gt; i32 = new_i32;

#}</code></pre></pre>
<a class="header" href="items.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="items.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="items.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. Each enum instance has a <em>discriminant</em> which is an
integer associated to it that is used to determine which variant it holds.</p>
<a class="header" href="items.html#c-like-enumerations" id="c-like-enumerations"><h3>C-like Enumerations</h3></a>
<p>If there is no data attached to <em>any</em> of the variants of an enumeration it is
called a <em>c-like enumeration</em>. If a discriminant isn't specified, they start at
zero, and add one for each variant, in order. Each enum value is just its
discriminant which you can specify explicitly:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
enum Foo {
    Bar,            // 0
    Baz = 123,
    Quux,           // 124
}

#}</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>You can also cast a c-like enum to get its discriminant:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
# enum Foo { Baz = 123 }
let x = Foo::Baz 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>Baz(i32)</code>, this is disallowed.</p>
<a class="header" href="items.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="items.html#constant-items" id="constant-items"><h2>Constant items</h2></a>
<p>A <em>constant item</em> is a named <em><a href="expressions.html#constant-expressions">constant value</a></em> which is not associated with a
specific memory location in the program. Constants are essentially inlined
wherever they are used, meaning that they are copied directly into the relevant
context when used. References to the same constant are not necessarily
guaranteed to refer to the same memory address.</p>
<p>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="items.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 any type that doesn't
implement <a href="the-drop-trait.html"><code>Drop</code></a> and has a <code>'static</code> lifetime: any references it contains
must have <code>'static</code> lifetimes.</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="items.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="items.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="items.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="items.html#traits" id="traits"><h2>Traits</h2></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><a href="items.html#associated-functions-and-methods">functions</a></li>
<li><a href="items.html#associated-types">types</a></li>
<li><a href="items.html#associated-constants">constants</a></li>
</ul>
<p>All traits define an implicit type parameter <code>Self</code> that refers to &quot;the type
that is implementing this interface&quot;. Traits may also contain additional type
parameters. These type parameters (including <code>Self</code>) may be constrained by
other traits and so forth as usual.</p>
<p>Traits are implemented for specific types through separate <a href="items.html#implementations">implementations</a>.</p>
<a class="header" href="items.html#associated-functions-and-methods" id="associated-functions-and-methods"><h3>Associated functions and methods</h3></a>
<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>) as well as the usual
function call notation (<code>foo(x)</code>).</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="items.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>. Note that <code>&amp;self</code> is short for <code>self: &amp;Self</code>, and similarly, <code>self</code> is short for <code>self: Self</code> and  <code>&amp;mut self</code> is
short for <code>self: &amp;mut Self</code>.</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="items.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>Associated functions may lack a <code>self</code> argument, sometimes called 'static
methods'. 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 or type 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);
let x: f64 = f64::from_i32(42);

#}</code></pre></pre>
<a class="header" href="items.html#associated-types" id="associated-types"><h3>Associated Types</h3></a>
<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>
<a class="header" href="items.html#associated-constants" id="associated-constants"><h3>Associated Constants</h3></a>
<p>A trait can define constants like this:</p>
<pre><pre class="playpen"><code class="language-rust">trait Foo {
    const ID: i32;
}

impl Foo for i32 {
    const ID: i32 = 1;
}

fn main() {
    assert_eq!(1, i32::ID);
}
</code></pre></pre>
<p>Any implementor of <code>Foo</code> will have to define <code>ID</code>. Without the definition:</p>
<pre><pre class="playpen"><code class="language-rust compile_fail E0046"># #![allow(unused_variables)]
#fn main() {
trait Foo {
    const ID: i32;
}

impl Foo for i32 {
}

#}</code></pre></pre>
<p>gives</p>
<pre><code class="language-text">error: not all trait items implemented, missing: `ID` [E0046]
     impl Foo for i32 {
     }
</code></pre>
<p>A default value can be implemented as well:</p>
<pre><pre class="playpen"><code class="language-rust">trait Foo {
    const ID: i32 = 1;
}

impl Foo for i32 {
}

impl Foo for i64 {
    const ID: i32 = 5;
}

fn main() {
    assert_eq!(1, i32::ID);
    assert_eq!(5, i64::ID);
}
</code></pre></pre>
<p>As you can see, when implementing <code>Foo</code>, you can leave it unimplemented, as
with <code>i32</code>. It will then use the default value. But, as in <code>i64</code>, we can also
add our own definition.</p>
<p>Associated constants don’t have to be associated with a trait. An <code>impl</code> block
for a <code>struct</code> or an <code>enum</code> works fine too:</p>
<pre><pre class="playpen"><code class="language-rust"># #![allow(unused_variables)]
#fn main() {
struct Foo;

impl Foo {
    const FOO: u32 = 3;
}

#}</code></pre></pre>
<a class="header" href="items.html#trait-bounds" id="trait-bounds"><h3>Trait bounds</h3></a>
<p>Generic functions may use traits as <em>bounds</em> on their type parameters. This
will have three 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. Associated types can be used in the
function's signature, and associated constants can be used in expressions
within the function body.</li>
<li>Generic functions and types with the same or weaker bounds can use the
generic type in the function body or signature.</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); }
struct Figure&lt;S: Shape&gt;(S, S);
fn draw_twice&lt;T: Shape&gt;(surface: Surface, sh: T) {
    sh.draw(surface);
    sh.draw(surface);
}
fn draw_figure&lt;U: Shape&gt;(surface: Surface, Figure(sh1, sh2): Figure&lt;U&gt;) {
    sh1.draw(surface);
    draw_twice(surface, sh2); // Can call this since U: Shape
}

#}</code></pre></pre>
<a class="header" href="items.html#trait-objects" id="trait-objects"><h3>Trait objects</h3></a>
<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>
<a class="header" href="items.html#supertraits" id="supertraits"><h3>Supertraits</h3></a>
<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>. 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><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; }
# 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></pre>
<a class="header" href="items.html#implementations" id="implementations"><h2>Implementations</h2></a>
<p>An <em>implementation</em> is an item that can implement a <a href="items.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, unions, 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 and lifetime parameters, which can be used in
the rest of the implementation. Type parameters declared for an implementation
must be used at least once in either the trait or the type of an
implementation. 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="items.html#external-blocks" id="external-blocks"><h2>External blocks</h2></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>

                </div>

                <!-- Mobile navigation buttons -->
                
                    <a href="items-and-attributes.html" class="mobile-nav-chapters previous">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="visibility-and-privacy.html" class="mobile-nav-chapters next">
                        <i class="fa fa-angle-right"></i>
                    </a>
                

            </div>

            
                <a href="items-and-attributes.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-left"></i>
                </a>
            

            
                <a href="visibility-and-privacy.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
                    <i class="fa fa-angle-right"></i>
                </a>
            

        </div>


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

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

        


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