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