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