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