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