]> git.lizzy.rs Git - rust.git/blob - src/doc/reference.md
Auto merge of #28396 - arielb1:misplaced-binding, r=eddyb
[rust.git] / src / doc / reference.md
1 % The Rust Reference
2
3 # Introduction
4
5 This document is the primary reference for the Rust programming language. It
6 provides three kinds of material:
7
8   - Chapters that informally describe each language construct and their use.
9   - Chapters that informally describe the memory model, concurrency model,
10     runtime services, linkage model and debugging facilities.
11   - Appendix chapters providing rationale and references to languages that
12     influenced the design.
13
14 This document does not serve as an introduction to the language. Background
15 familiarity with the language is assumed. A separate [book] is available to
16 help acquire such background familiarity.
17
18 This document also does not serve as a reference to the [standard] library
19 included in the language distribution. Those libraries are documented
20 separately by extracting documentation attributes from their source code. Many
21 of the features that one might expect to be language features are library
22 features in Rust, so what you're looking for may be there, not here.
23
24 You may also be interested in the [grammar].
25
26 [book]: book/index.html
27 [standard]: std/index.html
28 [grammar]: grammar.html
29
30 # Notation
31
32 ## Unicode productions
33
34 A few productions in Rust's grammar permit Unicode code points outside the
35 ASCII range. We define these productions in terms of character properties
36 specified in the Unicode standard, rather than in terms of ASCII-range code
37 points. The grammar has a [Special Unicode Productions][unicodeproductions]
38 section that lists these productions.
39
40 [unicodeproductions]: grammar.html#special-unicode-productions
41
42 ## String table productions
43
44 Some rules in the grammar — notably [unary
45 operators](#unary-operator-expressions), [binary
46 operators](#binary-operator-expressions), and [keywords][keywords] — are
47 given in a simplified form: as a listing of a table of unquoted, printable
48 whitespace-separated strings. These cases form a subset of the rules regarding
49 the [token](#tokens) rule, and are assumed to be the result of a
50 lexical-analysis phase feeding the parser, driven by a DFA, operating over the
51 disjunction of all such string table entries.
52
53 [keywords]: grammar.html#keywords
54
55 When such a string enclosed in double-quotes (`"`) occurs inside the grammar,
56 it is an implicit reference to a single member of such a string table
57 production. See [tokens](#tokens) for more information.
58
59 # Lexical structure
60
61 ## Input format
62
63 Rust input is interpreted as a sequence of Unicode code points encoded in UTF-8.
64 Most Rust grammar rules are defined in terms of printable ASCII-range
65 code points, but a small number are defined in terms of Unicode properties or
66 explicit code point lists. [^inputformat]
67
68 [^inputformat]: Substitute definitions for the special Unicode productions are
69   provided to the grammar verifier, restricted to ASCII range, when verifying the
70   grammar in this document.
71
72 ## Identifiers
73
74 An identifier is any nonempty Unicode[^non_ascii_idents] string of the following form:
75
76 [^non_ascii_idents]: Non-ASCII characters in identifiers are currently feature
77   gated. This is expected to improve soon.
78
79 - The first character has property `XID_start`
80 - The remaining characters have property `XID_continue`
81
82 that does _not_ occur in the set of [keywords][keywords].
83
84 > **Note**: `XID_start` and `XID_continue` as character properties cover the
85 > character ranges used to form the more familiar C and Java language-family
86 > identifiers.
87
88 ## Comments
89
90 Comments in Rust code follow the general C++ style of line (`//`) and
91 block (`/* ... */`) comment forms. Nested block comments are supported.
92
93 Line comments beginning with exactly _three_ slashes (`///`), and block
94 comments beginning with exactly one repeated asterisk in the block-open
95 sequence (`/**`), are interpreted as a special syntax for `doc`
96 [attributes](#attributes). That is, they are equivalent to writing
97 `#[doc="..."]` around the body of the comment, i.e., `/// Foo` turns into
98 `#[doc="Foo"]`.
99
100 Line comments beginning with `//!` and block comments beginning with `/*!` are
101 doc comments that apply to the parent of the comment, rather than the item
102 that follows.  That is, they are equivalent to writing `#![doc="..."]` around
103 the body of the comment. `//!` comments are usually used to document
104 modules that occupy a source file.
105
106 Non-doc comments are interpreted as a form of whitespace.
107
108 ## Whitespace
109
110 Whitespace is any non-empty string containing only the following characters:
111
112 - `U+0020` (space, `' '`)
113 - `U+0009` (tab, `'\t'`)
114 - `U+000A` (LF, `'\n'`)
115 - `U+000D` (CR, `'\r'`)
116
117 Rust is a "free-form" language, meaning that all forms of whitespace serve only
118 to separate _tokens_ in the grammar, and have no semantic significance.
119
120 A Rust program has identical meaning if each whitespace element is replaced
121 with any other legal whitespace element, such as a single space character.
122
123 ## Tokens
124
125 Tokens are primitive productions in the grammar defined by regular
126 (non-recursive) languages. "Simple" tokens are given in [string table
127 production](#string-table-productions) form, and occur in the rest of the
128 grammar as double-quoted strings. Other tokens have exact rules given.
129
130 ### Literals
131
132 A literal is an expression consisting of a single token, rather than a sequence
133 of tokens, that immediately and directly denotes the value it evaluates to,
134 rather than referring to it by name or some other evaluation rule. A literal is
135 a form of constant expression, so is evaluated (primarily) at compile time.
136
137 #### Examples
138
139 ##### Characters and strings
140
141 |                                              | Example         | `#` sets   | Characters  | Escapes             |
142 |----------------------------------------------|-----------------|------------|-------------|---------------------|
143 | [Character](#character-literals)             | `'H'`           | `N/A`      | All Unicode | `\'` & [Byte](#byte-escapes) & [Unicode](#unicode-escapes) |
144 | [String](#string-literals)                   | `"hello"`       | `N/A`      | All Unicode | `\"` & [Byte](#byte-escapes) & [Unicode](#unicode-escapes) |
145 | [Raw](#raw-string-literals)                  | `r#"hello"#`    | `0...`     | All Unicode | `N/A`                                                      |
146 | [Byte](#byte-literals)                       | `b'H'`          | `N/A`      | All ASCII   | `\'` & [Byte](#byte-escapes)                               |
147 | [Byte string](#byte-string-literals)         | `b"hello"`      | `N/A`      | All ASCII   | `\"` & [Byte](#byte-escapes)                               |
148 | [Raw byte string](#raw-byte-string-literals) | `br#"hello"#`   | `0...`     | All ASCII   | `N/A`                                                      |
149
150 ##### Byte escapes
151
152 |   | Name |
153 |---|------|
154 | `\x7F` | 8-bit character code (exactly 2 digits) |
155 | `\n` | Newline |
156 | `\r` | Carriage return |
157 | `\t` | Tab |
158 | `\\` | Backslash |
159
160 ##### Unicode escapes
161 |   | Name |
162 |---|------|
163 | `\u{7FFF}` | 24-bit Unicode character code (up to 6 digits) |
164
165 ##### Numbers
166
167 | [Number literals](#number-literals)`*` | Example | Exponentiation | Suffixes |
168 |----------------------------------------|---------|----------------|----------|
169 | Decimal integer | `98_222` | `N/A` | Integer suffixes |
170 | Hex integer | `0xff` | `N/A` | Integer suffixes |
171 | Octal integer | `0o77` | `N/A` | Integer suffixes |
172 | Binary integer | `0b1111_0000` | `N/A` | Integer suffixes |
173 | Floating-point | `123.0E+77` | `Optional` | Floating-point suffixes |
174
175 `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64`
176
177 ##### Suffixes
178 | Integer | Floating-point |
179 |---------|----------------|
180 | `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `isize`, `usize` | `f32`, `f64` |
181
182 #### Character and string literals
183
184 ##### Character literals
185
186 A _character literal_ is a single Unicode character enclosed within two
187 `U+0027` (single-quote) characters, with the exception of `U+0027` itself,
188 which must be _escaped_ by a preceding `U+005C` character (`\`).
189
190 ##### String literals
191
192 A _string literal_ is a sequence of any Unicode characters enclosed within two
193 `U+0022` (double-quote) characters, with the exception of `U+0022` itself,
194 which must be _escaped_ by a preceding `U+005C` character (`\`).
195
196 Line-break characters are allowed in string literals. Normally they represent
197 themselves (i.e. no translation), but as a special exception, when a `U+005C`
198 character (`\`) occurs immediately before the newline, the `U+005C` character,
199 the newline, and all whitespace at the beginning of the next line are ignored.
200 Thus `a` and `b` are equal:
201
202 ```rust
203 let a = "foobar";
204 let b = "foo\
205          bar";
206
207 assert_eq!(a,b);
208 ```
209
210 ##### Character escapes
211
212 Some additional _escapes_ are available in either character or non-raw string
213 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
214 following forms:
215
216 * An _8-bit code point escape_ starts with `U+0078` (`x`) and is
217   followed by exactly two _hex digits_. It denotes the Unicode code point
218   equal to the provided hex value.
219 * A _24-bit code point escape_ starts with `U+0075` (`u`) and is followed
220   by up to six _hex digits_ surrounded by braces `U+007B` (`{`) and `U+007D`
221   (`}`). It denotes the Unicode code point equal to the provided hex value.
222 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
223   (`r`), or `U+0074` (`t`), denoting the Unicode values `U+000A` (LF),
224   `U+000D` (CR) or `U+0009` (HT) respectively.
225 * The _backslash escape_ is the character `U+005C` (`\`) which must be
226   escaped in order to denote *itself*.
227
228 ##### Raw string literals
229
230 Raw string literals do not process any escapes. They start with the character
231 `U+0072` (`r`), followed by zero or more of the character `U+0023` (`#`) and a
232 `U+0022` (double-quote) character. The _raw string body_ can contain any sequence
233 of Unicode characters and is terminated only by another `U+0022` (double-quote)
234 character, followed by the same number of `U+0023` (`#`) characters that preceded
235 the opening `U+0022` (double-quote) character.
236
237 All Unicode characters contained in the raw string body represent themselves,
238 the characters `U+0022` (double-quote) (except when followed by at least as
239 many `U+0023` (`#`) characters as were used to start the raw string literal) or
240 `U+005C` (`\`) do not have any special meaning.
241
242 Examples for string literals:
243
244 ```
245 "foo"; r"foo";                     // foo
246 "\"foo\""; r#""foo""#;             // "foo"
247
248 "foo #\"# bar";
249 r##"foo #"# bar"##;                // foo #"# bar
250
251 "\x52"; "R"; r"R";                 // R
252 "\\x52"; r"\x52";                  // \x52
253 ```
254
255 #### Byte and byte string literals
256
257 ##### Byte literals
258
259 A _byte literal_ is a single ASCII character (in the `U+0000` to `U+007F`
260 range) or a single _escape_ preceded by the characters `U+0062` (`b`) and
261 `U+0027` (single-quote), and followed by the character `U+0027`. If the character
262 `U+0027` is present within the literal, it must be _escaped_ by a preceding
263 `U+005C` (`\`) character. It is equivalent to a `u8` unsigned 8-bit integer
264 _number literal_.
265
266 ##### Byte string literals
267
268 A non-raw _byte string literal_ is a sequence of ASCII characters and _escapes_,
269 preceded by the characters `U+0062` (`b`) and `U+0022` (double-quote), and
270 followed by the character `U+0022`. If the character `U+0022` is present within
271 the literal, it must be _escaped_ by a preceding `U+005C` (`\`) character.
272 Alternatively, a byte string literal can be a _raw byte string literal_, defined
273 below. A byte string literal of length `n` is equivalent to a `&'static [u8; n]` borrowed fixed-sized array
274 of unsigned 8-bit integers.
275
276 Some additional _escapes_ are available in either byte or non-raw byte string
277 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
278 following forms:
279
280 * A _byte escape_ escape starts with `U+0078` (`x`) and is
281   followed by exactly two _hex digits_. It denotes the byte
282   equal to the provided hex value.
283 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
284   (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF),
285   `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.
286 * The _backslash escape_ is the character `U+005C` (`\`) which must be
287   escaped in order to denote its ASCII encoding `0x5C`.
288
289 ##### Raw byte string literals
290
291 Raw byte string literals do not process any escapes. They start with the
292 character `U+0062` (`b`), followed by `U+0072` (`r`), followed by zero or more
293 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character. The
294 _raw string body_ can contain any sequence of ASCII characters and is terminated
295 only by another `U+0022` (double-quote) character, followed by the same number of
296 `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote)
297 character. A raw byte string literal can not contain any non-ASCII byte.
298
299 All characters contained in the raw string body represent their ASCII encoding,
300 the characters `U+0022` (double-quote) (except when followed by at least as
301 many `U+0023` (`#`) characters as were used to start the raw string literal) or
302 `U+005C` (`\`) do not have any special meaning.
303
304 Examples for byte string literals:
305
306 ```
307 b"foo"; br"foo";                     // foo
308 b"\"foo\""; br#""foo""#;             // "foo"
309
310 b"foo #\"# bar";
311 br##"foo #"# bar"##;                 // foo #"# bar
312
313 b"\x52"; b"R"; br"R";                // R
314 b"\\x52"; br"\x52";                  // \x52
315 ```
316
317 #### Number literals
318
319 A _number literal_ is either an _integer literal_ or a _floating-point
320 literal_. The grammar for recognizing the two kinds of literals is mixed.
321
322 ##### Integer literals
323
324 An _integer literal_ has one of four forms:
325
326 * A _decimal literal_ starts with a *decimal digit* and continues with any
327   mixture of *decimal digits* and _underscores_.
328 * A _hex literal_ starts with the character sequence `U+0030` `U+0078`
329   (`0x`) and continues as any mixture of hex digits and underscores.
330 * An _octal literal_ starts with the character sequence `U+0030` `U+006F`
331   (`0o`) and continues as any mixture of octal digits and underscores.
332 * A _binary literal_ starts with the character sequence `U+0030` `U+0062`
333   (`0b`) and continues as any mixture of binary digits and underscores.
334
335 Like any literal, an integer literal may be followed (immediately,
336 without any spaces) by an _integer suffix_, which forcibly sets the
337 type of the literal. The integer suffix must be the name of one of the
338 integral types: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`,
339 `isize`, or `usize`.
340
341 The type of an _unsuffixed_ integer literal is determined by type inference:
342
343 * If an integer type can be _uniquely_ determined from the surrounding
344   program context, the unsuffixed integer literal has that type.
345
346 * If the program context under-constrains the type, it defaults to the
347   signed 32-bit integer `i32`.
348
349 * If the program context over-constrains the type, it is considered a
350   static type error.
351
352 Examples of integer literals of various forms:
353
354 ```
355 123i32;                            // type i32
356 123u32;                            // type u32
357 123_u32;                           // type u32
358 0xff_u8;                           // type u8
359 0o70_i16;                          // type i16
360 0b1111_1111_1001_0000_i32;         // type i32
361 0usize;                            // type usize
362 ```
363
364 ##### Floating-point literals
365
366 A _floating-point literal_ has one of two forms:
367
368 * A _decimal literal_ followed by a period character `U+002E` (`.`). This is
369   optionally followed by another decimal literal, with an optional _exponent_.
370 * A single _decimal literal_ followed by an _exponent_.
371
372 Like integer literals, a floating-point literal may be followed by a
373 suffix, so long as the pre-suffix part does not end with `U+002E` (`.`).
374 The suffix forcibly sets the type of the literal. There are two valid
375 _floating-point suffixes_, `f32` and `f64` (the 32-bit and 64-bit floating point
376 types), which explicitly determine the type of the literal.
377
378 The type of an _unsuffixed_ floating-point literal is determined by
379 type inference:
380
381 * If a floating-point type can be _uniquely_ determined from the
382   surrounding program context, the unsuffixed floating-point literal
383   has that type.
384
385 * If the program context under-constrains the type, it defaults to `f64`.
386
387 * If the program context over-constrains the type, it is considered a
388   static type error.
389
390 Examples of floating-point literals of various forms:
391
392 ```
393 123.0f64;        // type f64
394 0.1f64;          // type f64
395 0.1f32;          // type f32
396 12E+99_f64;      // type f64
397 let x: f64 = 2.; // type f64
398 ```
399
400 This last example is different because it is not possible to use the suffix
401 syntax with a floating point literal ending in a period. `2.f64` would attempt
402 to call a method named `f64` on `2`.
403
404 The representation semantics of floating-point numbers are described in
405 ["Machine Types"](#machine-types).
406
407 #### Boolean literals
408
409 The two values of the boolean type are written `true` and `false`.
410
411 ### Symbols
412
413 Symbols are a general class of printable [token](#tokens) that play structural
414 roles in a variety of grammar productions. They are catalogued here for
415 completeness as the set of remaining miscellaneous printable tokens that do not
416 otherwise appear as [unary operators](#unary-operator-expressions), [binary
417 operators](#binary-operator-expressions), or [keywords][keywords].
418
419
420 ## Paths
421
422 A _path_ is a sequence of one or more path components _logically_ separated by
423 a namespace qualifier (`::`). If a path consists of only one component, it may
424 refer to either an [item](#items) or a [variable](#variables) in a local control
425 scope. If a path has multiple components, it refers to an item.
426
427 Every item has a _canonical path_ within its crate, but the path naming an item
428 is only meaningful within a given crate. There is no global namespace across
429 crates; an item's canonical path merely identifies it within the crate.
430
431 Two examples of simple paths consisting of only identifier components:
432
433 ```{.ignore}
434 x;
435 x::y::z;
436 ```
437
438 Path components are usually [identifiers](#identifiers), but they may
439 also include angle-bracket-enclosed lists of type arguments. In
440 [expression](#expressions) context, the type argument list is given
441 after a `::` namespace qualifier in order to disambiguate it from a
442 relational expression involving the less-than symbol (`<`). In type
443 expression context, the final namespace qualifier is omitted.
444
445 Two examples of paths with type arguments:
446
447 ```
448 # struct HashMap<K, V>(K,V);
449 # fn f() {
450 # fn id<T>(t: T) -> T { t }
451 type T = HashMap<i32,String>; // Type arguments used in a type expression
452 let x  = id::<i32>(10);       // Type arguments used in a call expression
453 # }
454 ```
455
456 Paths can be denoted with various leading qualifiers to change the meaning of
457 how it is resolved:
458
459 * Paths starting with `::` are considered to be global paths where the
460   components of the path start being resolved from the crate root. Each
461   identifier in the path must resolve to an item.
462
463 ```rust
464 mod a {
465     pub fn foo() {}
466 }
467 mod b {
468     pub fn foo() {
469         ::a::foo(); // call a's foo function
470     }
471 }
472 # fn main() {}
473 ```
474
475 * Paths starting with the keyword `super` begin resolution relative to the
476   parent module. Each further identifier must resolve to an item.
477
478 ```rust
479 mod a {
480     pub fn foo() {}
481 }
482 mod b {
483     pub fn foo() {
484         super::a::foo(); // call a's foo function
485     }
486 }
487 # fn main() {}
488 ```
489
490 * Paths starting with the keyword `self` begin resolution relative to the
491   current module. Each further identifier must resolve to an item.
492
493 ```rust
494 fn foo() {}
495 fn bar() {
496     self::foo();
497 }
498 # fn main() {}
499 ```
500
501 # Syntax extensions
502
503 A number of minor features of Rust are not central enough to have their own
504 syntax, and yet are not implementable as functions. Instead, they are given
505 names, and invoked through a consistent syntax: `some_extension!(...)`.
506
507 Users of `rustc` can define new syntax extensions in two ways:
508
509 * [Compiler plugins][plugin] can include arbitrary Rust code that
510   manipulates syntax trees at compile time. Note that the interface
511   for compiler plugins is considered highly unstable.
512
513 * [Macros](book/macros.html) define new syntax in a higher-level,
514   declarative way.
515
516 ## Macros
517
518 `macro_rules` allows users to define syntax extension in a declarative way.  We
519 call such extensions "macros by example" or simply "macros" â€” to be distinguished
520 from the "procedural macros" defined in [compiler plugins][plugin].
521
522 Currently, macros can expand to expressions, statements, items, or patterns.
523
524 (A `sep_token` is any token other than `*` and `+`. A `non_special_token` is
525 any token other than a delimiter or `$`.)
526
527 The macro expander looks up macro invocations by name, and tries each macro
528 rule in turn. It transcribes the first successful match. Matching and
529 transcription are closely related to each other, and we will describe them
530 together.
531
532 ### Macro By Example
533
534 The macro expander matches and transcribes every token that does not begin with
535 a `$` literally, including delimiters. For parsing reasons, delimiters must be
536 balanced, but they are otherwise not special.
537
538 In the matcher, `$` _name_ `:` _designator_ matches the nonterminal in the Rust
539 syntax named by _designator_. Valid designators are `item`, `block`, `stmt`,
540 `pat`, `expr`, `ty` (type), `ident`, `path`, `tt` (either side of the `=>`
541 in macro rules), and `meta` (contents of an attribute). In the transcriber, the
542 designator is already known, and so only the name of a matched nonterminal comes
543 after the dollar sign.
544
545 In both the matcher and transcriber, the Kleene star-like operator indicates
546 repetition. The Kleene star operator consists of `$` and parentheses, optionally
547 followed by a separator token, followed by `*` or `+`. `*` means zero or more
548 repetitions, `+` means at least one repetition. The parentheses are not matched or
549 transcribed. On the matcher side, a name is bound to _all_ of the names it
550 matches, in a structure that mimics the structure of the repetition encountered
551 on a successful match. The job of the transcriber is to sort that structure
552 out.
553
554 The rules for transcription of these repetitions are called "Macro By Example".
555 Essentially, one "layer" of repetition is discharged at a time, and all of them
556 must be discharged by the time a name is transcribed. Therefore, `( $( $i:ident
557 ),* ) => ( $i )` is an invalid macro, but `( $( $i:ident ),* ) => ( $( $i:ident
558 ),*  )` is acceptable (if trivial).
559
560 When Macro By Example encounters a repetition, it examines all of the `$`
561 _name_ s that occur in its body. At the "current layer", they all must repeat
562 the same number of times, so ` ( $( $i:ident ),* ; $( $j:ident ),* ) => ( $(
563 ($i,$j) ),* )` is valid if given the argument `(a,b,c ; d,e,f)`, but not
564 `(a,b,c ; d,e)`. The repetition walks through the choices at that layer in
565 lockstep, so the former input transcribes to `(a,d), (b,e), (c,f)`.
566
567 Nested repetitions are allowed.
568
569 ### Parsing limitations
570
571 The parser used by the macro system is reasonably powerful, but the parsing of
572 Rust syntax is restricted in two ways:
573
574 1. Macro definitions are required to include suitable separators after parsing
575    expressions and other bits of the Rust grammar. This implies that
576    a macro definition like `$i:expr [ , ]` is not legal, because `[` could be part
577    of an expression. A macro definition like `$i:expr,` or `$i:expr;` would be legal,
578    however, because `,` and `;` are legal separators. See [RFC 550] for more information.
579 2. The parser must have eliminated all ambiguity by the time it reaches a `$`
580    _name_ `:` _designator_. This requirement most often affects name-designator
581    pairs when they occur at the beginning of, or immediately after, a `$(...)*`;
582    requiring a distinctive token in front can solve the problem.
583
584 [RFC 550]: https://github.com/rust-lang/rfcs/blob/master/text/0550-macro-future-proofing.md
585
586 # Crates and source files
587
588 Although Rust, like any other language, can be implemented by an interpreter as
589 well as a compiler, the only existing implementation is a compiler &mdash;
590 from now on referred to as *the* Rust compiler &mdash; and the language has
591 always been designed to be compiled. For these reasons, this section assumes a
592 compiler.
593
594 Rust's semantics obey a *phase distinction* between compile-time and
595 run-time.[^phase-distinction] Semantic rules that have a *static
596 interpretation* govern the success or failure of compilation, while
597 semantic rules
598 that have a *dynamic interpretation* govern the behavior of the program at
599 run-time.
600
601 [^phase-distinction]: This distinction would also exist in an interpreter.
602     Static checks like syntactic analysis, type checking, and lints should
603     happen before the program is executed regardless of when it is executed.
604
605 The compilation model centers on artifacts called _crates_. Each compilation
606 processes a single crate in source form, and if successful, produces a single
607 crate in binary form: either an executable or some sort of
608 library.[^cratesourcefile]
609
610 [^cratesourcefile]: A crate is somewhat analogous to an *assembly* in the
611     ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit*
612     in the Owens and Flatt module system, or a *configuration* in Mesa.
613
614 A _crate_ is a unit of compilation and linking, as well as versioning,
615 distribution and runtime loading. A crate contains a _tree_ of nested
616 [module](#modules) scopes. The top level of this tree is a module that is
617 anonymous (from the point of view of paths within the module) and any item
618 within a crate has a canonical [module path](#paths) denoting its location
619 within the crate's module tree.
620
621 The Rust compiler is always invoked with a single source file as input, and
622 always produces a single output crate. The processing of that source file may
623 result in other source files being loaded as modules. Source files have the
624 extension `.rs`.
625
626 A Rust source file describes a module, the name and location of which &mdash;
627 in the module tree of the current crate &mdash; are defined from outside the
628 source file: either by an explicit `mod_item` in a referencing source file, or
629 by the name of the crate itself. Every source file is a module, but not every
630 module needs its own source file: [module definitions](#modules) can be nested
631 within one file.
632
633 Each source file contains a sequence of zero or more `item` definitions, and
634 may optionally begin with any number of [attributes](#items-and-attributes)
635 that apply to the containing module, most of which influence the behavior of
636 the compiler. The anonymous crate module can have additional attributes that
637 apply to the crate as a whole.
638
639 ```no_run
640 // Specify the crate name.
641 #![crate_name = "projx"]
642
643 // Specify the type of output artifact.
644 #![crate_type = "lib"]
645
646 // Turn on a warning.
647 // This can be done in any module, not just the anonymous crate module.
648 #![warn(non_camel_case_types)]
649 ```
650
651 A crate that contains a `main` function can be compiled to an executable. If a
652 `main` function is present, its return type must be [`unit`](#tuple-types)
653 and it must take no arguments.
654
655 # Items and attributes
656
657 Crates contain [items](#items), each of which may have some number of
658 [attributes](#attributes) attached to it.
659
660 ## Items
661
662 An _item_ is a component of a crate. Items are organized within a crate by a
663 nested set of [modules](#modules). Every crate has a single "outermost"
664 anonymous module; all further items within the crate have [paths](#paths)
665 within the module tree of the crate.
666
667 Items are entirely determined at compile-time, generally remain fixed during
668 execution, and may reside in read-only memory.
669
670 There are several kinds of item:
671
672 * [`extern crate` declarations](#extern-crate-declarations)
673 * [`use` declarations](#use-declarations)
674 * [modules](#modules)
675 * [functions](#functions)
676 * [type definitions](grammar.html#type-definitions)
677 * [structures](#structures)
678 * [enumerations](#enumerations)
679 * [constant items](#constant-items)
680 * [static items](#static-items)
681 * [traits](#traits)
682 * [implementations](#implementations)
683
684 Some items form an implicit scope for the declaration of sub-items. In other
685 words, within a function or module, declarations of items can (in many cases)
686 be mixed with the statements, control blocks, and similar artifacts that
687 otherwise compose the item body. The meaning of these scoped items is the same
688 as if the item was declared outside the scope &mdash; it is still a static item
689 &mdash; except that the item's *path name* within the module namespace is
690 qualified by the name of the enclosing item, or is private to the enclosing
691 item (in the case of functions). The grammar specifies the exact locations in
692 which sub-item declarations may appear.
693
694 ### Type Parameters
695
696 All items except modules, constants and statics may be *parameterized* by type.
697 Type parameters are given as a comma-separated list of identifiers enclosed in
698 angle brackets (`<...>`), after the name of the item and before its definition.
699 The type parameters of an item are considered "part of the name", not part of
700 the type of the item. A referencing [path](#paths) must (in principle) provide
701 type arguments as a list of comma-separated types enclosed within angle
702 brackets, in order to refer to the type-parameterized item. In practice, the
703 type-inference system can usually infer such argument types from context. There
704 are no general type-parametric types, only type-parametric items. That is, Rust
705 has no notion of type abstraction: there are no higher-ranked (or "forall") types
706 abstracted over other types, though higher-ranked types do exist for lifetimes.
707
708 ### Modules
709
710 A module is a container for zero or more [items](#items).
711
712 A _module item_ is a module, surrounded in braces, named, and prefixed with the
713 keyword `mod`. A module item introduces a new, named module into the tree of
714 modules making up a crate. Modules can nest arbitrarily.
715
716 An example of a module:
717
718 ```
719 mod math {
720     type Complex = (f64, f64);
721     fn sin(f: f64) -> f64 {
722         /* ... */
723 # panic!();
724     }
725     fn cos(f: f64) -> f64 {
726         /* ... */
727 # panic!();
728     }
729     fn tan(f: f64) -> f64 {
730         /* ... */
731 # panic!();
732     }
733 }
734 ```
735
736 Modules and types share the same namespace. Declaring a named type with
737 the same name as a module in scope is forbidden: that is, a type definition,
738 trait, struct, enumeration, or type parameter can't shadow the name of a module
739 in scope, or vice versa.
740
741 A module without a body is loaded from an external file, by default with the
742 same name as the module, plus the `.rs` extension. When a nested submodule is
743 loaded from an external file, it is loaded from a subdirectory path that
744 mirrors the module hierarchy.
745
746 ```{.ignore}
747 // Load the `vec` module from `vec.rs`
748 mod vec;
749
750 mod thread {
751     // Load the `local_data` module from `thread/local_data.rs`
752     // or `thread/local_data/mod.rs`.
753     mod local_data;
754 }
755 ```
756
757 The directories and files used for loading external file modules can be
758 influenced with the `path` attribute.
759
760 ```{.ignore}
761 #[path = "thread_files"]
762 mod thread {
763     // Load the `local_data` module from `thread_files/tls.rs`
764     #[path = "tls.rs"]
765     mod local_data;
766 }
767 ```
768
769 #### Extern crate declarations
770
771 An _`extern crate` declaration_ specifies a dependency on an external crate.
772 The external crate is then bound into the declaring scope as the `ident`
773 provided in the `extern_crate_decl`.
774
775 The external crate is resolved to a specific `soname` at compile time, and a
776 runtime linkage requirement to that `soname` is passed to the linker for
777 loading at runtime. The `soname` is resolved at compile time by scanning the
778 compiler's library path and matching the optional `crateid` provided against
779 the `crateid` attributes that were declared on the external crate when it was
780 compiled. If no `crateid` is provided, a default `name` attribute is assumed,
781 equal to the `ident` given in the `extern_crate_decl`.
782
783 Three examples of `extern crate` declarations:
784
785 ```{.ignore}
786 extern crate pcre;
787
788 extern crate std; // equivalent to: extern crate std as std;
789
790 extern crate std as ruststd; // linking to 'std' under another name
791 ```
792
793 #### Use declarations
794
795 A _use declaration_ creates one or more local name bindings synonymous with
796 some other [path](#paths). Usually a `use` declaration is used to shorten the
797 path required to refer to a module item. These declarations may appear at the
798 top of [modules](#modules) and [blocks](grammar.html#block-expressions).
799
800 > **Note**: Unlike in many languages,
801 > `use` declarations in Rust do *not* declare linkage dependency with external crates.
802 > Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies.
803
804 Use declarations support a number of convenient shortcuts:
805
806 * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`
807 * Simultaneously binding a list of paths differing only in their final element,
808   using the glob-like brace syntax `use a::b::{c,d,e,f};`
809 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
810   `use a::b::*;`
811 * Simultaneously binding a list of paths differing only in their final element
812   and their immediate parent module, using the `self` keyword, such as
813   `use a::b::{self, c, d};`
814
815 An example of `use` declarations:
816
817 ```rust
818 use std::option::Option::{Some, None};
819 use std::collections::hash_map::{self, HashMap};
820
821 fn foo<T>(_: T){}
822 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
823
824 fn main() {
825     // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
826     // std::option::Option::None]);'
827     foo(vec![Some(1.0f64), None]);
828
829     // Both `hash_map` and `HashMap` are in scope.
830     let map1 = HashMap::new();
831     let map2 = hash_map::HashMap::new();
832     bar(map1, map2);
833 }
834 ```
835
836 Like items, `use` declarations are private to the containing module, by
837 default. Also like items, a `use` declaration can be public, if qualified by
838 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
839 public `use` declaration can therefore _redirect_ some public name to a
840 different target definition: even a definition with a private canonical path,
841 inside a different module. If a sequence of such redirections form a cycle or
842 cannot be resolved unambiguously, they represent a compile-time error.
843
844 An example of re-exporting:
845
846 ```
847 # fn main() { }
848 mod quux {
849     pub use quux::foo::{bar, baz};
850
851     pub mod foo {
852         pub fn bar() { }
853         pub fn baz() { }
854     }
855 }
856 ```
857
858 In this example, the module `quux` re-exports two public names defined in
859 `foo`.
860
861 Also note that the paths contained in `use` items are relative to the crate
862 root. So, in the previous example, the `use` refers to `quux::foo::{bar,
863 baz}`, and not simply to `foo::{bar, baz}`. This also means that top-level
864 module declarations should be at the crate root if direct usage of the declared
865 modules within `use` items is desired. It is also possible to use `self` and
866 `super` at the beginning of a `use` item to refer to the current and direct
867 parent modules respectively. All rules regarding accessing declared modules in
868 `use` declarations apply to both module declarations and `extern crate`
869 declarations.
870
871 An example of what will and will not work for `use` items:
872
873 ```
874 # #![allow(unused_imports)]
875 use foo::baz::foobaz;    // good: foo is at the root of the crate
876
877 mod foo {
878
879     mod example {
880         pub mod iter {}
881     }
882
883     use foo::example::iter; // good: foo is at crate root
884 //  use example::iter;      // bad:  core is not at the crate root
885     use self::baz::foobaz;  // good: self refers to module 'foo'
886     use foo::bar::foobar;   // good: foo is at crate root
887
888     pub mod bar {
889         pub fn foobar() { }
890     }
891
892     pub mod baz {
893         use super::bar::foobar; // good: super refers to module 'foo'
894         pub fn foobaz() { }
895     }
896 }
897
898 fn main() {}
899 ```
900
901 ### Functions
902
903 A _function item_ defines a sequence of [statements](#statements) and an
904 optional final [expression](#expressions), along with a name and a set of
905 parameters. Functions are declared with the keyword `fn`. Functions declare a
906 set of *input* [*variables*](#variables) as parameters, through which the caller
907 passes arguments into the function, and the *output* [*type*](#types)
908 of the value the function will return to its caller on completion.
909
910 A function may also be copied into a first-class *value*, in which case the
911 value has the corresponding [*function type*](#function-types), and can be used
912 otherwise exactly as a function item (with a minor additional cost of calling
913 the function indirectly).
914
915 Every control path in a function logically ends with a `return` expression or a
916 diverging expression. If the outermost block of a function has a
917 value-producing expression in its final-expression position, that expression is
918 interpreted as an implicit `return` expression applied to the final-expression.
919
920 An example of a function:
921
922 ```
923 fn add(x: i32, y: i32) -> i32 {
924     return x + y;
925 }
926 ```
927
928 As with `let` bindings, function arguments are irrefutable patterns, so any
929 pattern that is valid in a let binding is also valid as an argument.
930
931 ```
932 fn first((value, _): (i32, i32)) -> i32 { value }
933 ```
934
935
936 #### Generic functions
937
938 A _generic function_ allows one or more _parameterized types_ to appear in its
939 signature. Each type parameter must be explicitly declared, in an
940 angle-bracket-enclosed, comma-separated list following the function name.
941
942 ```rust,ignore
943 // foo is generic over A and B
944
945 fn foo<A, B>(x: A, y: B) {
946 ```
947
948 Inside the function signature and body, the name of the type parameter can be
949 used as a type name. [Trait](#traits) bounds can be specified for type parameters
950 to allow methods with that trait to be called on values of that type. This is
951 specified using the `where` syntax:
952
953 ```rust,ignore
954 fn foo<T>(x: T) where T: Debug {
955 ```
956
957 When a generic function is referenced, its type is instantiated based on the
958 context of the reference. For example, calling the `foo` function here:
959
960 ```
961 use std::fmt::Debug;
962
963 fn foo<T>(x: &[T]) where T: Debug {
964     // details elided
965     # ()
966 }
967
968 foo(&[1, 2]);
969 ```
970
971 will instantiate type parameter `T` with `i32`.
972
973 The type parameters can also be explicitly supplied in a trailing
974 [path](#paths) component after the function name. This might be necessary if
975 there is not sufficient context to determine the type parameters. For example,
976 `mem::size_of::<u32>() == 4`.
977
978 #### Unsafety
979
980 Unsafe operations are those that potentially violate the memory-safety
981 guarantees of Rust's static semantics.
982
983 The following language level features cannot be used in the safe subset of
984 Rust:
985
986 - Dereferencing a [raw pointer](#pointer-types).
987 - Reading or writing a [mutable static variable](#mutable-statics).
988 - Calling an unsafe function (including an intrinsic or foreign function).
989
990 ##### Unsafe functions
991
992 Unsafe functions are functions that are not safe in all contexts and/or for all
993 possible inputs. Such a function must be prefixed with the keyword `unsafe` and
994 can only be called from an `unsafe` block or another `unsafe` function.
995
996 ##### Unsafe blocks
997
998 A block of code can be prefixed with the `unsafe` keyword, to permit calling
999 `unsafe` functions or dereferencing raw pointers within a safe function.
1000
1001 When a programmer has sufficient conviction that a sequence of potentially
1002 unsafe operations is actually safe, they can encapsulate that sequence (taken
1003 as a whole) within an `unsafe` block. The compiler will consider uses of such
1004 code safe, in the surrounding context.
1005
1006 Unsafe blocks are used to wrap foreign libraries, make direct use of hardware
1007 or implement features not directly present in the language. For example, Rust
1008 provides the language features necessary to implement memory-safe concurrency
1009 in the language but the implementation of threads and message passing is in the
1010 standard library.
1011
1012 Rust's type system is a conservative approximation of the dynamic safety
1013 requirements, so in some cases there is a performance cost to using safe code.
1014 For example, a doubly-linked list is not a tree structure and can only be
1015 represented with reference-counted pointers in safe code. By using `unsafe`
1016 blocks to represent the reverse links as raw pointers, it can be implemented
1017 with only boxes.
1018
1019 ##### Behavior considered undefined
1020
1021 The following is a list of behavior which is forbidden in all Rust code,
1022 including within `unsafe` blocks and `unsafe` functions. Type checking provides
1023 the guarantee that these issues are never caused by safe code.
1024
1025 * Data races
1026 * Dereferencing a null/dangling raw pointer
1027 * Reads of [undef](http://llvm.org/docs/LangRef.html#undefined-values)
1028   (uninitialized) memory
1029 * Breaking the [pointer aliasing
1030   rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules)
1031   with raw pointers (a subset of the rules used by C)
1032 * `&mut` and `&` follow LLVM’s scoped [noalias] model, except if the `&T`
1033   contains an `UnsafeCell<U>`. Unsafe code must not violate these aliasing
1034   guarantees.
1035 * Mutating non-mutable data (that is, data reached through a shared reference or
1036   data owned by a `let` binding), unless that data is contained within an `UnsafeCell<U>`.
1037 * Invoking undefined behavior via compiler intrinsics:
1038   * Indexing outside of the bounds of an object with `std::ptr::offset`
1039     (`offset` intrinsic), with
1040     the exception of one byte past the end which is permitted.
1041   * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`
1042     intrinsics) on overlapping buffers
1043 * Invalid values in primitive types, even in private fields/locals:
1044   * Dangling/null references or boxes
1045   * A value other than `false` (0) or `true` (1) in a `bool`
1046   * A discriminant in an `enum` not included in the type definition
1047   * A value in a `char` which is a surrogate or above `char::MAX`
1048   * Non-UTF-8 byte sequences in a `str`
1049 * Unwinding into Rust from foreign code or unwinding from Rust into foreign
1050   code. Rust's failure system is not compatible with exception handling in
1051   other languages. Unwinding must be caught and handled at FFI boundaries.
1052
1053 [noalias]: http://llvm.org/docs/LangRef.html#noalias
1054
1055 ##### Behavior not considered unsafe
1056
1057 This is a list of behavior not considered *unsafe* in Rust terms, but that may
1058 be undesired.
1059
1060 * Deadlocks
1061 * Leaks of memory and other resources
1062 * Exiting without calling destructors
1063 * Integer overflow
1064   - Overflow is considered "unexpected" behavior and is always user-error,
1065     unless the `wrapping` primitives are used. In non-optimized builds, the compiler
1066     will insert debug checks that panic on overflow, but in optimized builds overflow
1067     instead results in wrapped values. See [RFC 560] for the rationale and more details.
1068
1069 [RFC 560]: https://github.com/rust-lang/rfcs/blob/master/text/0560-integer-overflow.md
1070
1071 #### Diverging functions
1072
1073 A special kind of function can be declared with a `!` character where the
1074 output type would normally be. For example:
1075
1076 ```
1077 fn my_err(s: &str) -> ! {
1078     println!("{}", s);
1079     panic!();
1080 }
1081 ```
1082
1083 We call such functions "diverging" because they never return a value to the
1084 caller. Every control path in a diverging function must end with a `panic!()` or
1085 a call to another diverging function on every control path. The `!` annotation
1086 does *not* denote a type.
1087
1088 It might be necessary to declare a diverging function because as mentioned
1089 previously, the typechecker checks that every control path in a function ends
1090 with a [`return`](#return-expressions) or diverging expression. So, if `my_err`
1091 were declared without the `!` annotation, the following code would not
1092 typecheck:
1093
1094 ```
1095 # fn my_err(s: &str) -> ! { panic!() }
1096
1097 fn f(i: i32) -> i32 {
1098     if i == 42 {
1099         return 42;
1100     }
1101     else {
1102         my_err("Bad number!");
1103     }
1104 }
1105 ```
1106
1107 This will not compile without the `!` annotation on `my_err`, since the `else`
1108 branch of the conditional in `f` does not return an `i32`, as required by the
1109 signature of `f`. Adding the `!` annotation to `my_err` informs the
1110 typechecker that, should control ever enter `my_err`, no further type judgments
1111 about `f` need to hold, since control will never resume in any context that
1112 relies on those judgments. Thus the return type on `f` only needs to reflect
1113 the `if` branch of the conditional.
1114
1115 #### Extern functions
1116
1117 Extern functions are part of Rust's foreign function interface, providing the
1118 opposite functionality to [external blocks](#external-blocks). Whereas
1119 external blocks allow Rust code to call foreign code, extern functions with
1120 bodies defined in Rust code _can be called by foreign code_. They are defined
1121 in the same way as any other Rust function, except that they have the `extern`
1122 modifier.
1123
1124 ```
1125 // Declares an extern fn, the ABI defaults to "C"
1126 extern fn new_i32() -> i32 { 0 }
1127
1128 // Declares an extern fn with "stdcall" ABI
1129 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
1130 ```
1131
1132 Unlike normal functions, extern fns have type `extern "ABI" fn()`. This is the
1133 same type as the functions declared in an extern block.
1134
1135 ```
1136 # extern fn new_i32() -> i32 { 0 }
1137 let fptr: extern "C" fn() -> i32 = new_i32;
1138 ```
1139
1140 Extern functions may be called directly from Rust code as Rust uses large,
1141 contiguous stack segments like C.
1142
1143 ### Type aliases
1144
1145 A _type alias_ defines a new name for an existing [type](#types). Type
1146 aliases are declared with the keyword `type`. Every value has a single,
1147 specific type, but may implement several different traits, or be compatible with
1148 several different type constraints.
1149
1150 For example, the following defines the type `Point` as a synonym for the type
1151 `(u8, u8)`, the type of pairs of unsigned 8 bit integers:
1152
1153 ```
1154 type Point = (u8, u8);
1155 let p: Point = (41, 68);
1156 ```
1157
1158 ### Structures
1159
1160 A _structure_ is a nominal [structure type](#structure-types) defined with the
1161 keyword `struct`.
1162
1163 An example of a `struct` item and its use:
1164
1165 ```
1166 struct Point {x: i32, y: i32}
1167 let p = Point {x: 10, y: 11};
1168 let px: i32 = p.x;
1169 ```
1170
1171 A _tuple structure_ is a nominal [tuple type](#tuple-types), also defined with
1172 the keyword `struct`. For example:
1173
1174 ```
1175 struct Point(i32, i32);
1176 let p = Point(10, 11);
1177 let px: i32 = match p { Point(x, _) => x };
1178 ```
1179
1180 A _unit-like struct_ is a structure without any fields, defined by leaving off
1181 the list of fields entirely. Such types will have a single value. For example:
1182
1183 ```
1184 struct Cookie;
1185 let c = [Cookie, Cookie, Cookie, Cookie];
1186 ```
1187
1188 The precise memory layout of a structure is not specified. One can specify a
1189 particular layout using the [`repr` attribute](#ffi-attributes).
1190
1191 ### Enumerations
1192
1193 An _enumeration_ is a simultaneous definition of a nominal [enumerated
1194 type](#enumerated-types) as well as a set of *constructors*, that can be used
1195 to create or pattern-match values of the corresponding enumerated type.
1196
1197 Enumerations are declared with the keyword `enum`.
1198
1199 An example of an `enum` item and its use:
1200
1201 ```
1202 enum Animal {
1203     Dog,
1204     Cat,
1205 }
1206
1207 let mut a: Animal = Animal::Dog;
1208 a = Animal::Cat;
1209 ```
1210
1211 Enumeration constructors can have either named or unnamed fields:
1212
1213 ```rust
1214 enum Animal {
1215     Dog (String, f64),
1216     Cat { name: String, weight: f64 }
1217 }
1218
1219 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
1220 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
1221 ```
1222
1223 In this example, `Cat` is a _struct-like enum variant_,
1224 whereas `Dog` is simply called an enum variant.
1225
1226 Enums have a discriminant. You can assign them explicitly:
1227
1228 ```
1229 enum Foo {
1230     Bar = 123,
1231 }
1232 ```
1233
1234 If a discriminant isn't assigned, they start at zero, and add one for each
1235 variant, in order.
1236
1237 You can cast an enum to get this value:
1238
1239 ```
1240 # enum Foo { Bar = 123 }
1241 let x = Foo::Bar as u32; // x is now 123u32
1242 ```
1243
1244 This only works as long as none of the variants have data attached. If
1245 it were `Bar(i32)`, this is disallowed.
1246
1247 ### Constant items
1248
1249 A *constant item* is a named _constant value_ which is not associated with a
1250 specific memory location in the program. Constants are essentially inlined
1251 wherever they are used, meaning that they are copied directly into the relevant
1252 context when used. References to the same constant are not necessarily
1253 guaranteed to refer to the same memory address.
1254
1255 Constant values must not have destructors, and otherwise permit most forms of
1256 data. Constants may refer to the address of other constants, in which case the
1257 address will have the `static` lifetime. The compiler is, however, still at
1258 liberty to translate the constant many times, so the address referred to may not
1259 be stable.
1260
1261 Constants must be explicitly typed. The type may be `bool`, `char`, a number, or
1262 a type derived from those primitive types. The derived types are references with
1263 the `static` lifetime, fixed-size arrays, tuples, enum variants, and structs.
1264
1265 ```
1266 const BIT1: u32 = 1 << 0;
1267 const BIT2: u32 = 1 << 1;
1268
1269 const BITS: [u32; 2] = [BIT1, BIT2];
1270 const STRING: &'static str = "bitstring";
1271
1272 struct BitsNStrings<'a> {
1273     mybits: [u32; 2],
1274     mystring: &'a str
1275 }
1276
1277 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
1278     mybits: BITS,
1279     mystring: STRING
1280 };
1281 ```
1282
1283 ### Static items
1284
1285 A *static item* is similar to a *constant*, except that it represents a precise
1286 memory location in the program. A static is never "inlined" at the usage site,
1287 and all references to it refer to the same memory location. Static items have
1288 the `static` lifetime, which outlives all other lifetimes in a Rust program.
1289 Static items may be placed in read-only memory if they do not contain any
1290 interior mutability.
1291
1292 Statics may contain interior mutability through the `UnsafeCell` language item.
1293 All access to a static is safe, but there are a number of restrictions on
1294 statics:
1295
1296 * Statics may not contain any destructors.
1297 * The types of static values must ascribe to `Sync` to allow thread-safe access.
1298 * Statics may not refer to other statics by value, only by reference.
1299 * Constants cannot refer to statics.
1300
1301 Constants should in general be preferred over statics, unless large amounts of
1302 data are being stored, or single-address and mutability properties are required.
1303
1304 #### Mutable statics
1305
1306 If a static item is declared with the `mut` keyword, then it is allowed to
1307 be modified by the program. One of Rust's goals is to make concurrency bugs
1308 hard to run into, and this is obviously a very large source of race conditions
1309 or other bugs. For this reason, an `unsafe` block is required when either
1310 reading or writing a mutable static variable. Care should be taken to ensure
1311 that modifications to a mutable static are safe with respect to other threads
1312 running in the same process.
1313
1314 Mutable statics are still very useful, however. They can be used with C
1315 libraries and can also be bound from C libraries (in an `extern` block).
1316
1317 ```
1318 # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }
1319
1320 static mut LEVELS: u32 = 0;
1321
1322 // This violates the idea of no shared state, and this doesn't internally
1323 // protect against races, so this function is `unsafe`
1324 unsafe fn bump_levels_unsafe1() -> u32 {
1325     let ret = LEVELS;
1326     LEVELS += 1;
1327     return ret;
1328 }
1329
1330 // Assuming that we have an atomic_add function which returns the old value,
1331 // this function is "safe" but the meaning of the return value may not be what
1332 // callers expect, so it's still marked as `unsafe`
1333 unsafe fn bump_levels_unsafe2() -> u32 {
1334     return atomic_add(&mut LEVELS, 1);
1335 }
1336 ```
1337
1338 Mutable statics have the same restrictions as normal statics, except that the
1339 type of the value is not required to ascribe to `Sync`.
1340
1341 ### Traits
1342
1343 A _trait_ describes an abstract interface that types can
1344 implement. This interface consists of associated items, which come in
1345 three varieties:
1346
1347 - functions
1348 - constants
1349 - types
1350
1351 Associated functions whose first parameter is named `self` are called
1352 methods and may be invoked using `.` notation (e.g., `x.foo()`).
1353
1354 All traits define an implicit type parameter `Self` that refers to
1355 "the type that is implementing this interface". Traits may also
1356 contain additional type parameters. These type parameters (including
1357 `Self`) may be constrained by other traits and so forth as usual.
1358
1359 Trait bounds on `Self` are considered "supertraits". These are
1360 required to be acyclic.  Supertraits are somewhat different from other
1361 constraints in that they affect what methods are available in the
1362 vtable when the trait is used as a [trait object](#trait-objects).
1363
1364 Traits are implemented for specific types through separate
1365 [implementations](#implementations).
1366
1367 Consider the following trait:
1368
1369 ```
1370 # type Surface = i32;
1371 # type BoundingBox = i32;
1372 trait Shape {
1373     fn draw(&self, Surface);
1374     fn bounding_box(&self) -> BoundingBox;
1375 }
1376 ```
1377
1378 This defines a trait with two methods. All values that have
1379 [implementations](#implementations) of this trait in scope can have their
1380 `draw` and `bounding_box` methods called, using `value.bounding_box()`
1381 [syntax](#method-call-expressions).
1382
1383 Traits can include default implementations of methods, as in:
1384
1385 ```
1386 trait Foo {
1387     fn bar(&self);
1388     fn baz(&self) { println!("We called baz."); }
1389 }
1390 ```
1391
1392 Here the `baz` method has a default implementation, so types that implement
1393 `Foo` need only implement `bar`. It is also possible for implementing types
1394 to override a method that has a default implementation.
1395
1396 Type parameters can be specified for a trait to make it generic. These appear
1397 after the trait name, using the same syntax used in [generic
1398 functions](#generic-functions).
1399
1400 ```
1401 trait Seq<T> {
1402     fn len(&self) -> u32;
1403     fn elt_at(&self, n: u32) -> T;
1404     fn iter<F>(&self, F) where F: Fn(T);
1405 }
1406 ```
1407
1408 It is also possible to define associated types for a trait. Consider the
1409 following example of a `Container` trait. Notice how the type is available
1410 for use in the method signatures:
1411
1412 ```
1413 trait Container {
1414     type E;
1415     fn empty() -> Self;
1416     fn insert(&mut self, Self::E);
1417 }
1418 ```
1419
1420 In order for a type to implement this trait, it must not only provide
1421 implementations for every method, but it must specify the type `E`. Here's
1422 an implementation of `Container` for the standard library type `Vec`:
1423
1424 ```
1425 # trait Container {
1426 #     type E;
1427 #     fn empty() -> Self;
1428 #     fn insert(&mut self, Self::E);
1429 # }
1430 impl<T> Container for Vec<T> {
1431     type E = T;
1432     fn empty() -> Vec<T> { Vec::new() }
1433     fn insert(&mut self, x: T) { self.push(x); }
1434 }
1435 ```
1436
1437 Generic functions may use traits as _bounds_ on their type parameters. This
1438 will have two effects:
1439
1440 - Only types that have the trait may instantiate the parameter.
1441 - Within the generic function, the methods of the trait can be
1442   called on values that have the parameter's type.
1443
1444 For example:
1445
1446 ```
1447 # type Surface = i32;
1448 # trait Shape { fn draw(&self, Surface); }
1449 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
1450     sh.draw(surface);
1451     sh.draw(surface);
1452 }
1453 ```
1454
1455 Traits also define a [trait object](#trait-objects) with the same
1456 name as the trait. Values of this type are created by coercing from a
1457 pointer of some specific type to a pointer of trait type. For example,
1458 `&T` could be coerced to `&Shape` if `T: Shape` holds (and similarly
1459 for `Box<T>`). This coercion can either be implicit or
1460 [explicit](#type-cast-expressions). Here is an example of an explicit
1461 coercion:
1462
1463 ```
1464 trait Shape { }
1465 impl Shape for i32 { }
1466 let mycircle = 0i32;
1467 let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;
1468 ```
1469
1470 The resulting value is a box containing the value that was cast, along with
1471 information that identifies the methods of the implementation that was used.
1472 Values with a trait type can have [methods called](#method-call-expressions) on
1473 them, for any method in the trait, and can be used to instantiate type
1474 parameters that are bounded by the trait.
1475
1476 Trait methods may be static, which means that they lack a `self` argument.
1477 This means that they can only be called with function call syntax (`f(x)`) and
1478 not method call syntax (`obj.f()`). The way to refer to the name of a static
1479 method is to qualify it with the trait name, treating the trait name like a
1480 module. For example:
1481
1482 ```
1483 trait Num {
1484     fn from_i32(n: i32) -> Self;
1485 }
1486 impl Num for f64 {
1487     fn from_i32(n: i32) -> f64 { n as f64 }
1488 }
1489 let x: f64 = Num::from_i32(42);
1490 ```
1491
1492 Traits may inherit from other traits. Consider the following example:
1493
1494 ```
1495 trait Shape { fn area(&self) -> f64; }
1496 trait Circle : Shape { fn radius(&self) -> f64; }
1497 ```
1498
1499 The syntax `Circle : Shape` means that types that implement `Circle` must also
1500 have an implementation for `Shape`. Multiple supertraits are separated by `+`,
1501 `trait Circle : Shape + PartialEq { }`. In an implementation of `Circle` for a
1502 given type `T`, methods can refer to `Shape` methods, since the typechecker
1503 checks that any type with an implementation of `Circle` also has an
1504 implementation of `Shape`:
1505
1506 ```rust
1507 struct Foo;
1508
1509 trait Shape { fn area(&self) -> f64; }
1510 trait Circle : Shape { fn radius(&self) -> f64; }
1511 # impl Shape for Foo {
1512 #     fn area(&self) -> f64 {
1513 #         0.0
1514 #     }
1515 # }
1516 impl Circle for Foo {
1517     fn radius(&self) -> f64 {
1518         println!("calling area: {}", self.area());
1519
1520         0.0
1521     }
1522 }
1523
1524 let c = Foo;
1525 c.radius();
1526 ```
1527
1528 In type-parameterized functions, methods of the supertrait may be called on
1529 values of subtrait-bound type parameters. Referring to the previous example of
1530 `trait Circle : Shape`:
1531
1532 ```
1533 # trait Shape { fn area(&self) -> f64; }
1534 # trait Circle : Shape { fn radius(&self) -> f64; }
1535 fn radius_times_area<T: Circle>(c: T) -> f64 {
1536     // `c` is both a Circle and a Shape
1537     c.radius() * c.area()
1538 }
1539 ```
1540
1541 Likewise, supertrait methods may also be called on trait objects.
1542
1543 ```{.ignore}
1544 # trait Shape { fn area(&self) -> f64; }
1545 # trait Circle : Shape { fn radius(&self) -> f64; }
1546 # impl Shape for i32 { fn area(&self) -> f64 { 0.0 } }
1547 # impl Circle for i32 { fn radius(&self) -> f64 { 0.0 } }
1548 # let mycircle = 0i32;
1549 let mycircle = Box::new(mycircle) as Box<Circle>;
1550 let nonsense = mycircle.radius() * mycircle.area();
1551 ```
1552
1553 ### Implementations
1554
1555 An _implementation_ is an item that implements a [trait](#traits) for a
1556 specific type.
1557
1558 Implementations are defined with the keyword `impl`.
1559
1560 ```
1561 # #[derive(Copy, Clone)]
1562 # struct Point {x: f64, y: f64};
1563 # type Surface = i32;
1564 # struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
1565 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
1566 # fn do_draw_circle(s: Surface, c: Circle) { }
1567 struct Circle {
1568     radius: f64,
1569     center: Point,
1570 }
1571
1572 impl Copy for Circle {}
1573
1574 impl Clone for Circle {
1575     fn clone(&self) -> Circle { *self }
1576 }
1577
1578 impl Shape for Circle {
1579     fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
1580     fn bounding_box(&self) -> BoundingBox {
1581         let r = self.radius;
1582         BoundingBox {
1583             x: self.center.x - r,
1584             y: self.center.y - r,
1585             width: 2.0 * r,
1586             height: 2.0 * r,
1587         }
1588     }
1589 }
1590 ```
1591
1592 It is possible to define an implementation without referring to a trait. The
1593 methods in such an implementation can only be used as direct calls on the
1594 values of the type that the implementation targets. In such an implementation,
1595 the trait type and `for` after `impl` are omitted. Such implementations are
1596 limited to nominal types (enums, structs), and the implementation must appear
1597 in the same crate as the `self` type:
1598
1599 ```
1600 struct Point {x: i32, y: i32}
1601
1602 impl Point {
1603     fn log(&self) {
1604         println!("Point is at ({}, {})", self.x, self.y);
1605     }
1606 }
1607
1608 let my_point = Point {x: 10, y:11};
1609 my_point.log();
1610 ```
1611
1612 When a trait _is_ specified in an `impl`, all methods declared as part of the
1613 trait must be implemented, with matching types and type parameter counts.
1614
1615 An implementation can take type parameters, which can be different from the
1616 type parameters taken by the trait it implements. Implementation parameters
1617 are written after the `impl` keyword.
1618
1619 ```
1620 # trait Seq<T> { fn dummy(&self, _: T) { } }
1621 impl<T> Seq<T> for Vec<T> {
1622     /* ... */
1623 }
1624 impl Seq<bool> for u32 {
1625     /* Treat the integer as a sequence of bits */
1626 }
1627 ```
1628
1629 ### External blocks
1630
1631 External blocks form the basis for Rust's foreign function interface.
1632 Declarations in an external block describe symbols in external, non-Rust
1633 libraries.
1634
1635 Functions within external blocks are declared in the same way as other Rust
1636 functions, with the exception that they may not have a body and are instead
1637 terminated by a semicolon.
1638
1639 Functions within external blocks may be called by Rust code, just like
1640 functions defined in Rust. The Rust compiler automatically translates between
1641 the Rust ABI and the foreign ABI.
1642
1643 A number of [attributes](#attributes) control the behavior of external blocks.
1644
1645 By default external blocks assume that the library they are calling uses the
1646 standard C "cdecl" ABI. Other ABIs may be specified using an `abi` string, as
1647 shown here:
1648
1649 ```ignore
1650 // Interface to the Windows API
1651 extern "stdcall" { }
1652 ```
1653
1654 The `link` attribute allows the name of the library to be specified. When
1655 specified the compiler will attempt to link against the native library of the
1656 specified name.
1657
1658 ```{.ignore}
1659 #[link(name = "crypto")]
1660 extern { }
1661 ```
1662
1663 The type of a function declared in an extern block is `extern "abi" fn(A1, ...,
1664 An) -> R`, where `A1...An` are the declared types of its arguments and `R` is
1665 the declared return type.
1666
1667 It is valid to add the `link` attribute on an empty extern block. You can use
1668 this to satisfy the linking requirements of extern blocks elsewhere in your code
1669 (including upstream crates) instead of adding the attribute to each extern block.
1670
1671 ## Visibility and Privacy
1672
1673 These two terms are often used interchangeably, and what they are attempting to
1674 convey is the answer to the question "Can this item be used at this location?"
1675
1676 Rust's name resolution operates on a global hierarchy of namespaces. Each level
1677 in the hierarchy can be thought of as some item. The items are one of those
1678 mentioned above, but also include external crates. Declaring or defining a new
1679 module can be thought of as inserting a new tree into the hierarchy at the
1680 location of the definition.
1681
1682 To control whether interfaces can be used across modules, Rust checks each use
1683 of an item to see whether it should be allowed or not. This is where privacy
1684 warnings are generated, or otherwise "you used a private item of another module
1685 and weren't allowed to."
1686
1687 By default, everything in Rust is *private*, with one exception. Enum variants
1688 in a `pub` enum are also public by default. When an item is declared as `pub`,
1689 it can be thought of as being accessible to the outside world. For example:
1690
1691 ```
1692 # fn main() {}
1693 // Declare a private struct
1694 struct Foo;
1695
1696 // Declare a public struct with a private field
1697 pub struct Bar {
1698     field: i32
1699 }
1700
1701 // Declare a public enum with two public variants
1702 pub enum State {
1703     PubliclyAccessibleState,
1704     PubliclyAccessibleState2,
1705 }
1706 ```
1707
1708 With the notion of an item being either public or private, Rust allows item
1709 accesses in two cases:
1710
1711 1. If an item is public, then it can be used externally through any of its
1712    public ancestors.
1713 2. If an item is private, it may be accessed by the current module and its
1714    descendants.
1715
1716 These two cases are surprisingly powerful for creating module hierarchies
1717 exposing public APIs while hiding internal implementation details. To help
1718 explain, here's a few use cases and what they would entail:
1719
1720 * A library developer needs to expose functionality to crates which link
1721   against their library. As a consequence of the first case, this means that
1722   anything which is usable externally must be `pub` from the root down to the
1723   destination item. Any private item in the chain will disallow external
1724   accesses.
1725
1726 * A crate needs a global available "helper module" to itself, but it doesn't
1727   want to expose the helper module as a public API. To accomplish this, the
1728   root of the crate's hierarchy would have a private module which then
1729   internally has a "public API". Because the entire crate is a descendant of
1730   the root, then the entire local crate can access this private module through
1731   the second case.
1732
1733 * When writing unit tests for a module, it's often a common idiom to have an
1734   immediate child of the module to-be-tested named `mod test`. This module
1735   could access any items of the parent module through the second case, meaning
1736   that internal implementation details could also be seamlessly tested from the
1737   child module.
1738
1739 In the second case, it mentions that a private item "can be accessed" by the
1740 current module and its descendants, but the exact meaning of accessing an item
1741 depends on what the item is. Accessing a module, for example, would mean
1742 looking inside of it (to import more items). On the other hand, accessing a
1743 function would mean that it is invoked. Additionally, path expressions and
1744 import statements are considered to access an item in the sense that the
1745 import/expression is only valid if the destination is in the current visibility
1746 scope.
1747
1748 Here's an example of a program which exemplifies the three cases outlined
1749 above:
1750
1751 ```
1752 // This module is private, meaning that no external crate can access this
1753 // module. Because it is private at the root of this current crate, however, any
1754 // module in the crate may access any publicly visible item in this module.
1755 mod crate_helper_module {
1756
1757     // This function can be used by anything in the current crate
1758     pub fn crate_helper() {}
1759
1760     // This function *cannot* be used by anything else in the crate. It is not
1761     // publicly visible outside of the `crate_helper_module`, so only this
1762     // current module and its descendants may access it.
1763     fn implementation_detail() {}
1764 }
1765
1766 // This function is "public to the root" meaning that it's available to external
1767 // crates linking against this one.
1768 pub fn public_api() {}
1769
1770 // Similarly to 'public_api', this module is public so external crates may look
1771 // inside of it.
1772 pub mod submodule {
1773     use crate_helper_module;
1774
1775     pub fn my_method() {
1776         // Any item in the local crate may invoke the helper module's public
1777         // interface through a combination of the two rules above.
1778         crate_helper_module::crate_helper();
1779     }
1780
1781     // This function is hidden to any module which is not a descendant of
1782     // `submodule`
1783     fn my_implementation() {}
1784
1785     #[cfg(test)]
1786     mod test {
1787
1788         #[test]
1789         fn test_my_implementation() {
1790             // Because this module is a descendant of `submodule`, it's allowed
1791             // to access private items inside of `submodule` without a privacy
1792             // violation.
1793             super::my_implementation();
1794         }
1795     }
1796 }
1797
1798 # fn main() {}
1799 ```
1800
1801 For a rust program to pass the privacy checking pass, all paths must be valid
1802 accesses given the two rules above. This includes all use statements,
1803 expressions, types, etc.
1804
1805 ### Re-exporting and Visibility
1806
1807 Rust allows publicly re-exporting items through a `pub use` directive. Because
1808 this is a public directive, this allows the item to be used in the current
1809 module through the rules above. It essentially allows public access into the
1810 re-exported item. For example, this program is valid:
1811
1812 ```
1813 pub use self::implementation::api;
1814
1815 mod implementation {
1816     pub mod api {
1817         pub fn f() {}
1818     }
1819 }
1820
1821 # fn main() {}
1822 ```
1823
1824 This means that any external crate referencing `implementation::api::f` would
1825 receive a privacy violation, while the path `api::f` would be allowed.
1826
1827 When re-exporting a private item, it can be thought of as allowing the "privacy
1828 chain" being short-circuited through the reexport instead of passing through
1829 the namespace hierarchy as it normally would.
1830
1831 ## Attributes
1832
1833 Any item declaration may have an _attribute_ applied to it. Attributes in Rust
1834 are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
1835 (C#). An attribute is a general, free-form metadatum that is interpreted
1836 according to name, convention, and language and compiler version. Attributes
1837 may appear as any of:
1838
1839 * A single identifier, the attribute name
1840 * An identifier followed by the equals sign '=' and a literal, providing a
1841   key/value pair
1842 * An identifier followed by a parenthesized list of sub-attribute arguments
1843
1844 Attributes with a bang ("!") after the hash ("#") apply to the item that the
1845 attribute is declared within. Attributes that do not have a bang after the hash
1846 apply to the item that follows the attribute.
1847
1848 An example of attributes:
1849
1850 ```{.rust}
1851 // General metadata applied to the enclosing module or crate.
1852 #![crate_type = "lib"]
1853
1854 // A function marked as a unit test
1855 #[test]
1856 fn test_foo() {
1857     /* ... */
1858 }
1859
1860 // A conditionally-compiled module
1861 #[cfg(target_os="linux")]
1862 mod bar {
1863     /* ... */
1864 }
1865
1866 // A lint attribute used to suppress a warning/error
1867 #[allow(non_camel_case_types)]
1868 type int8_t = i8;
1869 ```
1870
1871 > **Note:** At some point in the future, the compiler will distinguish between
1872 > language-reserved and user-available attributes. Until then, there is
1873 > effectively no difference between an attribute handled by a loadable syntax
1874 > extension and the compiler.
1875
1876 ### Crate-only attributes
1877
1878 - `crate_name` - specify the crate's crate name.
1879 - `crate_type` - see [linkage](#linkage).
1880 - `feature` - see [compiler features](#compiler-features).
1881 - `no_builtins` - disable optimizing certain code patterns to invocations of
1882                   library functions that are assumed to exist
1883 - `no_main` - disable emitting the `main` symbol. Useful when some other
1884    object being linked to defines `main`.
1885 - `no_start` - disable linking to the `native` crate, which specifies the
1886   "start" language item.
1887 - `no_std` - disable linking to the `std` crate.
1888 - `plugin` - load a list of named crates as compiler plugins, e.g.
1889              `#![plugin(foo, bar)]`. Optional arguments for each plugin,
1890              i.e. `#![plugin(foo(... args ...))]`, are provided to the plugin's
1891              registrar function.  The `plugin` feature gate is required to use
1892              this attribute.
1893 - `recursion_limit` - Sets the maximum depth for potentially
1894                       infinitely-recursive compile-time operations like
1895                       auto-dereference or macro expansion. The default is
1896                       `#![recursion_limit="64"]`.
1897
1898 ### Module-only attributes
1899
1900 - `no_implicit_prelude` - disable injecting `use std::prelude::*` in this
1901   module.
1902 - `path` - specifies the file to load the module from. `#[path="foo.rs"] mod
1903   bar;` is equivalent to `mod bar { /* contents of foo.rs */ }`. The path is
1904   taken relative to the directory that the current module is in.
1905
1906 ### Function-only attributes
1907
1908 - `main` - indicates that this function should be passed to the entry point,
1909   rather than the function in the crate root named `main`.
1910 - `plugin_registrar` - mark this function as the registration point for
1911   [compiler plugins][plugin], such as loadable syntax extensions.
1912 - `start` - indicates that this function should be used as the entry point,
1913   overriding the "start" language item. See the "start" [language
1914   item](#language-items) for more details.
1915 - `test` - indicates that this function is a test function, to only be compiled
1916   in case of `--test`.
1917 - `should_panic` - indicates that this test function should panic, inverting the success condition.
1918 - `cold` - The function is unlikely to be executed, so optimize it (and calls
1919   to it) differently.
1920
1921 ### Static-only attributes
1922
1923 - `thread_local` - on a `static mut`, this signals that the value of this
1924   static may change depending on the current thread. The exact consequences of
1925   this are implementation-defined.
1926
1927 ### FFI attributes
1928
1929 On an `extern` block, the following attributes are interpreted:
1930
1931 - `link_args` - specify arguments to the linker, rather than just the library
1932   name and type. This is feature gated and the exact behavior is
1933   implementation-defined (due to variety of linker invocation syntax).
1934 - `link` - indicate that a native library should be linked to for the
1935   declarations in this block to be linked correctly. `link` supports an optional
1936   `kind` key with three possible values: `dylib`, `static`, and `framework`. See
1937   [external blocks](#external-blocks) for more about external blocks. Two
1938   examples: `#[link(name = "readline")]` and
1939   `#[link(name = "CoreFoundation", kind = "framework")]`.
1940 - `linked_from` - indicates what native library this block of FFI items is
1941   coming from. This attribute is of the form `#[linked_from = "foo"]` where
1942   `foo` is the name of a library in either `#[link]` or a `-l` flag. This
1943   attribute is currently required to export symbols from a Rust dynamic library
1944   on Windows, and it is feature gated behind the `linked_from` feature.
1945
1946 On declarations inside an `extern` block, the following attributes are
1947 interpreted:
1948
1949 - `link_name` - the name of the symbol that this function or static should be
1950   imported as.
1951 - `linkage` - on a static, this specifies the [linkage
1952   type](http://llvm.org/docs/LangRef.html#linkage-types).
1953
1954 On `enum`s:
1955
1956 - `repr` - on C-like enums, this sets the underlying type used for
1957   representation. Takes one argument, which is the primitive
1958   type this enum should be represented for, or `C`, which specifies that it
1959   should be the default `enum` size of the C ABI for that platform. Note that
1960   enum representation in C is undefined, and this may be incorrect when the C
1961   code is compiled with certain flags.
1962
1963 On `struct`s:
1964
1965 - `repr` - specifies the representation to use for this struct. Takes a list
1966   of options. The currently accepted ones are `C` and `packed`, which may be
1967   combined. `C` will use a C ABI compatible struct layout, and `packed` will
1968   remove any padding between fields (note that this is very fragile and may
1969   break platforms which require aligned access).
1970
1971 ### Macro-related attributes
1972
1973 - `macro_use` on a `mod` â€” macros defined in this module will be visible in the
1974   module's parent, after this module has been included.
1975
1976 - `macro_use` on an `extern crate` â€” load macros from this crate.  An optional
1977   list of names `#[macro_use(foo, bar)]` restricts the import to just those
1978   macros named.  The `extern crate` must appear at the crate root, not inside
1979   `mod`, which ensures proper function of the [`$crate` macro
1980   variable](book/macros.html#the-variable-$crate).
1981
1982 - `macro_reexport` on an `extern crate` â€” re-export the named macros.
1983
1984 - `macro_export` - export a macro for cross-crate usage.
1985
1986 - `no_link` on an `extern crate` â€” even if we load this crate for macros, don't
1987   link it into the output.
1988
1989 See the [macros section of the
1990 book](book/macros.html#scoping-and-macro-import/export) for more information on
1991 macro scope.
1992
1993
1994 ### Miscellaneous attributes
1995
1996 - `export_name` - on statics and functions, this determines the name of the
1997   exported symbol.
1998 - `link_section` - on statics and functions, this specifies the section of the
1999   object file that this item's contents will be placed into.
2000 - `no_mangle` - on any item, do not apply the standard name mangling. Set the
2001   symbol for this item to its identifier.
2002 - `simd` - on certain tuple structs, derive the arithmetic operators, which
2003   lower to the target's SIMD instructions, if any; the `simd` feature gate
2004   is necessary to use this attribute.
2005 - `unsafe_no_drop_flag` - on structs, remove the flag that prevents
2006   destructors from being run twice. Destructors might be run multiple times on
2007   the same object with this attribute. To use this, the `unsafe_no_drop_flag` feature
2008   gate must be enabled.
2009 - `doc` - Doc comments such as `/// foo` are equivalent to `#[doc = "foo"]`.
2010 - `rustc_on_unimplemented` - Write a custom note to be shown along with the error
2011    when the trait is found to be unimplemented on a type.
2012    You may use format arguments like `{T}`, `{A}` to correspond to the
2013    types at the point of use corresponding to the type parameters of the
2014    trait of the same name. `{Self}` will be replaced with the type that is supposed
2015    to implement the trait but doesn't. To use this, the `on_unimplemented` feature gate
2016    must be enabled.
2017
2018 ### Conditional compilation
2019
2020 Sometimes one wants to have different compiler outputs from the same code,
2021 depending on build target, such as targeted operating system, or to enable
2022 release builds.
2023
2024 There are two kinds of configuration options, one that is either defined or not
2025 (`#[cfg(foo)]`), and the other that contains a string that can be checked
2026 against (`#[cfg(bar = "baz")]`). Currently, only compiler-defined configuration
2027 options can have the latter form.
2028
2029 ```
2030 // The function is only included in the build when compiling for OSX
2031 #[cfg(target_os = "macos")]
2032 fn macos_only() {
2033   // ...
2034 }
2035
2036 // This function is only included when either foo or bar is defined
2037 #[cfg(any(foo, bar))]
2038 fn needs_foo_or_bar() {
2039   // ...
2040 }
2041
2042 // This function is only included when compiling for a unixish OS with a 32-bit
2043 // architecture
2044 #[cfg(all(unix, target_pointer_width = "32"))]
2045 fn on_32bit_unix() {
2046   // ...
2047 }
2048
2049 // This function is only included when foo is not defined
2050 #[cfg(not(foo))]
2051 fn needs_not_foo() {
2052   // ...
2053 }
2054 ```
2055
2056 This illustrates some conditional compilation can be achieved using the
2057 `#[cfg(...)]` attribute. `any`, `all` and `not` can be used to assemble
2058 arbitrarily complex configurations through nesting.
2059
2060 The following configurations must be defined by the implementation:
2061
2062 * `debug_assertions` - Enabled by default when compiling without optimizations.
2063   This can be used to enable extra debugging code in development but not in
2064   production.  For example, it controls the behavior of the standard library's
2065   `debug_assert!` macro.
2066 * `target_arch = "..."` - Target CPU architecture, such as `"x86"`, `"x86_64"`
2067   `"mips"`, `"powerpc"`, `"arm"`, or `"aarch64"`.
2068 * `target_endian = "..."` - Endianness of the target CPU, either `"little"` or
2069   `"big"`.
2070 * `target_env = ".."` - An option provided by the compiler by default
2071   describing the runtime environment of the target platform. Some examples of
2072   this are `musl` for builds targeting the MUSL libc implementation, `msvc` for
2073   Windows builds targeting MSVC, and `gnu` frequently the rest of the time. This
2074   option may also be blank on some platforms.
2075 * `target_family = "..."` - Operating system family of the target, e. g.
2076   `"unix"` or `"windows"`. The value of this configuration option is defined
2077   as a configuration itself, like `unix` or `windows`.
2078 * `target_os = "..."` - Operating system of the target, examples include
2079   `"windows"`, `"macos"`, `"ios"`, `"linux"`, `"android"`, `"freebsd"`, `"dragonfly"`,
2080   `"bitrig"` , `"openbsd"` or `"netbsd"`.
2081 * `target_pointer_width = "..."` - Target pointer width in bits. This is set
2082   to `"32"` for targets with 32-bit pointers, and likewise set to `"64"` for
2083   64-bit pointers.
2084 * `test` - Enabled when compiling the test harness (using the `--test` flag).
2085 * `unix` - See `target_family`.
2086 * `windows` - See `target_family`.
2087
2088 You can also set another attribute based on a `cfg` variable with `cfg_attr`:
2089
2090 ```rust,ignore
2091 #[cfg_attr(a, b)]
2092 ```
2093
2094 Will be the same as `#[b]` if `a` is set by `cfg`, and nothing otherwise.
2095
2096 ### Lint check attributes
2097
2098 A lint check names a potentially undesirable coding pattern, such as
2099 unreachable code or omitted documentation, for the static entity to which the
2100 attribute applies.
2101
2102 For any lint check `C`:
2103
2104 * `allow(C)` overrides the check for `C` so that violations will go
2105    unreported,
2106 * `deny(C)` signals an error after encountering a violation of `C`,
2107 * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint
2108    level afterwards,
2109 * `warn(C)` warns about violations of `C` but continues compilation.
2110
2111 The lint checks supported by the compiler can be found via `rustc -W help`,
2112 along with their default settings.  [Compiler
2113 plugins](book/compiler-plugins.html#lint-plugins) can provide additional lint checks.
2114
2115 ```{.ignore}
2116 mod m1 {
2117     // Missing documentation is ignored here
2118     #[allow(missing_docs)]
2119     pub fn undocumented_one() -> i32 { 1 }
2120
2121     // Missing documentation signals a warning here
2122     #[warn(missing_docs)]
2123     pub fn undocumented_too() -> i32 { 2 }
2124
2125     // Missing documentation signals an error here
2126     #[deny(missing_docs)]
2127     pub fn undocumented_end() -> i32 { 3 }
2128 }
2129 ```
2130
2131 This example shows how one can use `allow` and `warn` to toggle a particular
2132 check on and off:
2133
2134 ```{.ignore}
2135 #[warn(missing_docs)]
2136 mod m2{
2137     #[allow(missing_docs)]
2138     mod nested {
2139         // Missing documentation is ignored here
2140         pub fn undocumented_one() -> i32 { 1 }
2141
2142         // Missing documentation signals a warning here,
2143         // despite the allow above.
2144         #[warn(missing_docs)]
2145         pub fn undocumented_two() -> i32 { 2 }
2146     }
2147
2148     // Missing documentation signals a warning here
2149     pub fn undocumented_too() -> i32 { 3 }
2150 }
2151 ```
2152
2153 This example shows how one can use `forbid` to disallow uses of `allow` for
2154 that lint check:
2155
2156 ```{.ignore}
2157 #[forbid(missing_docs)]
2158 mod m3 {
2159     // Attempting to toggle warning signals an error here
2160     #[allow(missing_docs)]
2161     /// Returns 2.
2162     pub fn undocumented_too() -> i32 { 2 }
2163 }
2164 ```
2165
2166 ### Language items
2167
2168 Some primitive Rust operations are defined in Rust code, rather than being
2169 implemented directly in C or assembly language. The definitions of these
2170 operations have to be easy for the compiler to find. The `lang` attribute
2171 makes it possible to declare these operations. For example, the `str` module
2172 in the Rust standard library defines the string equality function:
2173
2174 ```{.ignore}
2175 #[lang = "str_eq"]
2176 pub fn eq_slice(a: &str, b: &str) -> bool {
2177     // details elided
2178 }
2179 ```
2180
2181 The name `str_eq` has a special meaning to the Rust compiler, and the presence
2182 of this definition means that it will use this definition when generating calls
2183 to the string equality function.
2184
2185 The set of language items is currently considered unstable. A complete
2186 list of the built-in language items will be added in the future.
2187
2188 ### Inline attributes
2189
2190 The inline attribute suggests that the compiler should place a copy of
2191 the function or static in the caller, rather than generating code to
2192 call the function or access the static where it is defined.
2193
2194 The compiler automatically inlines functions based on internal heuristics.
2195 Incorrectly inlining functions can actually make the program slower, so it
2196 should be used with care.
2197
2198 `#[inline]` and `#[inline(always)]` always cause the function to be serialized
2199 into the crate metadata to allow cross-crate inlining.
2200
2201 There are three different types of inline attributes:
2202
2203 * `#[inline]` hints the compiler to perform an inline expansion.
2204 * `#[inline(always)]` asks the compiler to always perform an inline expansion.
2205 * `#[inline(never)]` asks the compiler to never perform an inline expansion.
2206
2207 ### `derive`
2208
2209 The `derive` attribute allows certain traits to be automatically implemented
2210 for data structures. For example, the following will create an `impl` for the
2211 `PartialEq` and `Clone` traits for `Foo`, the type parameter `T` will be given
2212 the `PartialEq` or `Clone` constraints for the appropriate `impl`:
2213
2214 ```
2215 #[derive(PartialEq, Clone)]
2216 struct Foo<T> {
2217     a: i32,
2218     b: T
2219 }
2220 ```
2221
2222 The generated `impl` for `PartialEq` is equivalent to
2223
2224 ```
2225 # struct Foo<T> { a: i32, b: T }
2226 impl<T: PartialEq> PartialEq for Foo<T> {
2227     fn eq(&self, other: &Foo<T>) -> bool {
2228         self.a == other.a && self.b == other.b
2229     }
2230
2231     fn ne(&self, other: &Foo<T>) -> bool {
2232         self.a != other.a || self.b != other.b
2233     }
2234 }
2235 ```
2236
2237 ### Compiler Features
2238
2239 Certain aspects of Rust may be implemented in the compiler, but they're not
2240 necessarily ready for every-day use. These features are often of "prototype
2241 quality" or "almost production ready", but may not be stable enough to be
2242 considered a full-fledged language feature.
2243
2244 For this reason, Rust recognizes a special crate-level attribute of the form:
2245
2246 ```{.ignore}
2247 #![feature(feature1, feature2, feature3)]
2248 ```
2249
2250 This directive informs the compiler that the feature list: `feature1`,
2251 `feature2`, and `feature3` should all be enabled. This is only recognized at a
2252 crate-level, not at a module-level. Without this directive, all features are
2253 considered off, and using the features will result in a compiler error.
2254
2255 The currently implemented features of the reference compiler are:
2256
2257 * `advanced_slice_patterns` - See the [match expressions](#match-expressions)
2258                               section for discussion; the exact semantics of
2259                               slice patterns are subject to change, so some types
2260                               are still unstable.
2261
2262 * `slice_patterns` - OK, actually, slice patterns are just scary and
2263                      completely unstable.
2264
2265 * `asm` - The `asm!` macro provides a means for inline assembly. This is often
2266           useful, but the exact syntax for this feature along with its
2267           semantics are likely to change, so this macro usage must be opted
2268           into.
2269
2270 * `associated_consts` - Allows constants to be defined in `impl` and `trait`
2271                         blocks, so that they can be associated with a type or
2272                         trait in a similar manner to methods and associated
2273                         types.
2274
2275 * `box_patterns` - Allows `box` patterns, the exact semantics of which
2276                    is subject to change.
2277
2278 * `box_syntax` - Allows use of `box` expressions, the exact semantics of which
2279                  is subject to change.
2280
2281 * `concat_idents` - Allows use of the `concat_idents` macro, which is in many
2282                     ways insufficient for concatenating identifiers, and may be
2283                     removed entirely for something more wholesome.
2284
2285 * `custom_attribute` - Allows the usage of attributes unknown to the compiler
2286                        so that new attributes can be added in a backwards compatible
2287                        manner (RFC 572).
2288
2289 * `custom_derive` - Allows the use of `#[derive(Foo,Bar)]` as sugar for
2290                     `#[derive_Foo] #[derive_Bar]`, which can be user-defined syntax
2291                     extensions.
2292
2293 * `intrinsics` - Allows use of the "rust-intrinsics" ABI. Compiler intrinsics
2294                  are inherently unstable and no promise about them is made.
2295
2296 * `lang_items` - Allows use of the `#[lang]` attribute. Like `intrinsics`,
2297                  lang items are inherently unstable and no promise about them
2298                  is made.
2299
2300 * `link_args` - This attribute is used to specify custom flags to the linker,
2301                 but usage is strongly discouraged. The compiler's usage of the
2302                 system linker is not guaranteed to continue in the future, and
2303                 if the system linker is not used then specifying custom flags
2304                 doesn't have much meaning.
2305
2306 * `link_llvm_intrinsics` â€“ Allows linking to LLVM intrinsics via
2307                            `#[link_name="llvm.*"]`.
2308
2309 * `linkage` - Allows use of the `linkage` attribute, which is not portable.
2310
2311 * `log_syntax` - Allows use of the `log_syntax` macro attribute, which is a
2312                  nasty hack that will certainly be removed.
2313
2314 * `main` - Allows use of the `#[main]` attribute, which changes the entry point
2315            into a Rust program. This capability is subject to change.
2316
2317 * `macro_reexport` - Allows macros to be re-exported from one crate after being imported
2318                      from another. This feature was originally designed with the sole
2319                      use case of the Rust standard library in mind, and is subject to
2320                      change.
2321
2322 * `non_ascii_idents` - The compiler supports the use of non-ascii identifiers,
2323                        but the implementation is a little rough around the
2324                        edges, so this can be seen as an experimental feature
2325                        for now until the specification of identifiers is fully
2326                        fleshed out.
2327
2328 * `no_std` - Allows the `#![no_std]` crate attribute, which disables the implicit
2329              `extern crate std`. This typically requires use of the unstable APIs
2330              behind the libstd "facade", such as libcore and libcollections. It
2331              may also cause problems when using syntax extensions, including
2332              `#[derive]`.
2333
2334 * `on_unimplemented` - Allows the `#[rustc_on_unimplemented]` attribute, which allows
2335                        trait definitions to add specialized notes to error messages
2336                        when an implementation was expected but not found.
2337
2338 * `optin_builtin_traits` - Allows the definition of default and negative trait
2339                            implementations. Experimental.
2340
2341 * `plugin` - Usage of [compiler plugins][plugin] for custom lints or syntax extensions.
2342              These depend on compiler internals and are subject to change.
2343
2344 * `plugin_registrar` - Indicates that a crate provides [compiler plugins][plugin].
2345
2346 * `quote` - Allows use of the `quote_*!` family of macros, which are
2347             implemented very poorly and will likely change significantly
2348             with a proper implementation.
2349
2350 * `rustc_attrs` - Gates internal `#[rustc_*]` attributes which may be
2351                   for internal use only or have meaning added to them in the future.
2352
2353 * `rustc_diagnostic_macros`- A mysterious feature, used in the implementation
2354                              of rustc, not meant for mortals.
2355
2356 * `simd` - Allows use of the `#[simd]` attribute, which is overly simple and
2357            not the SIMD interface we want to expose in the long term.
2358
2359 * `simd_ffi` - Allows use of SIMD vectors in signatures for foreign functions.
2360                The SIMD interface is subject to change.
2361
2362 * `staged_api` - Allows usage of stability markers and `#![staged_api]` in a
2363                  crate. Stability markers are also attributes: `#[stable]`,
2364                  `#[unstable]`, and `#[deprecated]` are the three levels.
2365
2366 * `start` - Allows use of the `#[start]` attribute, which changes the entry point
2367             into a Rust program. This capability, especially the signature for the
2368             annotated function, is subject to change.
2369
2370 * `struct_variant` - Structural enum variants (those with named fields). It is
2371                      currently unknown whether this style of enum variant is as
2372                      fully supported as the tuple-forms, and it's not certain
2373                      that this style of variant should remain in the language.
2374                      For now this style of variant is hidden behind a feature
2375                      flag.
2376
2377 * `thread_local` - The usage of the `#[thread_local]` attribute is experimental
2378                    and should be seen as unstable. This attribute is used to
2379                    declare a `static` as being unique per-thread leveraging
2380                    LLVM's implementation which works in concert with the kernel
2381                    loader and dynamic linker. This is not necessarily available
2382                    on all platforms, and usage of it is discouraged.
2383
2384 * `trace_macros` - Allows use of the `trace_macros` macro, which is a nasty
2385                    hack that will certainly be removed.
2386
2387 * `unboxed_closures` - Rust's new closure design, which is currently a work in
2388                        progress feature with many known bugs.
2389
2390 * `unsafe_no_drop_flag` - Allows use of the `#[unsafe_no_drop_flag]` attribute,
2391                           which removes hidden flag added to a type that
2392                           implements the `Drop` trait. The design for the
2393                           `Drop` flag is subject to change, and this feature
2394                           may be removed in the future.
2395
2396 * `unmarked_api` - Allows use of items within a `#![staged_api]` crate
2397                    which have not been marked with a stability marker.
2398                    Such items should not be allowed by the compiler to exist,
2399                    so if you need this there probably is a compiler bug.
2400
2401 * `visible_private_types` - Allows public APIs to expose otherwise private
2402                             types, e.g. as the return type of a public function.
2403                             This capability may be removed in the future.
2404
2405 * `allow_internal_unstable` - Allows `macro_rules!` macros to be tagged with the
2406                               `#[allow_internal_unstable]` attribute, designed
2407                               to allow `std` macros to call
2408                               `#[unstable]`/feature-gated functionality
2409                               internally without imposing on callers
2410                               (i.e. making them behave like function calls in
2411                               terms of encapsulation).
2412 * - `default_type_parameter_fallback` - Allows type parameter defaults to
2413                                         influence type inference.
2414
2415 If a feature is promoted to a language feature, then all existing programs will
2416 start to receive compilation warnings about `#![feature]` directives which enabled
2417 the new feature (because the directive is no longer necessary). However, if a
2418 feature is decided to be removed from the language, errors will be issued (if
2419 there isn't a parser error first). The directive in this case is no longer
2420 necessary, and it's likely that existing code will break if the feature isn't
2421 removed.
2422
2423 If an unknown feature is found in a directive, it results in a compiler error.
2424 An unknown feature is one which has never been recognized by the compiler.
2425
2426 # Statements and expressions
2427
2428 Rust is _primarily_ an expression language. This means that most forms of
2429 value-producing or effect-causing evaluation are directed by the uniform syntax
2430 category of _expressions_. Each kind of expression can typically _nest_ within
2431 each other kind of expression, and rules for evaluation of expressions involve
2432 specifying both the value produced by the expression and the order in which its
2433 sub-expressions are themselves evaluated.
2434
2435 In contrast, statements in Rust serve _mostly_ to contain and explicitly
2436 sequence expression evaluation.
2437
2438 ## Statements
2439
2440 A _statement_ is a component of a block, which is in turn a component of an
2441 outer [expression](#expressions) or [function](#functions).
2442
2443 Rust has two kinds of statement: [declaration
2444 statements](#declaration-statements) and [expression
2445 statements](#expression-statements).
2446
2447 ### Declaration statements
2448
2449 A _declaration statement_ is one that introduces one or more *names* into the
2450 enclosing statement block. The declared names may denote new variables or new
2451 items.
2452
2453 #### Item declarations
2454
2455 An _item declaration statement_ has a syntactic form identical to an
2456 [item](#items) declaration within a module. Declaring an item &mdash; a
2457 function, enumeration, structure, type, static, trait, implementation or module
2458 &mdash; locally within a statement block is simply a way of restricting its
2459 scope to a narrow region containing all of its uses; it is otherwise identical
2460 in meaning to declaring the item outside the statement block.
2461
2462 > **Note**: there is no implicit capture of the function's dynamic environment when
2463 > declaring a function-local item.
2464
2465 #### Variable declarations
2466
2467 A _variable declaration_ introduces a new set of variable, given by a pattern. The
2468 pattern may be followed by a type annotation, and/or an initializer expression.
2469 When no type annotation is given, the compiler will infer the type, or signal
2470 an error if insufficient type information is available for definite inference.
2471 Any variables introduced by a variable declaration are visible from the point of
2472 declaration until the end of the enclosing block scope.
2473
2474 ### Expression statements
2475
2476 An _expression statement_ is one that evaluates an [expression](#expressions)
2477 and ignores its result. The type of an expression statement `e;` is always
2478 `()`, regardless of the type of `e`. As a rule, an expression statement's
2479 purpose is to trigger the effects of evaluating its expression.
2480
2481 ## Expressions
2482
2483 An expression may have two roles: it always produces a *value*, and it may have
2484 *effects* (otherwise known as "side effects"). An expression *evaluates to* a
2485 value, and has effects during *evaluation*. Many expressions contain
2486 sub-expressions (operands). The meaning of each kind of expression dictates
2487 several things:
2488
2489 * Whether or not to evaluate the sub-expressions when evaluating the expression
2490 * The order in which to evaluate the sub-expressions
2491 * How to combine the sub-expressions' values to obtain the value of the expression
2492
2493 In this way, the structure of expressions dictates the structure of execution.
2494 Blocks are just another kind of expression, so blocks, statements, expressions,
2495 and blocks again can recursively nest inside each other to an arbitrary depth.
2496
2497 #### Lvalues, rvalues and temporaries
2498
2499 Expressions are divided into two main categories: _lvalues_ and _rvalues_.
2500 Likewise within each expression, sub-expressions may occur in _lvalue context_
2501 or _rvalue context_. The evaluation of an expression depends both on its own
2502 category and the context it occurs within.
2503
2504 An lvalue is an expression that represents a memory location. These expressions
2505 are [paths](#path-expressions) (which refer to local variables, function and
2506 method arguments, or static variables), dereferences (`*expr`), [indexing
2507 expressions](#index-expressions) (`expr[expr]`), and [field
2508 references](#field-expressions) (`expr.f`). All other expressions are rvalues.
2509
2510 The left operand of an [assignment](#assignment-expressions) or
2511 [compound-assignment](#compound-assignment-expressions) expression is
2512 an lvalue context, as is the single operand of a unary
2513 [borrow](#unary-operator-expressions). The discriminant or subject of
2514 a [match expression](#match-expressions) may be an lvalue context, if
2515 ref bindings are made, but is otherwise an rvalue context. All other
2516 expression contexts are rvalue contexts.
2517
2518 When an lvalue is evaluated in an _lvalue context_, it denotes a memory
2519 location; when evaluated in an _rvalue context_, it denotes the value held _in_
2520 that memory location.
2521
2522 ##### Temporary lifetimes
2523
2524 When an rvalue is used in an lvalue context, a temporary un-named
2525 lvalue is created and used instead. The lifetime of temporary values
2526 is typically the innermost enclosing statement; the tail expression of
2527 a block is considered part of the statement that encloses the block.
2528
2529 When a temporary rvalue is being created that is assigned into a `let`
2530 declaration, however, the temporary is created with the lifetime of
2531 the enclosing block instead, as using the enclosing statement (the
2532 `let` declaration) would be a guaranteed error (since a pointer to the
2533 temporary would be stored into a variable, but the temporary would be
2534 freed before the variable could be used). The compiler uses simple
2535 syntactic rules to decide which values are being assigned into a `let`
2536 binding, and therefore deserve a longer temporary lifetime.
2537
2538 Here are some examples:
2539
2540 - `let x = foo(&temp())`. The expression `temp()` is an rvalue. As it
2541   is being borrowed, a temporary is created which will be freed after
2542   the innermost enclosing statement (the `let` declaration, in this case).
2543 - `let x = temp().foo()`. This is the same as the previous example,
2544   except that the value of `temp()` is being borrowed via autoref on a
2545   method-call. Here we are assuming that `foo()` is an `&self` method
2546   defined in some trait, say `Foo`. In other words, the expression
2547   `temp().foo()` is equivalent to `Foo::foo(&temp())`.
2548 - `let x = &temp()`. Here, the same temporary is being assigned into
2549   `x`, rather than being passed as a parameter, and hence the
2550   temporary's lifetime is considered to be the enclosing block.
2551 - `let x = SomeStruct { foo: &temp() }`. As in the previous case, the
2552   temporary is assigned into a struct which is then assigned into a
2553   binding, and hence it is given the lifetime of the enclosing block.
2554 - `let x = [ &temp() ]`. As in the previous case, the
2555   temporary is assigned into an array which is then assigned into a
2556   binding, and hence it is given the lifetime of the enclosing block.
2557 - `let ref x = temp()`. In this case, the temporary is created using a ref binding,
2558   but the result is the same: the lifetime is extended to the enclosing block.
2559
2560 #### Moved and copied types
2561
2562 When a [local variable](#variables) is used as an
2563 [rvalue](#lvalues,-rvalues-and-temporaries), the variable will be copied
2564 if its type implements `Copy`. All others are moved.
2565
2566 ### Literal expressions
2567
2568 A _literal expression_ consists of one of the [literal](#literals) forms
2569 described earlier. It directly describes a number, character, string, boolean
2570 value, or the unit value.
2571
2572 ```{.literals}
2573 ();        // unit type
2574 "hello";   // string type
2575 '5';       // character type
2576 5;         // integer type
2577 ```
2578
2579 ### Path expressions
2580
2581 A [path](#paths) used as an expression context denotes either a local variable
2582 or an item. Path expressions are [lvalues](#lvalues,-rvalues-and-temporaries).
2583
2584 ### Tuple expressions
2585
2586 Tuples are written by enclosing zero or more comma-separated expressions in
2587 parentheses. They are used to create [tuple-typed](#tuple-types) values.
2588
2589 ```{.tuple}
2590 (0.0, 4.5);
2591 ("a", 4usize, true);
2592 ```
2593
2594 You can disambiguate a single-element tuple from a value in parentheses with a
2595 comma:
2596
2597 ```
2598 (0,); // single-element tuple
2599 (0); // zero in parentheses
2600 ```
2601
2602 ### Structure expressions
2603
2604 There are several forms of structure expressions. A _structure expression_
2605 consists of the [path](#paths) of a [structure item](#structures), followed by
2606 a brace-enclosed list of one or more comma-separated name-value pairs,
2607 providing the field values of a new instance of the structure. A field name
2608 can be any identifier, and is separated from its value expression by a colon.
2609 The location denoted by a structure field is mutable if and only if the
2610 enclosing structure is mutable.
2611
2612 A _tuple structure expression_ consists of the [path](#paths) of a [structure
2613 item](#structures), followed by a parenthesized list of one or more
2614 comma-separated expressions (in other words, the path of a structure item
2615 followed by a tuple expression). The structure item must be a tuple structure
2616 item.
2617
2618 A _unit-like structure expression_ consists only of the [path](#paths) of a
2619 [structure item](#structures).
2620
2621 The following are examples of structure expressions:
2622
2623 ```
2624 # struct Point { x: f64, y: f64 }
2625 # struct TuplePoint(f64, f64);
2626 # mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } }
2627 # struct Cookie; fn some_fn<T>(t: T) {}
2628 Point {x: 10.0, y: 20.0};
2629 TuplePoint(10.0, 20.0);
2630 let u = game::User {name: "Joe", age: 35, score: 100_000};
2631 some_fn::<Cookie>(Cookie);
2632 ```
2633
2634 A structure expression forms a new value of the named structure type. Note
2635 that for a given *unit-like* structure type, this will always be the same
2636 value.
2637
2638 A structure expression can terminate with the syntax `..` followed by an
2639 expression to denote a functional update. The expression following `..` (the
2640 base) must have the same structure type as the new structure type being formed.
2641 The entire expression denotes the result of constructing a new structure (with
2642 the same type as the base expression) with the given values for the fields that
2643 were explicitly specified and the values in the base expression for all other
2644 fields.
2645
2646 ```
2647 # struct Point3d { x: i32, y: i32, z: i32 }
2648 let base = Point3d {x: 1, y: 2, z: 3};
2649 Point3d {y: 0, z: 10, .. base};
2650 ```
2651
2652 ### Block expressions
2653
2654 A _block expression_ is similar to a module in terms of the declarations that
2655 are possible. Each block conceptually introduces a new namespace scope. Use
2656 items can bring new names into scopes and declared items are in scope for only
2657 the block itself.
2658
2659 A block will execute each statement sequentially, and then execute the
2660 expression (if given). If the block ends in a statement, its value is `()`:
2661
2662 ```
2663 let x: () = { println!("Hello."); };
2664 ```
2665
2666 If it ends in an expression, its value and type are that of the expression:
2667
2668 ```
2669 let x: i32 = { println!("Hello."); 5 };
2670
2671 assert_eq!(5, x);
2672 ```
2673
2674 ### Method-call expressions
2675
2676 A _method call_ consists of an expression followed by a single dot, an
2677 identifier, and a parenthesized expression-list. Method calls are resolved to
2678 methods on specific traits, either statically dispatching to a method if the
2679 exact `self`-type of the left-hand-side is known, or dynamically dispatching if
2680 the left-hand-side expression is an indirect [trait object](#trait-objects).
2681
2682 ### Field expressions
2683
2684 A _field expression_ consists of an expression followed by a single dot and an
2685 identifier, when not immediately followed by a parenthesized expression-list
2686 (the latter is a [method call expression](#method-call-expressions)). A field
2687 expression denotes a field of a [structure](#structure-types).
2688
2689 ```{.ignore .field}
2690 mystruct.myfield;
2691 foo().x;
2692 (Struct {a: 10, b: 20}).a;
2693 ```
2694
2695 A field access is an [lvalue](#lvalues,-rvalues-and-temporaries) referring to
2696 the value of that field. When the type providing the field inherits mutability,
2697 it can be [assigned](#assignment-expressions) to.
2698
2699 Also, if the type of the expression to the left of the dot is a
2700 pointer, it is automatically dereferenced as many times as necessary
2701 to make the field access possible. In cases of ambiguity, we prefer
2702 fewer autoderefs to more.
2703
2704 ### Array expressions
2705
2706 An [array](#array,-and-slice-types) _expression_ is written by enclosing zero
2707 or more comma-separated expressions of uniform type in square brackets.
2708
2709 In the `[expr ';' expr]` form, the expression after the `';'` must be a
2710 constant expression that can be evaluated at compile time, such as a
2711 [literal](#literals) or a [static item](#static-items).
2712
2713 ```
2714 [1, 2, 3, 4];
2715 ["a", "b", "c", "d"];
2716 [0; 128];              // array with 128 zeros
2717 [0u8, 0u8, 0u8, 0u8];
2718 ```
2719
2720 ### Index expressions
2721
2722 [Array](#array,-and-slice-types)-typed expressions can be indexed by
2723 writing a square-bracket-enclosed expression (the index) after them. When the
2724 array is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can
2725 be assigned to.
2726
2727 Indices are zero-based, and may be of any integral type. Vector access is
2728 bounds-checked at compile-time for constant arrays being accessed with a constant index value.
2729 Otherwise a check will be performed at run-time that will put the thread in a _panicked state_ if it fails.
2730
2731 ```{should-fail}
2732 ([1, 2, 3, 4])[0];
2733
2734 let x = (["a", "b"])[10]; // compiler error: const index-expr is out of bounds
2735
2736 let n = 10;
2737 let y = (["a", "b"])[n]; // panics
2738
2739 let arr = ["a", "b"];
2740 arr[10]; // panics
2741 ```
2742
2743 Also, if the type of the expression to the left of the brackets is a
2744 pointer, it is automatically dereferenced as many times as necessary
2745 to make the indexing possible. In cases of ambiguity, we prefer fewer
2746 autoderefs to more.
2747
2748 ### Range expressions
2749
2750 The `..` operator will construct an object of one of the `std::ops::Range` variants.
2751
2752 ```
2753 1..2;   // std::ops::Range
2754 3..;    // std::ops::RangeFrom
2755 ..4;    // std::ops::RangeTo
2756 ..;     // std::ops::RangeFull
2757 ```
2758
2759 The following expressions are equivalent.
2760
2761 ```
2762 let x = std::ops::Range {start: 0, end: 10};
2763 let y = 0..10;
2764
2765 assert_eq!(x,y);
2766 ```
2767
2768 ### Unary operator expressions
2769
2770 Rust defines the following unary operators. They are all written as prefix operators,
2771 before the expression they apply to.
2772
2773 * `-`
2774   : Negation. May only be applied to numeric types.
2775 * `*`
2776   : Dereference. When applied to a [pointer](#pointer-types) it denotes the
2777     pointed-to location. For pointers to mutable locations, the resulting
2778     [lvalue](#lvalues,-rvalues-and-temporaries) can be assigned to.
2779     On non-pointer types, it calls the `deref` method of the `std::ops::Deref`
2780     trait, or the `deref_mut` method of the `std::ops::DerefMut` trait (if
2781     implemented by the type and required for an outer expression that will or
2782     could mutate the dereference), and produces the result of dereferencing the
2783     `&` or `&mut` borrowed pointer returned from the overload method.
2784 * `!`
2785   : Logical negation. On the boolean type, this flips between `true` and
2786     `false`. On integer types, this inverts the individual bits in the
2787     two's complement representation of the value.
2788 * `&` and `&mut`
2789   : Borrowing. When applied to an lvalue, these operators produce a
2790     reference (pointer) to the lvalue. The lvalue is also placed into
2791     a borrowed state for the duration of the reference. For a shared
2792     borrow (`&`), this implies that the lvalue may not be mutated, but
2793     it may be read or shared again. For a mutable borrow (`&mut`), the
2794     lvalue may not be accessed in any way until the borrow expires.
2795     If the `&` or `&mut` operators are applied to an rvalue, a
2796     temporary value is created; the lifetime of this temporary value
2797     is defined by [syntactic rules](#temporary-lifetimes).
2798
2799 ### Binary operator expressions
2800
2801 Binary operators expressions are given in terms of [operator
2802 precedence](#operator-precedence).
2803
2804 #### Arithmetic operators
2805
2806 Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
2807 defined in the `std::ops` module of the `std` library. This means that
2808 arithmetic operators can be overridden for user-defined types. The default
2809 meaning of the operators on standard types is given here.
2810
2811 * `+`
2812   : Addition and array/string concatenation.
2813     Calls the `add` method on the `std::ops::Add` trait.
2814 * `-`
2815   : Subtraction.
2816     Calls the `sub` method on the `std::ops::Sub` trait.
2817 * `*`
2818   : Multiplication.
2819     Calls the `mul` method on the `std::ops::Mul` trait.
2820 * `/`
2821   : Quotient.
2822     Calls the `div` method on the `std::ops::Div` trait.
2823 * `%`
2824   : Remainder.
2825     Calls the `rem` method on the `std::ops::Rem` trait.
2826
2827 #### Bitwise operators
2828
2829 Like the [arithmetic operators](#arithmetic-operators), bitwise operators are
2830 syntactic sugar for calls to methods of built-in traits. This means that
2831 bitwise operators can be overridden for user-defined types. The default
2832 meaning of the operators on standard types is given here. Bitwise `&`, `|` and
2833 `^` applied to boolean arguments are equivalent to logical `&&`, `||` and `!=`
2834 evaluated in non-lazy fashion.
2835
2836 * `&`
2837   : Bitwise AND.
2838     Calls the `bitand` method of the `std::ops::BitAnd` trait.
2839 * `|`
2840   : Bitwise inclusive OR.
2841     Calls the `bitor` method of the `std::ops::BitOr` trait.
2842 * `^`
2843   : Bitwise exclusive OR.
2844     Calls the `bitxor` method of the `std::ops::BitXor` trait.
2845 * `<<`
2846   : Left shift.
2847     Calls the `shl` method of the `std::ops::Shl` trait.
2848 * `>>`
2849   : Right shift (arithmetic).
2850     Calls the `shr` method of the `std::ops::Shr` trait.
2851
2852 #### Lazy boolean operators
2853
2854 The operators `||` and `&&` may be applied to operands of boolean type. The
2855 `||` operator denotes logical 'or', and the `&&` operator denotes logical
2856 'and'. They differ from `|` and `&` in that the right-hand operand is only
2857 evaluated when the left-hand operand does not already determine the result of
2858 the expression. That is, `||` only evaluates its right-hand operand when the
2859 left-hand operand evaluates to `false`, and `&&` only when it evaluates to
2860 `true`.
2861
2862 #### Comparison operators
2863
2864 Comparison operators are, like the [arithmetic
2865 operators](#arithmetic-operators), and [bitwise operators](#bitwise-operators),
2866 syntactic sugar for calls to built-in traits. This means that comparison
2867 operators can be overridden for user-defined types. The default meaning of the
2868 operators on standard types is given here.
2869
2870 * `==`
2871   : Equal to.
2872     Calls the `eq` method on the `std::cmp::PartialEq` trait.
2873 * `!=`
2874   : Unequal to.
2875     Calls the `ne` method on the `std::cmp::PartialEq` trait.
2876 * `<`
2877   : Less than.
2878     Calls the `lt` method on the `std::cmp::PartialOrd` trait.
2879 * `>`
2880   : Greater than.
2881     Calls the `gt` method on the `std::cmp::PartialOrd` trait.
2882 * `<=`
2883   : Less than or equal.
2884     Calls the `le` method on the `std::cmp::PartialOrd` trait.
2885 * `>=`
2886   : Greater than or equal.
2887     Calls the `ge` method on the `std::cmp::PartialOrd` trait.
2888
2889 #### Type cast expressions
2890
2891 A type cast expression is denoted with the binary operator `as`.
2892
2893 Executing an `as` expression casts the value on the left-hand side to the type
2894 on the right-hand side.
2895
2896 An example of an `as` expression:
2897
2898 ```
2899 # fn sum(values: &[f64]) -> f64 { 0.0 }
2900 # fn len(values: &[f64]) -> i32 { 0 }
2901
2902 fn average(values: &[f64]) -> f64 {
2903     let sum: f64 = sum(values);
2904     let size: f64 = len(values) as f64;
2905     sum / size
2906 }
2907 ```
2908
2909 Some of the conversions which can be done through the `as` operator
2910 can also be done implicitly at various points in the program, such as
2911 argument passing and assignment to a `let` binding with an explicit
2912 type. Implicit conversions are limited to "harmless" conversions that
2913 do not lose information and which have minimal or no risk of
2914 surprising side-effects on the dynamic execution semantics.
2915
2916 #### Assignment expressions
2917
2918 An _assignment expression_ consists of an
2919 [lvalue](#lvalues,-rvalues-and-temporaries) expression followed by an equals
2920 sign (`=`) and an [rvalue](#lvalues,-rvalues-and-temporaries) expression.
2921
2922 Evaluating an assignment expression [either copies or
2923 moves](#moved-and-copied-types) its right-hand operand to its left-hand
2924 operand.
2925
2926 ```
2927 # let mut x = 0;
2928 # let y = 0;
2929 x = y;
2930 ```
2931
2932 #### Compound assignment expressions
2933
2934 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>` operators may be
2935 composed with the `=` operator. The expression `lval OP= val` is equivalent to
2936 `lval = lval OP val`. For example, `x = x + 1` may be written as `x += 1`.
2937
2938 Any such expression always has the [`unit`](#tuple-types) type.
2939
2940 #### Operator precedence
2941
2942 The precedence of Rust binary operators is ordered as follows, going from
2943 strong to weak:
2944
2945 ```{.text .precedence}
2946 as
2947 * / %
2948 + -
2949 << >>
2950 &
2951 ^
2952 |
2953 == != < > <= >=
2954 &&
2955 ||
2956 = ..
2957 ```
2958
2959 Operators at the same precedence level are evaluated left-to-right. [Unary
2960 operators](#unary-operator-expressions) have the same precedence level and are
2961 stronger than any of the binary operators.
2962
2963 ### Grouped expressions
2964
2965 An expression enclosed in parentheses evaluates to the result of the enclosed
2966 expression. Parentheses can be used to explicitly specify evaluation order
2967 within an expression.
2968
2969 An example of a parenthesized expression:
2970
2971 ```
2972 let x: i32 = (2 + 3) * 4;
2973 ```
2974
2975
2976 ### Call expressions
2977
2978 A _call expression_ invokes a function, providing zero or more input variables
2979 and an optional location to move the function's output into. If the function
2980 eventually returns, then the expression completes.
2981
2982 Some examples of call expressions:
2983
2984 ```
2985 # fn add(x: i32, y: i32) -> i32 { 0 }
2986
2987 let x: i32 = add(1i32, 2i32);
2988 let pi: Result<f32, _> = "3.14".parse();
2989 ```
2990
2991 ### Lambda expressions
2992
2993 A _lambda expression_ (sometimes called an "anonymous function expression")
2994 defines a function and denotes it as a value, in a single expression. A lambda
2995 expression is a pipe-symbol-delimited (`|`) list of identifiers followed by an
2996 expression.
2997
2998 A lambda expression denotes a function that maps a list of parameters
2999 (`ident_list`) onto the expression that follows the `ident_list`. The
3000 identifiers in the `ident_list` are the parameters to the function. These
3001 parameters' types need not be specified, as the compiler infers them from
3002 context.
3003
3004 Lambda expressions are most useful when passing functions as arguments to other
3005 functions, as an abbreviation for defining and capturing a separate function.
3006
3007 Significantly, lambda expressions _capture their environment_, which regular
3008 [function definitions](#functions) do not. The exact type of capture depends
3009 on the [function type](#function-types) inferred for the lambda expression. In
3010 the simplest and least-expensive form (analogous to a ```|| { }``` expression),
3011 the lambda expression captures its environment by reference, effectively
3012 borrowing pointers to all outer variables mentioned inside the function.
3013 Alternately, the compiler may infer that a lambda expression should copy or
3014 move values (depending on their type) from the environment into the lambda
3015 expression's captured environment.
3016
3017 In this example, we define a function `ten_times` that takes a higher-order
3018 function argument, and we then call it with a lambda expression as an argument:
3019
3020 ```
3021 fn ten_times<F>(f: F) where F: Fn(i32) {
3022     for index in 0..10 {
3023         f(index);
3024     }
3025 }
3026
3027 ten_times(|j| println!("hello, {}", j));
3028 ```
3029
3030 ### Infinite loops
3031
3032 A `loop` expression denotes an infinite loop.
3033
3034 A `loop` expression may optionally have a _label_. The label is written as
3035 a lifetime preceding the loop expression, as in `'foo: loop{ }`. If a
3036 label is present, then labeled `break` and `continue` expressions nested
3037 within this loop may exit out of this loop or return control to its head.
3038 See [Break expressions](#break-expressions) and [Continue
3039 expressions](#continue-expressions).
3040
3041 ### Break expressions
3042
3043 A `break` expression has an optional _label_. If the label is absent, then
3044 executing a `break` expression immediately terminates the innermost loop
3045 enclosing it. It is only permitted in the body of a loop. If the label is
3046 present, then `break 'foo` terminates the loop with label `'foo`, which need not
3047 be the innermost label enclosing the `break` expression, but must enclose it.
3048
3049 ### Continue expressions
3050
3051 A `continue` expression has an optional _label_. If the label is absent, then
3052 executing a `continue` expression immediately terminates the current iteration
3053 of the innermost loop enclosing it, returning control to the loop *head*. In
3054 the case of a `while` loop, the head is the conditional expression controlling
3055 the loop. In the case of a `for` loop, the head is the call-expression
3056 controlling the loop. If the label is present, then `continue 'foo` returns
3057 control to the head of the loop with label `'foo`, which need not be the
3058 innermost label enclosing the `break` expression, but must enclose it.
3059
3060 A `continue` expression is only permitted in the body of a loop.
3061
3062 ### While loops
3063
3064 A `while` loop begins by evaluating the boolean loop conditional expression.
3065 If the loop conditional expression evaluates to `true`, the loop body block
3066 executes and control returns to the loop conditional expression. If the loop
3067 conditional expression evaluates to `false`, the `while` expression completes.
3068
3069 An example:
3070
3071 ```
3072 let mut i = 0;
3073
3074 while i < 10 {
3075     println!("hello");
3076     i = i + 1;
3077 }
3078 ```
3079
3080 Like `loop` expressions, `while` loops can be controlled with `break` or
3081 `continue`, and may optionally have a _label_. See [infinite
3082 loops](#infinite-loops), [break expressions](#break-expressions), and
3083 [continue expressions](#continue-expressions) for more information.
3084
3085 ### For expressions
3086
3087 A `for` expression is a syntactic construct for looping over elements provided
3088 by an implementation of `std::iter::IntoIterator`.
3089
3090 An example of a for loop over the contents of an array:
3091
3092 ```
3093 # type Foo = i32;
3094 # fn bar(f: &Foo) { }
3095 # let a = 0;
3096 # let b = 0;
3097 # let c = 0;
3098
3099 let v: &[Foo] = &[a, b, c];
3100
3101 for e in v {
3102     bar(e);
3103 }
3104 ```
3105
3106 An example of a for loop over a series of integers:
3107
3108 ```
3109 # fn bar(b:usize) { }
3110 for i in 0..256 {
3111     bar(i);
3112 }
3113 ```
3114
3115 Like `loop` expressions, `for` loops can be controlled with `break` or
3116 `continue`, and may optionally have a _label_. See [infinite
3117 loops](#infinite-loops), [break expressions](#break-expressions), and
3118 [continue expressions](#continue-expressions) for more information.
3119
3120 ### If expressions
3121
3122 An `if` expression is a conditional branch in program control. The form of an
3123 `if` expression is a condition expression, followed by a consequent block, any
3124 number of `else if` conditions and blocks, and an optional trailing `else`
3125 block. The condition expressions must have type `bool`. If a condition
3126 expression evaluates to `true`, the consequent block is executed and any
3127 subsequent `else if` or `else` block is skipped. If a condition expression
3128 evaluates to `false`, the consequent block is skipped and any subsequent `else
3129 if` condition is evaluated. If all `if` and `else if` conditions evaluate to
3130 `false` then any `else` block is executed.
3131
3132 ### Match expressions
3133
3134 A `match` expression branches on a *pattern*. The exact form of matching that
3135 occurs depends on the pattern. Patterns consist of some combination of
3136 literals, destructured arrays or enum constructors, structures and tuples,
3137 variable binding specifications, wildcards (`..`), and placeholders (`_`). A
3138 `match` expression has a *head expression*, which is the value to compare to
3139 the patterns. The type of the patterns must equal the type of the head
3140 expression.
3141
3142 In a pattern whose head expression has an `enum` type, a placeholder (`_`)
3143 stands for a *single* data field, whereas a wildcard `..` stands for *all* the
3144 fields of a particular variant.
3145
3146 A `match` behaves differently depending on whether or not the head expression
3147 is an [lvalue or an rvalue](#lvalues,-rvalues-and-temporaries). If the head
3148 expression is an rvalue, it is first evaluated into a temporary location, and
3149 the resulting value is sequentially compared to the patterns in the arms until
3150 a match is found. The first arm with a matching pattern is chosen as the branch
3151 target of the `match`, any variables bound by the pattern are assigned to local
3152 variables in the arm's block, and control enters the block.
3153
3154 When the head expression is an lvalue, the match does not allocate a temporary
3155 location (however, a by-value binding may copy or move from the lvalue). When
3156 possible, it is preferable to match on lvalues, as the lifetime of these
3157 matches inherits the lifetime of the lvalue, rather than being restricted to
3158 the inside of the match.
3159
3160 An example of a `match` expression:
3161
3162 ```
3163 let x = 1;
3164
3165 match x {
3166     1 => println!("one"),
3167     2 => println!("two"),
3168     3 => println!("three"),
3169     4 => println!("four"),
3170     5 => println!("five"),
3171     _ => println!("something else"),
3172 }
3173 ```
3174
3175 Patterns that bind variables default to binding to a copy or move of the
3176 matched value (depending on the matched value's type). This can be changed to
3177 bind to a reference by using the `ref` keyword, or to a mutable reference using
3178 `ref mut`.
3179
3180 Subpatterns can also be bound to variables by the use of the syntax `variable @
3181 subpattern`. For example:
3182
3183 ```
3184 let x = 1;
3185
3186 match x {
3187     e @ 1 ... 5 => println!("got a range element {}", e),
3188     _ => println!("anything"),
3189 }
3190 ```
3191
3192 Patterns can also dereference pointers by using the `&`, `&mut` and `box`
3193 symbols, as appropriate. For example, these two matches on `x: &i32` are
3194 equivalent:
3195
3196 ```
3197 # let x = &3;
3198 let y = match *x { 0 => "zero", _ => "some" };
3199 let z = match x { &0 => "zero", _ => "some" };
3200
3201 assert_eq!(y, z);
3202 ```
3203
3204 Multiple match patterns may be joined with the `|` operator. A range of values
3205 may be specified with `...`. For example:
3206
3207 ```
3208 # let x = 2;
3209
3210 let message = match x {
3211     0 | 1  => "not many",
3212     2 ... 9 => "a few",
3213     _      => "lots"
3214 };
3215 ```
3216
3217 Range patterns only work on scalar types (like integers and characters; not
3218 like arrays and structs, which have sub-components). A range pattern may not
3219 be a sub-range of another range pattern inside the same `match`.
3220
3221 Finally, match patterns can accept *pattern guards* to further refine the
3222 criteria for matching a case. Pattern guards appear after the pattern and
3223 consist of a bool-typed expression following the `if` keyword. A pattern guard
3224 may refer to the variables bound within the pattern they follow.
3225
3226 ```
3227 # let maybe_digit = Some(0);
3228 # fn process_digit(i: i32) { }
3229 # fn process_other(i: i32) { }
3230
3231 let message = match maybe_digit {
3232     Some(x) if x < 10 => process_digit(x),
3233     Some(x) => process_other(x),
3234     None => panic!()
3235 };
3236 ```
3237
3238 ### If let expressions
3239
3240 An `if let` expression is semantically identical to an `if` expression but in place
3241 of a condition expression it expects a refutable let statement. If the value of the
3242 expression on the right hand side of the let statement matches the pattern, the corresponding
3243 block will execute, otherwise flow proceeds to the first `else` block that follows.
3244
3245 ```
3246 let dish = ("Ham", "Eggs");
3247
3248 // this body will be skipped because the pattern is refuted
3249 if let ("Bacon", b) = dish {
3250     println!("Bacon is served with {}", b);
3251 }
3252
3253 // this body will execute
3254 if let ("Ham", b) = dish {
3255     println!("Ham is served with {}", b);
3256 }
3257 ```
3258
3259 ### While let loops
3260
3261 A `while let` loop is semantically identical to a `while` loop but in place of a
3262 condition expression it expects a refutable let statement. If the value of the
3263 expression on the right hand side of the let statement matches the pattern, the
3264 loop body block executes and control returns to the pattern matching statement.
3265 Otherwise, the while expression completes.
3266
3267 ### Return expressions
3268
3269 Return expressions are denoted with the keyword `return`. Evaluating a `return`
3270 expression moves its argument into the designated output location for the
3271 current function call, destroys the current function activation frame, and
3272 transfers control to the caller frame.
3273
3274 An example of a `return` expression:
3275
3276 ```
3277 fn max(a: i32, b: i32) -> i32 {
3278     if a > b {
3279         return a;
3280     }
3281     return b;
3282 }
3283 ```
3284
3285 # Type system
3286
3287 ## Types
3288
3289 Every variable, item and value in a Rust program has a type. The _type_ of a
3290 *value* defines the interpretation of the memory holding it.
3291
3292 Built-in types and type-constructors are tightly integrated into the language,
3293 in nontrivial ways that are not possible to emulate in user-defined types.
3294 User-defined types have limited capabilities.
3295
3296 ### Primitive types
3297
3298 The primitive types are the following:
3299
3300 * The boolean type `bool` with values `true` and `false`.
3301 * The machine types (integer and floating-point).
3302 * The machine-dependent integer types.
3303
3304 #### Machine types
3305
3306 The machine types are the following:
3307
3308 * The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from
3309   the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1] and
3310   [0, 2^64 - 1] respectively.
3311
3312 * The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with
3313   values drawn from the integer intervals [-(2^(7)), 2^7 - 1],
3314   [-(2^(15)), 2^15 - 1], [-(2^(31)), 2^31 - 1], [-(2^(63)), 2^63 - 1]
3315   respectively.
3316
3317 * The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and
3318   `f64`, respectively.
3319
3320 #### Machine-dependent integer types
3321
3322 The `usize` type is an unsigned integer type with the same number of bits as the
3323 platform's pointer type. It can represent every memory address in the process.
3324
3325 The `isize` type is a signed integer type with the same number of bits as the
3326 platform's pointer type. The theoretical upper bound on object and array size
3327 is the maximum `isize` value. This ensures that `isize` can be used to calculate
3328 differences between pointers into an object or array and can address every byte
3329 within an object along with one byte past the end.
3330
3331 ### Textual types
3332
3333 The types `char` and `str` hold textual data.
3334
3335 A value of type `char` is a [Unicode scalar value](
3336 http://www.unicode.org/glossary/#unicode_scalar_value) (i.e. a code point that
3337 is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to
3338 0xD7FF or 0xE000 to 0x10FFFF range. A `[char]` array is effectively an UCS-4 /
3339 UTF-32 string.
3340
3341 A value of type `str` is a Unicode string, represented as an array of 8-bit
3342 unsigned bytes holding a sequence of UTF-8 code points. Since `str` is of
3343 unknown size, it is not a _first-class_ type, but can only be instantiated
3344 through a pointer type, such as `&str`.
3345
3346 ### Tuple types
3347
3348 A tuple *type* is a heterogeneous product of other types, called the *elements*
3349 of the tuple. It has no nominal name and is instead structurally typed.
3350
3351 Tuple types and values are denoted by listing the types or values of their
3352 elements, respectively, in a parenthesized, comma-separated list.
3353
3354 Because tuple elements don't have a name, they can only be accessed by
3355 pattern-matching or by using `N` directly as a field to access the
3356 `N`th element.
3357
3358 An example of a tuple type and its use:
3359
3360 ```
3361 type Pair<'a> = (i32, &'a str);
3362 let p: Pair<'static> = (10, "ten");
3363 let (a, b) = p;
3364
3365 assert_eq!(a, 10);
3366 assert_eq!(b, "ten");
3367 assert_eq!(p.0, 10);
3368 assert_eq!(p.1, "ten");
3369 ```
3370
3371 For historical reasons and convenience, the tuple type with no elements (`()`)
3372 is often called â€˜unit’ or â€˜the unit type’.
3373
3374 ### Array, and Slice types
3375
3376 Rust has two different types for a list of items:
3377
3378 * `[T; N]`, an 'array'
3379 * `&[T]`, a 'slice'
3380
3381 An array has a fixed size, and can be allocated on either the stack or the
3382 heap.
3383
3384 A slice is a 'view' into an array. It doesn't own the data it points
3385 to, it borrows it.
3386
3387 Examples:
3388
3389 ```{rust}
3390 // A stack-allocated array
3391 let array: [i32; 3] = [1, 2, 3];
3392
3393 // A heap-allocated array
3394 let vector: Vec<i32> = vec![1, 2, 3];
3395
3396 // A slice into an array
3397 let slice: &[i32] = &vector[..];
3398 ```
3399
3400 As you can see, the `vec!` macro allows you to create a `Vec<T>` easily. The
3401 `vec!` macro is also part of the standard library, rather than the language.
3402
3403 All in-bounds elements of arrays and slices are always initialized, and access
3404 to an array or slice is always bounds-checked.
3405
3406 ### Structure types
3407
3408 A `struct` *type* is a heterogeneous product of other types, called the
3409 *fields* of the type.[^structtype]
3410
3411 [^structtype]: `struct` types are analogous to `struct` types in C,
3412     the *record* types of the ML family,
3413     or the *structure* types of the Lisp family.
3414
3415 New instances of a `struct` can be constructed with a [struct
3416 expression](#structure-expressions).
3417
3418 The memory layout of a `struct` is undefined by default to allow for compiler
3419 optimizations like field reordering, but it can be fixed with the
3420 `#[repr(...)]` attribute. In either case, fields may be given in any order in
3421 a corresponding struct *expression*; the resulting `struct` value will always
3422 have the same memory layout.
3423
3424 The fields of a `struct` may be qualified by [visibility
3425 modifiers](#visibility-and-privacy), to allow access to data in a
3426 structure outside a module.
3427
3428 A _tuple struct_ type is just like a structure type, except that the fields are
3429 anonymous.
3430
3431 A _unit-like struct_ type is like a structure type, except that it has no
3432 fields. The one value constructed by the associated [structure
3433 expression](#structure-expressions) is the only value that inhabits such a
3434 type.
3435
3436 ### Enumerated types
3437
3438 An *enumerated type* is a nominal, heterogeneous disjoint union type, denoted
3439 by the name of an [`enum` item](#enumerations). [^enumtype]
3440
3441 [^enumtype]: The `enum` type is analogous to a `data` constructor declaration in
3442              ML, or a *pick ADT* in Limbo.
3443
3444 An [`enum` item](#enumerations) declares both the type and a number of *variant
3445 constructors*, each of which is independently named and takes an optional tuple
3446 of arguments.
3447
3448 New instances of an `enum` can be constructed by calling one of the variant
3449 constructors, in a [call expression](#call-expressions).
3450
3451 Any `enum` value consumes as much memory as the largest variant constructor for
3452 its corresponding `enum` type.
3453
3454 Enum types cannot be denoted *structurally* as types, but must be denoted by
3455 named reference to an [`enum` item](#enumerations).
3456
3457 ### Recursive types
3458
3459 Nominal types &mdash; [enumerations](#enumerated-types) and
3460 [structures](#structure-types) &mdash; may be recursive. That is, each `enum`
3461 constructor or `struct` field may refer, directly or indirectly, to the
3462 enclosing `enum` or `struct` type itself. Such recursion has restrictions:
3463
3464 * Recursive types must include a nominal type in the recursion
3465   (not mere [type definitions](grammar.html#type-definitions),
3466    or other structural types such as [arrays](#array,-and-slice-types) or [tuples](#tuple-types)).
3467 * A recursive `enum` item must have at least one non-recursive constructor
3468   (in order to give the recursion a basis case).
3469 * The size of a recursive type must be finite;
3470   in other words the recursive fields of the type must be [pointer types](#pointer-types).
3471 * Recursive type definitions can cross module boundaries, but not module *visibility* boundaries,
3472   or crate boundaries (in order to simplify the module system and type checker).
3473
3474 An example of a *recursive* type and its use:
3475
3476 ```
3477 enum List<T> {
3478     Nil,
3479     Cons(T, Box<List<T>>)
3480 }
3481
3482 let a: List<i32> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil))));
3483 ```
3484
3485 ### Pointer types
3486
3487 All pointers in Rust are explicit first-class values. They can be copied,
3488 stored into data structures, and returned from functions. There are two
3489 varieties of pointer in Rust:
3490
3491 * References (`&`)
3492   : These point to memory _owned by some other value_.
3493     A reference type is written `&type`,
3494     or `&'a type` when you need to specify an explicit lifetime.
3495     Copying a reference is a "shallow" operation:
3496     it involves only copying the pointer itself.
3497     Releasing a reference has no effect on the value it points to,
3498     but a reference of a temporary value will keep it alive during the scope
3499     of the reference itself.
3500
3501 * Raw pointers (`*`)
3502   : Raw pointers are pointers without safety or liveness guarantees.
3503     Raw pointers are written as `*const T` or `*mut T`,
3504     for example `*const i32` means a raw pointer to a 32-bit integer.
3505     Copying or dropping a raw pointer has no effect on the lifecycle of any
3506     other value. Dereferencing a raw pointer or converting it to any other
3507     pointer type is an [`unsafe` operation](#unsafe-functions).
3508     Raw pointers are generally discouraged in Rust code;
3509     they exist to support interoperability with foreign code,
3510     and writing performance-critical or low-level functions.
3511
3512 The standard library contains additional 'smart pointer' types beyond references
3513 and raw pointers.
3514
3515 ### Function types
3516
3517 The function type constructor `fn` forms new function types. A function type
3518 consists of a possibly-empty set of function-type modifiers (such as `unsafe`
3519 or `extern`), a sequence of input types and an output type.
3520
3521 An example of a `fn` type:
3522
3523 ```
3524 fn add(x: i32, y: i32) -> i32 {
3525     return x + y;
3526 }
3527
3528 let mut x = add(5,7);
3529
3530 type Binop = fn(i32, i32) -> i32;
3531 let bo: Binop = add;
3532 x = bo(5,7);
3533 ```
3534
3535 #### Function types for specific items
3536
3537 Internal to the compiler, there are also function types that are specific to a particular
3538 function item. In the following snippet, for example, the internal types of the functions
3539 `foo` and `bar` are different, despite the fact that they have the same signature:
3540
3541 ```
3542 fn foo() { }
3543 fn bar() { }
3544 ```
3545
3546 The types of `foo` and `bar` can both be implicitly coerced to the fn
3547 pointer type `fn()`. There is currently no syntax for unique fn types,
3548 though the compiler will emit a type like `fn() {foo}` in error
3549 messages to indicate "the unique fn type for the function `foo`".
3550
3551 ### Closure types
3552
3553 A [lambda expression](#lambda-expressions) produces a closure value with
3554 a unique, anonymous type that cannot be written out.
3555
3556 Depending on the requirements of the closure, its type implements one or
3557 more of the closure traits:
3558
3559 * `FnOnce`
3560   : The closure can be called once. A closure called as `FnOnce`
3561     can move out values from its environment.
3562
3563 * `FnMut`
3564   : The closure can be called multiple times as mutable. A closure called as
3565     `FnMut` can mutate values from its environment. `FnMut` inherits from
3566     `FnOnce` (i.e. anything implementing `FnMut` also implements `FnOnce`).
3567
3568 * `Fn`
3569   : The closure can be called multiple times through a shared reference.
3570     A closure called as `Fn` can neither move out from nor mutate values
3571     from its environment. `Fn` inherits from `FnMut`, which itself
3572     inherits from `FnOnce`.
3573
3574
3575 ### Trait objects
3576
3577 In Rust, a type like `&SomeTrait` or `Box<SomeTrait>` is called a _trait object_.
3578 Each instance of a trait object includes:
3579
3580  - a pointer to an instance of a type `T` that implements `SomeTrait`
3581  - a _virtual method table_, often just called a _vtable_, which contains, for
3582    each method of `SomeTrait` that `T` implements, a pointer to `T`'s
3583    implementation (i.e. a function pointer).
3584
3585 The purpose of trait objects is to permit "late binding" of methods. A call to
3586 a method on a trait object is only resolved to a vtable entry at compile time.
3587 The actual implementation for each vtable entry can vary on an object-by-object
3588 basis.
3589
3590 Note that for a trait object to be instantiated, the trait must be
3591 _object-safe_. Object safety rules are defined in [RFC 255].
3592
3593 [RFC 255]: https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md
3594
3595 Given a pointer-typed expression `E` of type `&T` or `Box<T>`, where `T`
3596 implements trait `R`, casting `E` to the corresponding pointer type `&R` or
3597 `Box<R>` results in a value of the _trait object_ `R`. This result is
3598 represented as a pair of pointers: the vtable pointer for the `T`
3599 implementation of `R`, and the pointer value of `E`.
3600
3601 An example of a trait object:
3602
3603 ```
3604 trait Printable {
3605     fn stringify(&self) -> String;
3606 }
3607
3608 impl Printable for i32 {
3609     fn stringify(&self) -> String { self.to_string() }
3610 }
3611
3612 fn print(a: Box<Printable>) {
3613     println!("{}", a.stringify());
3614 }
3615
3616 fn main() {
3617     print(Box::new(10) as Box<Printable>);
3618 }
3619 ```
3620
3621 In this example, the trait `Printable` occurs as a trait object in both the
3622 type signature of `print`, and the cast expression in `main`.
3623
3624 ### Type parameters
3625
3626 Within the body of an item that has type parameter declarations, the names of
3627 its type parameters are types:
3628
3629 ```ignore
3630 fn to_vec<A: Clone>(xs: &[A]) -> Vec<A> {
3631     if xs.is_empty() {
3632         return vec![];
3633     }
3634     let first: A = xs[0].clone();
3635     let mut rest: Vec<A> = to_vec(&xs[1..]);
3636     rest.insert(0, first);
3637     rest
3638 }
3639 ```
3640
3641 Here, `first` has type `A`, referring to `to_vec`'s `A` type parameter; and `rest`
3642 has type `Vec<A>`, a vector with element type `A`.
3643
3644 ### Self types
3645
3646 The special type `Self` has a meaning within traits and impls. In a trait definition, it refers
3647 to an implicit type parameter representing the "implementing" type. In an impl,
3648 it is an alias for the implementing type. For example, in:
3649
3650 ```
3651 trait Printable {
3652     fn make_string(&self) -> String;
3653 }
3654
3655 impl Printable for String {
3656     fn make_string(&self) -> String {
3657         (*self).clone()
3658     }
3659 }
3660 ```
3661
3662 The notation `&self` is a shorthand for `self: &Self`. In this case,
3663 in the impl, `Self` refers to the value of type `String` that is the
3664 receiver for a call to the method `make_string`.
3665
3666 ## Subtyping
3667
3668 Subtyping is implicit and can occur at any stage in type checking or
3669 inference. Subtyping in Rust is very restricted and occurs only due to
3670 variance with respect to lifetimes and between types with higher ranked
3671 lifetimes. If we were to erase lifetimes from types, then the only subtyping
3672 would be due to type equality.
3673
3674 Consider the following example: string literals always have `'static`
3675 lifetime. Nevertheless, we can assign `s` to `t`:
3676
3677 ```
3678 fn bar<'a>() {
3679     let s: &'static str = "hi";
3680     let t: &'a str = s;
3681 }
3682 ```
3683 Since `'static` "lives longer" than `'a`, `&'static str` is a subtype of
3684 `&'a str`.
3685
3686 ## Type coercions
3687
3688 Coercions are defined in [RFC401]. A coercion is implicit and has no syntax.
3689
3690 [RFC401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md
3691
3692 ### Coercion sites
3693
3694 A coercion can only occur at certain coercion sites in a program; these are
3695 typically places where the desired type is explicit or can be derived by
3696 propagation from explicit types (without type inference). Possible coercion
3697 sites are:
3698
3699 * `let` statements where an explicit type is given.
3700
3701    For example, `128` is coerced to have type `i8` in the following:
3702
3703    ```rust
3704    let _: i8 = 128;
3705    ```
3706
3707 * `static` and `const` statements (similar to `let` statements).
3708
3709 * Arguments for function calls
3710
3711   The value being coerced is the actual parameter, and it is coerced to
3712   the type of the formal parameter.
3713
3714   For example, `128` is coerced to have type `i8` in the following:
3715
3716   ```rust
3717   fn bar(_: i8) { }
3718
3719   fn main() {
3720       bar(128);
3721   }
3722   ```
3723
3724 * Instantiations of struct or variant fields
3725
3726   For example, `128` is coerced to have type `i8` in the following:
3727
3728   ```rust
3729   struct Foo { x: i8 }
3730
3731   fn main() {
3732       Foo { x: 128 };
3733   }
3734   ```
3735
3736 * Function results, either the final line of a block if it is not
3737   semicolon-terminated or any expression in a `return` statement
3738
3739   For example, `128` is coerced to have type `i8` in the following:
3740
3741   ```rust
3742   fn foo() -> i8 {
3743       128
3744   }
3745   ```
3746
3747 If the expression in one of these coercion sites is a coercion-propagating
3748 expression, then the relevant sub-expressions in that expression are also
3749 coercion sites. Propagation recurses from these new coercion sites.
3750 Propagating expressions and their relevant sub-expressions are:
3751
3752 * Array literals, where the array has type `[U; n]`. Each sub-expression in
3753 the array literal is a coercion site for coercion to type `U`.
3754
3755 * Array literals with repeating syntax, where the array has type `[U; n]`. The
3756 repeated sub-expression is a coercion site for coercion to type `U`.
3757
3758 * Tuples, where a tuple is a coercion site to type `(U_0, U_1, ..., U_n)`.
3759 Each sub-expression is a coercion site to the respective type, e.g. the
3760 zeroth sub-expression is a coercion site to type `U_0`.
3761
3762 * Parenthesised sub-expressions (`(e)`): if the expression has type `U`, then
3763 the sub-expression is a coercion site to `U`.
3764
3765 * Blocks: if a block has type `U`, then the last expression in the block (if
3766 it is not semicolon-terminated) is a coercion site to `U`. This includes
3767 blocks which are part of control flow statements, such as `if`/`else`, if
3768 the block has a known type.
3769
3770 ### Coercion types
3771
3772 Coercion is allowed between the following types:
3773
3774 * `T` to `U` if `T` is a subtype of `U` (*reflexive case*)
3775
3776 * `T_1` to `T_3` where `T_1` coerces to `T_2` and `T_2` coerces to `T_3`
3777 (*transitive case*)
3778
3779     Note that this is not fully supported yet
3780
3781 * `&mut T` to `&T`
3782
3783 * `*mut T` to `*const T`
3784
3785 * `&T` to `*const T`
3786
3787 * `&mut T` to `*mut T`
3788
3789 * `&T` to `&U` if `T` implements `Deref<Target = U>`. For example:
3790
3791   ```rust
3792   use std::ops::Deref;
3793
3794   struct CharContainer {
3795       value: char
3796   }
3797
3798   impl Deref for CharContainer {
3799       type Target = char;
3800
3801       fn deref<'a>(&'a self) -> &'a char {
3802           &self.value
3803       }
3804   }
3805
3806   fn foo(arg: &char) {}
3807
3808   fn main() {
3809       let x = &mut CharContainer { value: 'y' };
3810       foo(x); //&mut CharContainer is coerced to &char.
3811   }
3812   ```
3813
3814 * `&mut T` to `&mut U` if `T` implements `DerefMut<Target = U>`.
3815
3816 * TyCtor(`T`) to TyCtor(coerce_inner(`T`)), where TyCtor(`T`) is one of
3817     - `&T`
3818     - `&mut T`
3819     - `*const T`
3820     - `*mut T`
3821     - `Box<T>`
3822
3823     and where
3824     - coerce_inner(`[T, ..n]`) = `[T]`
3825     - coerce_inner(`T`) = `U` where `T` is a concrete type which implements the
3826     trait `U`.
3827
3828     In the future, coerce_inner will be recursively extended to tuples and
3829     structs. In addition, coercions from sub-traits to super-traits will be
3830     added. See [RFC401] for more details.
3831
3832 # Special traits
3833
3834 Several traits define special evaluation behavior.
3835
3836 ## The `Copy` trait
3837
3838 The `Copy` trait changes the semantics of a type implementing it. Values whose
3839 type implements `Copy` are copied rather than moved upon assignment.
3840
3841 ## The `Sized` trait
3842
3843 The `Sized` trait indicates that the size of this type is known at compile-time.
3844
3845 ## The `Drop` trait
3846
3847 The `Drop` trait provides a destructor, to be run whenever a value of this type
3848 is to be destroyed.
3849
3850 ## The `Deref` trait
3851
3852 The `Deref<Target = U>` trait allows a type to implicitly implement all the methods
3853 of the type `U`. When attempting to resolve a method call, the compiler will search
3854 the top-level type for the implementation of the called method. If no such method is
3855 found, `.deref()` is called and the compiler continues to search for the method
3856 implementation in the returned type `U`.
3857
3858 # Memory model
3859
3860 A Rust program's memory consists of a static set of *items* and a *heap*.
3861 Immutable portions of the heap may be safely shared between threads, mutable
3862 portions may not be safely shared, but several mechanisms for effectively-safe
3863 sharing of mutable values, built on unsafe code but enforcing a safe locking
3864 discipline, exist in the standard library.
3865
3866 Allocations in the stack consist of *variables*, and allocations in the heap
3867 consist of *boxes*.
3868
3869 ### Memory allocation and lifetime
3870
3871 The _items_ of a program are those functions, modules and types that have their
3872 value calculated at compile-time and stored uniquely in the memory image of the
3873 rust process. Items are neither dynamically allocated nor freed.
3874
3875 The _heap_ is a general term that describes boxes.  The lifetime of an
3876 allocation in the heap depends on the lifetime of the box values pointing to
3877 it. Since box values may themselves be passed in and out of frames, or stored
3878 in the heap, heap allocations may outlive the frame they are allocated within.
3879
3880 ### Memory ownership
3881
3882 When a stack frame is exited, its local allocations are all released, and its
3883 references to boxes are dropped.
3884
3885 ### Variables
3886
3887 A _variable_ is a component of a stack frame, either a named function parameter,
3888 an anonymous [temporary](#lvalues,-rvalues-and-temporaries), or a named local
3889 variable.
3890
3891 A _local variable_ (or *stack-local* allocation) holds a value directly,
3892 allocated within the stack's memory. The value is a part of the stack frame.
3893
3894 Local variables are immutable unless declared otherwise like: `let mut x = ...`.
3895
3896 Function parameters are immutable unless declared with `mut`. The `mut` keyword
3897 applies only to the following parameter (so `|mut x, y|` and `fn f(mut x:
3898 Box<i32>, y: Box<i32>)` declare one mutable variable `x` and one immutable
3899 variable `y`).
3900
3901 Methods that take either `self` or `Box<Self>` can optionally place them in a
3902 mutable variable by prefixing them with `mut` (similar to regular arguments):
3903
3904 ```
3905 trait Changer {
3906     fn change(mut self) -> Self;
3907     fn modify(mut self: Box<Self>) -> Box<Self>;
3908 }
3909 ```
3910
3911 Local variables are not initialized when allocated; the entire frame worth of
3912 local variables are allocated at once, on frame-entry, in an uninitialized
3913 state. Subsequent statements within a function may or may not initialize the
3914 local variables. Local variables can be used only after they have been
3915 initialized; this is enforced by the compiler.
3916
3917 # Linkage
3918
3919 The Rust compiler supports various methods to link crates together both
3920 statically and dynamically. This section will explore the various methods to
3921 link Rust crates together, and more information about native libraries can be
3922 found in the [ffi section of the book][ffi].
3923
3924 In one session of compilation, the compiler can generate multiple artifacts
3925 through the usage of either command line flags or the `crate_type` attribute.
3926 If one or more command line flag is specified, all `crate_type` attributes will
3927 be ignored in favor of only building the artifacts specified by command line.
3928
3929 * `--crate-type=bin`, `#[crate_type = "bin"]` - A runnable executable will be
3930   produced. This requires that there is a `main` function in the crate which
3931   will be run when the program begins executing. This will link in all Rust and
3932   native dependencies, producing a distributable binary.
3933
3934 * `--crate-type=lib`, `#[crate_type = "lib"]` - A Rust library will be produced.
3935   This is an ambiguous concept as to what exactly is produced because a library
3936   can manifest itself in several forms. The purpose of this generic `lib` option
3937   is to generate the "compiler recommended" style of library. The output library
3938   will always be usable by rustc, but the actual type of library may change from
3939   time-to-time. The remaining output types are all different flavors of
3940   libraries, and the `lib` type can be seen as an alias for one of them (but the
3941   actual one is compiler-defined).
3942
3943 * `--crate-type=dylib`, `#[crate_type = "dylib"]` - A dynamic Rust library will
3944   be produced. This is different from the `lib` output type in that this forces
3945   dynamic library generation. The resulting dynamic library can be used as a
3946   dependency for other libraries and/or executables. This output type will
3947   create `*.so` files on linux, `*.dylib` files on osx, and `*.dll` files on
3948   windows.
3949
3950 * `--crate-type=staticlib`, `#[crate_type = "staticlib"]` - A static system
3951   library will be produced. This is different from other library outputs in that
3952   the Rust compiler will never attempt to link to `staticlib` outputs. The
3953   purpose of this output type is to create a static library containing all of
3954   the local crate's code along with all upstream dependencies. The static
3955   library is actually a `*.a` archive on linux and osx and a `*.lib` file on
3956   windows. This format is recommended for use in situations such as linking
3957   Rust code into an existing non-Rust application because it will not have
3958   dynamic dependencies on other Rust code.
3959
3960 * `--crate-type=rlib`, `#[crate_type = "rlib"]` - A "Rust library" file will be
3961   produced. This is used as an intermediate artifact and can be thought of as a
3962   "static Rust library". These `rlib` files, unlike `staticlib` files, are
3963   interpreted by the Rust compiler in future linkage. This essentially means
3964   that `rustc` will look for metadata in `rlib` files like it looks for metadata
3965   in dynamic libraries. This form of output is used to produce statically linked
3966   executables as well as `staticlib` outputs.
3967
3968 Note that these outputs are stackable in the sense that if multiple are
3969 specified, then the compiler will produce each form of output at once without
3970 having to recompile. However, this only applies for outputs specified by the
3971 same method. If only `crate_type` attributes are specified, then they will all
3972 be built, but if one or more `--crate-type` command line flag is specified,
3973 then only those outputs will be built.
3974
3975 With all these different kinds of outputs, if crate A depends on crate B, then
3976 the compiler could find B in various different forms throughout the system. The
3977 only forms looked for by the compiler, however, are the `rlib` format and the
3978 dynamic library format. With these two options for a dependent library, the
3979 compiler must at some point make a choice between these two formats. With this
3980 in mind, the compiler follows these rules when determining what format of
3981 dependencies will be used:
3982
3983 1. If a static library is being produced, all upstream dependencies are
3984    required to be available in `rlib` formats. This requirement stems from the
3985    reason that a dynamic library cannot be converted into a static format.
3986
3987    Note that it is impossible to link in native dynamic dependencies to a static
3988    library, and in this case warnings will be printed about all unlinked native
3989    dynamic dependencies.
3990
3991 2. If an `rlib` file is being produced, then there are no restrictions on what
3992    format the upstream dependencies are available in. It is simply required that
3993    all upstream dependencies be available for reading metadata from.
3994
3995    The reason for this is that `rlib` files do not contain any of their upstream
3996    dependencies. It wouldn't be very efficient for all `rlib` files to contain a
3997    copy of `libstd.rlib`!
3998
3999 3. If an executable is being produced and the `-C prefer-dynamic` flag is not
4000    specified, then dependencies are first attempted to be found in the `rlib`
4001    format. If some dependencies are not available in an rlib format, then
4002    dynamic linking is attempted (see below).
4003
4004 4. If a dynamic library or an executable that is being dynamically linked is
4005    being produced, then the compiler will attempt to reconcile the available
4006    dependencies in either the rlib or dylib format to create a final product.
4007
4008    A major goal of the compiler is to ensure that a library never appears more
4009    than once in any artifact. For example, if dynamic libraries B and C were
4010    each statically linked to library A, then a crate could not link to B and C
4011    together because there would be two copies of A. The compiler allows mixing
4012    the rlib and dylib formats, but this restriction must be satisfied.
4013
4014    The compiler currently implements no method of hinting what format a library
4015    should be linked with. When dynamically linking, the compiler will attempt to
4016    maximize dynamic dependencies while still allowing some dependencies to be
4017    linked in via an rlib.
4018
4019    For most situations, having all libraries available as a dylib is recommended
4020    if dynamically linking. For other situations, the compiler will emit a
4021    warning if it is unable to determine which formats to link each library with.
4022
4023 In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for
4024 all compilation needs, and the other options are just available if more
4025 fine-grained control is desired over the output format of a Rust crate.
4026
4027 # Appendix: Rationales and design trade-offs
4028
4029 *TODO*.
4030
4031 # Appendix: Influences
4032
4033 Rust is not a particularly original language, with design elements coming from
4034 a wide range of sources. Some of these are listed below (including elements
4035 that have since been removed):
4036
4037 * SML, OCaml: algebraic data types, pattern matching, type inference,
4038   semicolon statement separation
4039 * C++: references, RAII, smart pointers, move semantics, monomorphisation,
4040   memory model
4041 * ML Kit, Cyclone: region based memory management
4042 * Haskell (GHC): typeclasses, type families
4043 * Newsqueak, Alef, Limbo: channels, concurrency
4044 * Erlang: message passing, thread failure, ~~linked thread failure~~,
4045   ~~lightweight concurrency~~
4046 * Swift: optional bindings
4047 * Scheme: hygienic macros
4048 * C#: attributes
4049 * Ruby: ~~block syntax~~
4050 * NIL, Hermes: ~~typestate~~
4051 * [Unicode Annex #31](http://www.unicode.org/reports/tr31/): identifier and
4052   pattern syntax
4053
4054 [ffi]: book/ffi.html
4055 [plugin]: book/compiler-plugins.html