Sophie

Sophie

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

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

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Types - 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" class="active"><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="types.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="types.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="types.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="types.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="types.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="types.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="types.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="types.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="types.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="types.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="types.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="types.html#recursive-types" id="recursive-types"><h2>Recursive types</h2></a>
<p>Nominal types — <a href="types.html#enumerated-types">enumerations</a> and
<a href="types.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="types.html#array-and-slice-types">arrays</a> or <a href="types.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="types.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="types.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="types.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="types.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="types.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="types.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="types.html#type-parameters" id="type-parameters"><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="types.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>

                </div>

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

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

            </div>

            
                <a href="type-system.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="subtyping.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>