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