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