<!DOCTYPE HTML> <html lang="en" class="sidebar-visible no-js"> <head> <!-- Book generated using mdBook --> <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"> <meta name="theme-color" content="#ffffff" /> <base href=""> <link rel="stylesheet" href="book.css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css"> <link rel="shortcut icon" href="favicon.png"> <!-- Font Awesome --> <link rel="stylesheet" href="_FontAwesome/css/font-awesome.css"> <link rel="stylesheet" href="highlight.css"> <link rel="stylesheet" href="tomorrow-night.css"> <link rel="stylesheet" href="ayu-highlight.css"> <!-- Custom theme stylesheets --> <link rel="stylesheet" href="src/theme/reference.css"> </head> <body class="light"> <!-- Work around some values being stored in localStorage wrapped in quotes --> <script type="text/javascript"> try { var theme = localStorage.getItem('mdbook-theme'); var sidebar = localStorage.getItem('mdbook-sidebar'); if (theme.startsWith('"') && theme.endsWith('"')) { localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1)); } if (sidebar.startsWith('"') && sidebar.endsWith('"')) { localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1)); } } catch (e) { } </script> <!-- Set the theme before any content is loaded, prevents flash --> <script type="text/javascript"> var theme; try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } if (theme === null || theme === undefined) { theme = 'light'; } document.body.className = theme; document.querySelector('html').className = theme + ' js'; </script> <!-- Hide / unhide sidebar before it is displayed --> <script type="text/javascript"> var html = document.querySelector('html'); var sidebar = 'hidden'; if (document.body.clientWidth >= 1080) { try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { } sidebar = sidebar || 'visible'; } html.classList.remove('sidebar-visible'); html.classList.add("sidebar-" + sidebar); </script> <nav id="sidebar" class="sidebar" aria-label="Table of contents"> <ol class="chapter"><li class="affix"><a href="introduction.html">Introduction</a></li><li><a href="notation.html"><strong aria-hidden="true">1.</strong> Notation</a></li><li><a href="lexical-structure.html"><strong aria-hidden="true">2.</strong> Lexical structure</a></li><li><ol class="section"><li><a href="input-format.html"><strong aria-hidden="true">2.1.</strong> Input format</a></li><li><a href="keywords.html"><strong aria-hidden="true">2.2.</strong> Keywords</a></li><li><a href="identifiers.html"><strong aria-hidden="true">2.3.</strong> Identifiers</a></li><li><a href="comments.html"><strong aria-hidden="true">2.4.</strong> Comments</a></li><li><a href="whitespace.html"><strong aria-hidden="true">2.5.</strong> Whitespace</a></li><li><a href="tokens.html"><strong aria-hidden="true">2.6.</strong> Tokens</a></li><li><a href="paths.html"><strong aria-hidden="true">2.7.</strong> Paths</a></li></ol></li><li><a href="macros.html"><strong aria-hidden="true">3.</strong> Macros</a></li><li><ol class="section"><li><a href="macros-by-example.html"><strong aria-hidden="true">3.1.</strong> Macros By Example</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">3.2.</strong> Procedural Macros</a></li></ol></li><li><a href="crates-and-source-files.html"><strong aria-hidden="true">4.</strong> Crates and source files</a></li><li><a href="items-and-attributes.html"><strong aria-hidden="true">5.</strong> Items and attributes</a></li><li><ol class="section"><li><a href="items.html"><strong aria-hidden="true">5.1.</strong> Items</a></li><li><ol class="section"><li><a href="items/modules.html"><strong aria-hidden="true">5.1.1.</strong> Modules</a></li><li><a href="items/extern-crates.html"><strong aria-hidden="true">5.1.2.</strong> Extern crates</a></li><li><a href="items/use-declarations.html"><strong aria-hidden="true">5.1.3.</strong> Use declarations</a></li><li><a href="items/functions.html"><strong aria-hidden="true">5.1.4.</strong> Functions</a></li><li><a href="items/type-aliases.html"><strong aria-hidden="true">5.1.5.</strong> Type aliases</a></li><li><a href="items/structs.html"><strong aria-hidden="true">5.1.6.</strong> Structs</a></li><li><a href="items/enumerations.html"><strong aria-hidden="true">5.1.7.</strong> Enumerations</a></li><li><a href="items/unions.html"><strong aria-hidden="true">5.1.8.</strong> Unions</a></li><li><a href="items/constant-items.html"><strong aria-hidden="true">5.1.9.</strong> Constant items</a></li><li><a href="items/static-items.html"><strong aria-hidden="true">5.1.10.</strong> Static items</a></li><li><a href="items/traits.html"><strong aria-hidden="true">5.1.11.</strong> Traits</a></li><li><a href="items/implementations.html"><strong aria-hidden="true">5.1.12.</strong> Implementations</a></li><li><a href="items/external-blocks.html"><strong aria-hidden="true">5.1.13.</strong> External blocks</a></li></ol></li><li><a href="items/generics.html"><strong aria-hidden="true">5.2.</strong> Type and lifetime parameters</a></li><li><a href="items/associated-items.html"><strong aria-hidden="true">5.3.</strong> Associated Items</a></li><li><a href="visibility-and-privacy.html"><strong aria-hidden="true">5.4.</strong> Visibility and Privacy</a></li><li><a href="attributes.html"><strong aria-hidden="true">5.5.</strong> Attributes</a></li></ol></li><li><a href="statements-and-expressions.html"><strong aria-hidden="true">6.</strong> Statements and expressions</a></li><li><ol class="section"><li><a href="statements.html"><strong aria-hidden="true">6.1.</strong> Statements</a></li><li><a href="expressions.html"><strong aria-hidden="true">6.2.</strong> Expressions</a></li><li><ol class="section"><li><a href="expressions/literal-expr.html"><strong aria-hidden="true">6.2.1.</strong> Literal expressions</a></li><li><a href="expressions/path-expr.html"><strong aria-hidden="true">6.2.2.</strong> Path expressions</a></li><li><a href="expressions/block-expr.html"><strong aria-hidden="true">6.2.3.</strong> Block expressions</a></li><li><a href="expressions/operator-expr.html"><strong aria-hidden="true">6.2.4.</strong> Operator expressions</a></li><li><a href="expressions/grouped-expr.html"><strong aria-hidden="true">6.2.5.</strong> Grouped expressions</a></li><li><a href="expressions/array-expr.html"><strong aria-hidden="true">6.2.6.</strong> Array and index expressions</a></li><li><a href="expressions/tuple-expr.html"><strong aria-hidden="true">6.2.7.</strong> Tuple and index expressions</a></li><li><a href="expressions/struct-expr.html"><strong aria-hidden="true">6.2.8.</strong> Struct expressions</a></li><li><a href="expressions/enum-variant-expr.html"><strong aria-hidden="true">6.2.9.</strong> Enum variant expressions</a></li><li><a href="expressions/call-expr.html"><strong aria-hidden="true">6.2.10.</strong> Call expressions</a></li><li><a href="expressions/method-call-expr.html"><strong aria-hidden="true">6.2.11.</strong> Method call expressions</a></li><li><a href="expressions/field-expr.html"><strong aria-hidden="true">6.2.12.</strong> Field access expressions</a></li><li><a href="expressions/closure-expr.html"><strong aria-hidden="true">6.2.13.</strong> Closure expressions</a></li><li><a href="expressions/loop-expr.html"><strong aria-hidden="true">6.2.14.</strong> Loop expressions</a></li><li><a href="expressions/range-expr.html"><strong aria-hidden="true">6.2.15.</strong> Range expressions</a></li><li><a href="expressions/if-expr.html"><strong aria-hidden="true">6.2.16.</strong> If and if let expressions</a></li><li><a href="expressions/match-expr.html"><strong aria-hidden="true">6.2.17.</strong> Match expressions</a></li><li><a href="expressions/return-expr.html"><strong aria-hidden="true">6.2.18.</strong> Return expressions</a></li></ol></li></ol></li><li><a href="type-system.html"><strong aria-hidden="true">7.</strong> Type system</a></li><li><ol class="section"><li><a href="types.html" class="active"><strong aria-hidden="true">7.1.</strong> Types</a></li><li><a href="dynamically-sized-types.html"><strong aria-hidden="true">7.2.</strong> Dynamically Sized Types</a></li><li><a href="type-layout.html"><strong aria-hidden="true">7.3.</strong> Type layout</a></li><li><a href="interior-mutability.html"><strong aria-hidden="true">7.4.</strong> Interior mutability</a></li><li><a href="subtyping.html"><strong aria-hidden="true">7.5.</strong> Subtyping and Variance</a></li><li><a href="trait-bounds.html"><strong aria-hidden="true">7.6.</strong> Trait and lifetime bounds</a></li><li><a href="type-coercions.html"><strong aria-hidden="true">7.7.</strong> Type coercions</a></li><li><a href="destructors.html"><strong aria-hidden="true">7.8.</strong> Destructors</a></li><li><a href="lifetime-elision.html"><strong aria-hidden="true">7.9.</strong> Lifetime elision</a></li></ol></li><li><a href="special-types-and-traits.html"><strong aria-hidden="true">8.</strong> Special types and traits</a></li><li><a href="memory-model.html"><strong aria-hidden="true">9.</strong> Memory model</a></li><li><ol class="section"><li><a href="memory-allocation-and-lifetime.html"><strong aria-hidden="true">9.1.</strong> Memory allocation and lifetime</a></li><li><a href="memory-ownership.html"><strong aria-hidden="true">9.2.</strong> Memory ownership</a></li><li><a href="variables.html"><strong aria-hidden="true">9.3.</strong> Variables</a></li></ol></li><li><a href="linkage.html"><strong aria-hidden="true">10.</strong> Linkage</a></li><li><a href="unsafety.html"><strong aria-hidden="true">11.</strong> Unsafety</a></li><li><ol class="section"><li><a href="unsafe-functions.html"><strong aria-hidden="true">11.1.</strong> Unsafe functions</a></li><li><a href="unsafe-blocks.html"><strong aria-hidden="true">11.2.</strong> Unsafe blocks</a></li><li><a href="behavior-considered-undefined.html"><strong aria-hidden="true">11.3.</strong> Behavior considered undefined</a></li><li><a href="behavior-not-considered-unsafe.html"><strong aria-hidden="true">11.4.</strong> Behavior not considered unsafe</a></li></ol></li><li><a href="influences.html">Appendix: Influences</a></li><li class="affix"><a href="undocumented.html">Appendix: As-yet-undocumented Features</a></li><li class="affix"><a href="glossary.html">Appendix: Glossary</a></li></ol> </nav> <div id="page-wrapper" class="page-wrapper"> <div class="page"> <header><p class="warning"> For now, this reference is a best-effort document. We strive for validity and completeness, but are not yet there. In the future, the docs and lang teams will work together to figure out how best to do this. Until then, this is a best-effort attempt. If you find something wrong or missing, file an <a href="https://github.com/rust-lang-nursery/reference/issues">issue</a> or send in a pull request. </p></header> <div id="menu-bar" class="menu-bar"> <div id="menu-bar-sticky-container"> <div class="left-buttons"> <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar"> <i class="fa fa-bars"></i> </button> <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list"> <i class="fa fa-paint-brush"></i> </button> <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu"> <li role="none"><button role="menuitem" class="theme" id="light">Light <span class="default">(default)</span></button></li> <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li> <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li> <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li> <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li> </ul> <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar"> <i class="fa fa-search"></i> </button> </div> <h1 class="menu-title">The Rust Reference</h1> <div class="right-buttons"> <a href="print.html" title="Print this book" aria-label="Print this book"> <i id="print-button" class="fa fa-print"></i> </a> </div> </div> </div> <div id="search-wrapper" class="hidden"> <form id="searchbar-outer" class="searchbar-outer"> <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header"> </form> <div id="searchresults-outer" class="searchresults-outer hidden"> <div id="searchresults-header" class="searchresults-header"></div> <ul id="searchresults"> </ul> </div> </div> <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM --> <script type="text/javascript"> document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible'); document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible'); Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) { link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1); }); </script> <div id="content" class="content"> <main> <a class="header" href="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 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>Some types are defined by the language, rather than as part of the standard library, these are called <em>primitive types</em>. Some of these are individual types:</p> <ul> <li>The boolean type <code>bool</code> with values <code>true</code> and <code>false</code>.</li> <li>The <a href="types.html#machine-types">machine types</a> (integer and floating-point).</li> <li>The <a href="types.html#machine-dependent-integer-types">machine-dependent integer types</a>.</li> <li>The <a href="types.html#textual-types">textual types</a> <code>char</code> and <code>str</code>.</li> <li>The [never type] <code>!</code></li> </ul> <p>There are also some primitive constructs for generic types built in to the language:</p> <ul> <li><a href="types.html#tuple-types">Tuples</a></li> <li><a href="types.html#array-and-slice-types">Arrays</a></li> <li><a href="types.html#array-and-slice-types">Slices</a></li> <li><a href="types.html#function-pointer-types">Function pointers</a></li> <li><a href="types.html#pointer-types">References</a></li> <li><a href="types.html#raw-pointers-const-and-mut">Pointers</a></li> </ul> <a class="header" href="types.html#numeric-types" id="numeric-types"><h2>Numeric types</h2></a> <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>, <code>u64</code>, and <code>u128</code> with values drawn from the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1], [0, 2^64 - 1], and [0, 2^128 - 1] respectively.</p> </li> <li> <p>The signed two's complement word types <code>i8</code>, <code>i16</code>, <code>i32</code>, <code>i64</code>, and <code>i128</code>, with values drawn from the integer intervals [-(2^7), 2^7 - 1], [-(2^15), 2^15 - 1], [-(2^31), 2^31 - 1], [-(2^63), 2^63 - 1], and [-(2^127), 2^127 - 1] respectively.</p> </li> <li> <p>The IEEE 754-2008 "binary32" and "binary64" 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> is effectively a UCS-4 / UTF-32 string.</p> <p>A value of type <code>str</code> is a Unicode string, represented as an array of 8-bit unsigned bytes holding a sequence of UTF-8 code points. Since <code>str</code> is a <a href="dynamically-sized-types.html">dynamically sized type</a>, it is not a <em>first-class</em> type, but can only be instantiated through a pointer type, such as <code>&str</code>.</p> <a class="header" href="types.html#never-type" id="never-type"><h2>Never type</h2></a> <p>The never type <code>!</code> is a type with no values, representing the result of computations that never complete. Expressions of type <code>!</code> can be coerced into any other type.</p> <a class="header" href="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<'a> = (i32, &'a str); let p: Pair<'static> = (10, "ten"); let (a, b) = p; assert_eq!(a, 10); assert_eq!(b, "ten"); assert_eq!(p.0, 10); assert_eq!(p.1, "ten"); #}</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>[T]</code>, a 'slice'</li> </ul> <p>An array has a fixed size, and can be allocated on either the stack or the heap.</p> <p>A slice is a <a href="dynamically-sized-types.html">dynamically sized type</a> representing a 'view' into an array. To use a slice type it generally has to be used behind a pointer for example as</p> <ul> <li><code>&[T]</code>, a 'shared slice', often just called a 'slice', it doesn't own the data it points to, it borrows it.</li> <li><code>&mut [T]</code>, a 'mutable slice', mutably borrows the data it points to.</li> <li><code>Box<[T]></code>, a 'boxed slice'</li> </ul> <p>Examples:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { // A stack-allocated array let array: [i32; 3] = [1, 2, 3]; // A heap-allocated array, coerced to a slice let boxed_array: Box<[i32]> = Box::new([1, 2, 3]); // A (shared) slice into an array let slice: &[i32] = &boxed_array[..]; #}</code></pre></pre> <p>All elements of arrays and slices are always initialized, and access to an array or slice is always bounds-checked in safe methods and operators.</p> <blockquote> <p>Note: The <a href="../std/vec/struct.Vec.html"><code>Vec<T></code></a> standard library type provides a heap-allocated resizable array type.</p> </blockquote> <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> <p>New instances of a <code>struct</code> can be constructed with a <a href="expressions/struct-expr.html">struct expression</a>.</p> <p>The memory layout of a <code>struct</code> is undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with the <code>#[repr(...)]</code> attribute. In either case, fields may be given in any order in a corresponding struct <em>expression</em>; the resulting <code>struct</code> value will always have the same memory layout.</p> <p>The fields of a <code>struct</code> may be qualified by <a href="visibility-and-privacy.html">visibility modifiers</a>, to allow access to data in a struct outside a module.</p> <p>A <em>tuple struct</em> type is just like a struct type, except that the fields are anonymous.</p> <p>A <em>unit-like struct</em> type is like a struct type, except that it has no fields. The one value constructed by the associated <a href="expressions/struct-expr.html">struct expression</a> is the only value that inhabits such a type.</p> <div class="footnote-definition" id="structtype"><sup class="footnote-definition-label">1</sup> <p><code>struct</code> types are analogous to <code>struct</code> types in C, the <em>record</em> types of the ML family, or the <em>struct</em> types of the Lisp family.</p> </div> <a class="header" href="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/enumerations.html"><code>enum</code> item</a>. <sup class="footnote-reference"><a href="types.html#enumtype">2</a></sup></p> <p>An <a href="items/enumerations.html"><code>enum</code> item</a> declares both the type and a number of <em>variants</em>, each of which is independently named and has the syntax of a struct, tuple struct or unit-like struct.</p> <p>New instances of an <code>enum</code> can be constructed in an <a href="expressions/enum-variant-expr.html">enumeration variant expression</a>.</p> <p>Any <code>enum</code> value consumes as much memory as the largest variant for its corresponding <code>enum</code> type, as well as the size needed to store a discriminant.</p> <p>Enum types cannot be denoted <em>structurally</em> as types, but must be denoted by named reference to an <a href="items/enumerations.html"><code>enum</code> item</a>.</p> <div class="footnote-definition" id="enumtype"><sup class="footnote-definition-label">2</sup> <p>The <code>enum</code> type is analogous to a <code>data</code> constructor declaration in ML, or a <em>pick ADT</em> in Limbo.</p> </div> <a class="header" href="types.html#union-types" id="union-types"><h2>Union types</h2></a> <p>A <em>union type</em> is a nominal, heterogeneous C-like union, denoted by the name of a <a href="items/unions.html"><code>union</code> item</a>.</p> <p>A union contains the value of any one of its fields. Since the accessing the wrong field can cause unexpected or undefined behaviour, <code>unsafe</code> is required to read from a union field or to write to a field that doesn't implement <a href="special-types-and-traits.html#copy"><code>Copy</code></a>.</p> <p>The memory layout of a <code>union</code> is undefined by default, but the <code>#[repr(...)]</code> attribute can be used to fix a layout.</p> <a class="header" href="types.html#recursive-types" id="recursive-types"><h2>Recursive types</h2></a> <p>Nominal types — <a href="types.html#struct-types">structs</a>, <a href="types.html#enumerated-types">enumerations</a> and <a href="types.html#union-types">unions</a> — may be recursive. That is, each <code>enum</code> variant or <code>struct</code> or <code>union</code> field may refer, directly or indirectly, to the enclosing <code>enum</code> or <code>struct</code> type itself. Such recursion has restrictions:</p> <ul> <li>Recursive types must include a nominal type in the recursion (not mere <a href="../grammar.html#type-definitions">type definitions</a>, or other structural types such as <a href="types.html#array-and-slice-types">arrays</a> or <a href="types.html#tuple-types">tuples</a>). So <code>type Rec = &'static [Rec]</code> is not allowed.</li> <li>The size of a recursive type must be finite; in other words the recursive fields of the type must be <a href="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<T> { Nil, Cons(T, Box<List<T>>) } let a: List<i32> = 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 moved or copied, stored into data structs, and returned from functions.</p> <a class="header" href="types.html#shared-references-" id="shared-references-"><h3>Shared references (<code>&</code>)</h3></a> <p>These point to memory <em>owned by some other value</em>. When a shared reference to a value is created it prevents direct mutation of the value. <a href="interior-mutability.html">Interior mutability</a> provides an exception for this in certain circumstances. As the name suggests, any number of shared references to a value may exit. A shared reference type is written <code>&type</code>, or <code>&'a type</code> when you need to specify an explicit lifetime. Copying a reference is a "shallow" operation: it involves only copying the pointer itself, that is, pointers are <code>Copy</code>. Releasing a reference has no effect on the value it points to, but referencing of a <a href="expressions.html#temporary-lifetimes">temporary value</a> will keep it alive during the scope of the reference itself.</p> <a class="header" href="types.html#mutable-references-mut" id="mutable-references-mut"><h3>Mutable references (<code>&mut</code>)</h3></a> <p>These also point to memory owned by some other value. A mutable reference type is written <code>&mut type</code> or <code>&'a mut type</code>. A mutable reference (that hasn't been borrowed) is the only way to access the value it points to, so is not <code>Copy</code>.</p> <a class="header" href="types.html#raw-pointers-const-and-mut" id="raw-pointers-const-and-mut"><h3>Raw pointers (<code>*const</code> and <code>*mut</code>)</h3></a> <p>Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written as <code>*const T</code> or <code>*mut T</code>, for example <code>*const i32</code> means a raw pointer to a 32-bit integer. Copying or dropping a raw pointer has no effect on the lifecycle of any other value. Dereferencing a raw pointer is an <a href="unsafe-functions.html"><code>unsafe</code> operation</a>, this can also be used to convert a raw pointer to a reference by reborrowing it (<code>&*</code> or <code>&mut *</code>). Raw pointers are generally discouraged in Rust code; they exist to support interoperability with foreign code, and writing performance-critical or low-level functions.</p> <p>When comparing pointers they are compared by their address, rather than by what they point to. When comparing pointers to <a href="dynamically-sized-types.html">dynamically sized types</a> they also have their addition data compared.</p> <a class="header" href="types.html#smart-pointers" id="smart-pointers"><h3>Smart Pointers</h3></a> <p>The standard library contains additional 'smart pointer' types beyond references and raw pointers.</p> <a class="header" href="types.html#function-item-types" id="function-item-types"><h2>Function item types</h2></a> <p>When referred to, a function item, or the constructor of a tuple-like struct or enum variant, yields a zero-sized value of its <em>function item type</em>. That type explicitly identifies the function - its name, its type arguments, and its early-bound lifetime arguments (but not its late-bound lifetime arguments, which are only assigned when the function is called) - so the value does not need to contain an actual function pointer, and no indirection is needed when the function is called.</p> <p>There is no syntax that directly refers to a function item type, but the compiler will display the type as something like <code>fn(u32) -> i32 {fn_name}</code> in error messages.</p> <p>Because the function item type explicitly identifies the function, the item types of different functions - different items, or the same item with different generics - are distinct, and mixing them will create a type error:</p> <pre><pre class="playpen"><code class="language-rust compile_fail E0308"> # #![allow(unused_variables)] #fn main() { fn foo<T>() { } let x = &mut foo::<i32>; *x = foo::<u32>; //~ ERROR mismatched types #}</code></pre></pre> <p>However, there is a <a href="type-coercions.html">coercion</a> from function items to <a href="types.html#function-pointer-types">function pointers</a> with the same signature, which is triggered not only when a function item is used when a function pointer is directly expected, but also when different function item types with the same signature meet in different arms of the same <code>if</code> or <code>match</code>:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { # let want_i32 = false; # fn foo<T>() { } // `foo_ptr_1` has function pointer type `fn()` here let foo_ptr_1: fn() = foo::<i32>; // ... and so does `foo_ptr_2` - this type-checks. let foo_ptr_2 = if want_i32 { foo::<i32> } else { foo::<u32> }; #}</code></pre></pre> <p>All function items implement <a href="../std/ops/trait.Fn.html"><code>Fn</code></a>, <a href="../std/ops/trait.FnMut.html"><code>FnMut</code></a>, <a href="../std/ops/trait.FnOnce.html"><code>FnOnce</code></a>, <a href="special-types-and-traits.html#copy"><code>Copy</code></a>, [<code>Clone]</code>, <a href="special-types-and-traits.html#send"><code>Send</code></a>, and <a href="special-types-and-traits.html#sync"><code>Sync</code></a>.</p> <a class="header" href="types.html#function-pointer-types" id="function-pointer-types"><h2>Function pointer types</h2></a> <p>Function pointer types, written using the <code>fn</code> keyword, refer to a function whose identity is not necessarily known at compile-time. They can be created via a coercion from both <a href="types.html#function-item-types">function items</a> and non-capturing <a href="types.html#closure-types">closures</a>.</p> <p>A function pointer type consists of a possibly-empty set of function-type modifiers (such as <code>unsafe</code> or <code>extern</code>), a sequence of input types and an output type.</p> <p>An example where <code>Binop</code> is defined as a function pointer type:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { fn add(x: i32, y: i32) -> i32 { x + y } let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); #}</code></pre></pre> <a class="header" href="types.html#closure-types" id="closure-types"><h2>Closure types</h2></a> <p>A <a href="expressions/closure-expr.html">closure expression</a> produces a closure value with a unique, anonymous type that cannot be written out. A closure type is approximately equivalent to a struct which contains the captured variables. For instance, the following closure:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { fn f<F : FnOnce() -> String> (g: F) { println!("{}", g()); } let mut s = String::from("foo"); let t = String::from("bar"); f(|| { s += &*t; s }); // Prints "foobar". #}</code></pre></pre> <p>generates a closure type roughly like the following:</p> <pre><code class="language-rust ignore">struct Closure<'a> { s : String, t : &'a String, } impl<'a> (FnOnce() -> String) for Closure<'a> { fn call_once(self) -> String { self.s += &*self.t; self.s } } </code></pre> <p>so that the call to <code>f</code> works as if it were:</p> <pre><code class="language-rust ignore">f(Closure{s: s, t: &t}); </code></pre> <p>The compiler prefers to capture a closed-over variable by immutable borrow, followed by unique immutable borrow (see below), by mutable borrow, and finally by move. It will pick the first choice of these that allows the closure to compile. The choice is made only with regards to the contents of the closure expression; the compiler does not take into account surrounding code, such as the lifetimes of involved variables.</p> <p>If the <code>move</code> keyword is used, then all captures are by move or, for <code>Copy</code> types, by copy, regardless of whether a borrow would work. The <code>move</code> keyword is usually used to allow the closure to outlive the captured values, such as if the closure is being returned or used to spawn a new thread.</p> <p>Composite types such as structs, tuples, and enums are always captured entirely, not by individual fields. It may be necessary to borrow into a local variable in order to capture a single field:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { # use std::collections::HashSet; # struct SetVec { set: HashSet<u32>, vec: Vec<u32> } impl SetVec { fn populate(&mut self) { let vec = &mut self.vec; self.set.iter().for_each(|&n| { vec.push(n); }) } } #}</code></pre></pre> <p>If, instead, the closure were to use <code>self.vec</code> directly, then it would attempt to capture <code>self</code> by mutable reference. But since <code>self.set</code> is already borrowed to iterate over, the code would not compile.</p> <a class="header" href="types.html#unique-immutable-borrows-in-captures" id="unique-immutable-borrows-in-captures"><h3>Unique immutable borrows in captures</h3></a> <p>Captures can occur by a special kind of borrow called a <em>unique immutable borrow</em>, which cannot be used anywhere else in the language and cannot be written out explicitly. It occurs when modifying the referent of a mutable reference, as in the following example:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { let mut b = false; let x = &mut b; { let mut c = || { *x = true; }; // The following line is an error: // let y = &x; c(); } let z = &x; #}</code></pre></pre> <p>In this case, borrowing <code>x</code> mutably is not possible, because <code>x</code> is not <code>mut</code>. But at the same time, borrowing <code>x</code> immutably would make the assignment illegal, because a <code>& &mut</code> reference may not be unique, so it cannot safely be used to modify a value. So a unique immutable borrow is used: it borrows <code>x</code> immutably, but like a mutable borrow, it must be unique. In the above example, uncommenting the declaration of <code>y</code> will produce an error because it would violate the uniqueness of the closure's borrow of <code>x</code>; the declaration of z is valid because the closure's lifetime has expired at the end of the block, releasing the borrow.</p> <a class="header" href="types.html#call-traits-and-coercions" id="call-traits-and-coercions"><h3>Call traits and coercions</h3></a> <p>Closure types all implement <a href="../std/ops/trait.FnOnce.html"><code>FnOnce</code></a>, indicating that they can be called once by consuming ownership of the closure. Additionally, some closures implement more specific call traits:</p> <ul> <li> <p>A closure which does not move out of any captured variables implements <a href="../std/ops/trait.FnMut.html"><code>FnMut</code></a>, indicating that it can be called by mutable reference.</p> </li> <li> <p>A closure which does not mutate or move out of any captured variables implements <a href="../std/ops/trait.Fn.html"><code>Fn</code></a>, indicating that it can be called by shared reference.</p> </li> </ul> <blockquote> <p>Note: <code>move</code> closures may still implement <a href="../std/ops/trait.Fn.html"><code>Fn</code></a> or <a href="../std/ops/trait.FnMut.html"><code>FnMut</code></a>, even though they capture variables by move. This is because the traits implemented by a closure type are determined by what the closure does with captured values, not how it captures them.</p> </blockquote> <p><em>Non-capturing closures</em> are closures that don't capture anything from their environment. They can be coerced to function pointers (<code>fn</code>) with the matching signature.</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { let add = |x, y| x + y; let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); #}</code></pre></pre> <a class="header" href="types.html#other-traits" id="other-traits"><h3>Other traits</h3></a> <p>All closure types implement <a href="special-types-and-traits.html#sized"><code>Sized</code></a>. Additionally, closure types implement the following traits if allowed to do so by the types of the captures it stores:</p> <ul> <li><a href="special-types-and-traits.html#clone"><code>Clone</code></a></li> <li><a href="special-types-and-traits.html#copy"><code>Copy</code></a></li> <li><a href="special-types-and-traits.html#sync"><code>Sync</code></a></li> <li><a href="special-types-and-traits.html#send"><code>Send</code></a></li> </ul> <p>The rules for <a href="special-types-and-traits.html#send"><code>Send</code></a> and <a href="special-types-and-traits.html#sync"><code>Sync</code></a> match those for normal struct types, while <a href="special-types-and-traits.html#clone"><code>Clone</code></a> and <a href="special-types-and-traits.html#copy"><code>Copy</code></a> behave as if <a href="attributes.html#derive">derived</a>. For <a href="special-types-and-traits.html#clone"><code>Clone</code></a>, the order of cloning of the captured variables is left unspecified.</p> <p>Because captures are often by reference, the following general rules arise:</p> <ul> <li>A closure is <a href="special-types-and-traits.html#sync"><code>Sync</code></a> if all captured variables are <a href="special-types-and-traits.html#sync"><code>Sync</code></a>.</li> <li>A closure is <a href="special-types-and-traits.html#send"><code>Send</code></a> if all variables captured by non-unique immutable reference are <a href="special-types-and-traits.html#sync"><code>Sync</code></a>, and all values captured by unique immutable or mutable reference, copy, or move are <a href="special-types-and-traits.html#send"><code>Send</code></a>.</li> <li>A closure is <a href="special-types-and-traits.html#clone"><code>Clone</code></a> or <a href="special-types-and-traits.html#copy"><code>Copy</code></a> if it does not capture any values by unique immutable or mutable reference, and if all values it captures by copy or move are <a href="special-types-and-traits.html#clone"><code>Clone</code></a> or <a href="special-types-and-traits.html#copy"><code>Copy</code></a>, respectively.</li> </ul> <a class="header" href="types.html#trait-objects" id="trait-objects"><h2>Trait objects</h2></a> <blockquote> <p><strong><sup>Syntax</sup></strong> <em>TraitObjectType</em> : <code>dyn</code><sup>?</sup> <em>TypeParamBounds</em></p> </blockquote> <p>A <em>trait object</em> is an opaque value of another type that implements a set of traits. The set of traits is made up of an <a href="items/traits.html#object-safety">object safe</a> <em>base trait</em> plus any number of <a href="special-types-and-traits.html#auto-traits">auto traits</a>.</p> <p>Trait objects implement the base trait, its auto traits, and any <a href="items/traits.html#supertraits">supertraits</a> of the base trait.</p> <p>Trait objects are written as the optional keyword <code>dyn</code> followed by a set of trait bounds, but with the following restrictions on the trait bounds. All traits except the first trait must be auto traits, there may not be more than one lifetime, and opt-out bounds (e.g. <code>?sized</code>) are not allowed. Furthermore, paths to traits may be parenthesized.</p> <p>For example, given a trait <code>Trait</code>, the following are all trait objects:</p> <ul> <li><code>Trait</code></li> <li><code>dyn Trait</code></li> <li><code>dyn Trait + Send</code></li> <li><code>dyn Trait + Send + Sync</code></li> <li><code>dyn Trait + 'static</code></li> <li><code>dyn Trait + Send + 'static</code></li> <li><code>dyn Trait +</code></li> <li><code>dyn 'static + Trait</code>.</li> <li><code>dyn (Trait)</code></li> </ul> <p>If the first bound of the trait object is a path that starts with <code>::</code>, then the <code>dyn</code> will be treated as a part of the path. The first path can be put in parenthesis to get around this. As such, if you want a trait object with the trait <code>::your_module::Trait</code>, you should write it as <code>dyn (::your_module::Trait)</code>.</p> <blockquote> <p>Note: For clarity, it is recommended to always use the <code>dyn</code> keyword on your trait objects unless your codebase supports compiling with Rust 1.26 or lower.</p> </blockquote> <p>Two trait object types alias each other if the base traits alias each other and if the sets of auto traits are the same and the lifetime bounds are the same. For example, <code>dyn Trait + Send + UnwindSafe</code> is the same as <code>dyn Trait + Unwindsafe + Send</code>.</p> <blockquote> <p>Warning: With two trait object types, even when the complete set of traits is the same, if the base traits differ, the type is different. For example, <code>dyn Send + Sync</code> is a different type from <code>dyn Sync + Send</code>. See <a href="https://github.com/rust-lang/rust/issues/33140">issue 33140</a>.</p> </blockquote> <p>Due to the opaqueness of which concrete type the value is of, trait objects are <a href="dynamically-sized-types.html">dynamically sized types</a>. Like all <abbr title="dynamically sized types">DSTs</abbr>, trait objects are used behind some type of pointer; for example <code>&dyn SomeTrait</code> or <code>Box<dyn SomeTrait></code>. Each instance of a pointer to a trait object includes:</p> <ul> <li>a pointer to an instance of a type <code>T</code> that implements <code>SomeTrait</code></li> <li>a <em>virtual method table</em>, often just called a <em>vtable</em>, which contains, for each method of <code>SomeTrait</code> and its <a href="items/traits.html#supertraits">supertraits</a> that <code>T</code> implements, a pointer to <code>T</code>'s implementation (i.e. a function pointer).</li> </ul> <p>The purpose of trait objects is to permit "late binding" of methods. Calling a method on a trait object results in virtual dispatch at runtime: that is, a function pointer is loaded from the trait object vtable and invoked indirectly. The actual implementation for each vtable entry can vary on an object-by-object basis.</p> <p>An example of a trait object:</p> <pre><pre class="playpen"><code class="language-rust">trait Printable { fn stringify(&self) -> String; } impl Printable for i32 { fn stringify(&self) -> String { self.to_string() } } fn print(a: Box<dyn Printable>) { println!("{}", a.stringify()); } fn main() { print(Box::new(10) as Box<dyn Printable>); } </code></pre></pre> <p>In this example, the trait <code>Printable</code> occurs as a trait object in both the type signature of <code>print</code>, and the cast expression in <code>main</code>.</p> <a class="header" href="types.html#trait-object-lifetime-bounds" id="trait-object-lifetime-bounds"><h3>Trait Object Lifetime Bounds</h3></a> <p>Since a trait object can contain references, the lifetimes of those references need to be expressed as part of the trait object. This lifetime is written as <code>Trait + 'a</code>. There are <a href="lifetime-elision.html#default-trait-object-lifetimes">defaults</a> that allow this lifetime to usually be inferred with a sensible choice.</p> <a class="header" href="types.html#type-parameters" id="type-parameters"><h2>Type parameters</h2></a> <p>Within the body of an item that has type parameter declarations, the names of its type parameters are types:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { fn to_vec<A: Clone>(xs: &[A]) -> Vec<A> { if xs.is_empty() { return vec![]; } let first: A = xs[0].clone(); let mut rest: Vec<A> = to_vec(&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<A></code>, a vector with element type <code>A</code>.</p> <a class="header" href="types.html#anonymous-type-parameters" id="anonymous-type-parameters"><h2>Anonymous type parameters</h2></a> <blockquote> <p>Note: This section is a placeholder for more comprehensive reference material.</p> </blockquote> <blockquote> <p>Note: This is often called "impl Trait in argument position".</p> </blockquote> <p>Functions can declare an argument to be an anonymous type parameter where the callee must provide a type that has the bounds declared by the anonymous type parameter and the function can only use the methods available by the trait bounds of the anonymous type parameter.</p> <p>They are written as <code>impl</code> followed by a set of trait bounds.</p> <a class="header" href="types.html#abstract-return-types" id="abstract-return-types"><h2>Abstract return types</h2></a> <blockquote> <p>Note: This section is a placeholder for more comprehensive reference material.</p> </blockquote> <blockquote> <p>Note: This is often called "impl Trait in return position".</p> </blockquote> <p>Functions, except for associated trait functions, can return an abstract return type. These types stand in for another concrete type where the use-site may only use the trait methods declared by the trait bounds of the type.</p> <p>They are written as <code>impl</code> followed by a set of trait bounds.</p> <a class="header" href="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 implementations: it refers to the implementing type. For example, in:</p> <pre><pre class="playpen"><code class="language-rust"> # #![allow(unused_variables)] #fn main() { pub trait From<T> { fn from(T) -> Self; } impl From<i32> for String { fn from(x: i32) -> 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(&self) -> String; } impl Printable for String { fn make_string(&self) -> String { (*self).clone() } } #}</code></pre></pre> <blockquote> <p>Note: The notation <code>&self</code> is a shorthand for <code>self: &Self</code>.</p> </blockquote> </main> <nav class="nav-wrapper" aria-label="Page navigation"> <!-- Mobile navigation buttons --> <a rel="prev" href="type-system.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> <i class="fa fa-angle-left"></i> </a> <a rel="next" href="dynamically-sized-types.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> <i class="fa fa-angle-right"></i> </a> <div style="clear: both"></div> </nav> </div> </div> <nav class="nav-wide-wrapper" aria-label="Page navigation"> <a href="type-system.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left"> <i class="fa fa-angle-left"></i> </a> <a href="dynamically-sized-types.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right"> <i class="fa fa-angle-right"></i> </a> </nav> </div> <script src="searchindex.js" type="text/javascript" charset="utf-8"></script> <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script> <script src="mark.min.js" type="text/javascript" charset="utf-8"></script> <script src="searcher.js" type="text/javascript" charset="utf-8"></script> <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script> <script src="highlight.js" type="text/javascript" charset="utf-8"></script> <script src="book.js" type="text/javascript" charset="utf-8"></script> <!-- Custom JS scripts --> </body> </html>