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