5 This document is the primary reference for the Rust programming language. It
6 provides three kinds of material:
8 - Chapters that formally define the language grammar and, for each
9 construct, informally describe its semantics and give examples of its
11 - Chapters that informally describe the memory model, concurrency model,
12 runtime services, linkage model and debugging facilities.
13 - Appendix chapters providing rationale and references to languages that
14 influenced the design.
16 This document does not serve as an introduction to the language. Background
17 familiarity with the language is assumed. A separate [guide] is available to
18 help acquire such background familiarity.
20 This document also does not serve as a reference to the [standard] library
21 included in the language distribution. Those libraries are documented
22 separately by extracting documentation attributes from their source code. Many
23 of the features that one might expect to be language features are library
24 features in Rust, so what you're looking for may be there, not here.
27 [standard]: std/index.html
31 Rust's grammar is defined over Unicode codepoints, each conventionally denoted
32 `U+XXXX`, for 4 or more hexadecimal digits `X`. _Most_ of Rust's grammar is
33 confined to the ASCII range of Unicode, and is described in this document by a
34 dialect of Extended Backus-Naur Form (EBNF), specifically a dialect of EBNF
35 supported by common automated LL(k) parsing tools such as `llgen`, rather than
36 the dialect given in ISO 14977. The dialect can be defined self-referentially
41 rule : nonterminal ':' productionrule ';' ;
42 productionrule : production [ '|' production ] * ;
44 term : element repeats ;
45 element : LITERAL | IDENTIFIER | '[' productionrule ']' ;
46 repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;
51 - Whitespace in the grammar is ignored.
52 - Square brackets are used to group rules.
53 - `LITERAL` is a single printable ASCII character, or an escaped hexadecimal
54 ASCII code of the form `\xQQ`, in single quotes, denoting the corresponding
55 Unicode codepoint `U+00QQ`.
56 - `IDENTIFIER` is a nonempty string of ASCII letters and underscores.
57 - The `repeat` forms apply to the adjacent `element`, and are as follows:
58 - `?` means zero or one repetition
59 - `*` means zero or more repetitions
60 - `+` means one or more repetitions
61 - NUMBER trailing a repeat symbol gives a maximum repetition count
62 - NUMBER on its own gives an exact repetition count
64 This EBNF dialect should hopefully be familiar to many readers.
66 ## Unicode productions
68 A few productions in Rust's grammar permit Unicode codepoints outside the ASCII
69 range. We define these productions in terms of character properties specified
70 in the Unicode standard, rather than in terms of ASCII-range codepoints. The
71 section [Special Unicode Productions](#special-unicode-productions) lists these
74 ## String table productions
76 Some rules in the grammar — notably [unary
77 operators](#unary-operator-expressions), [binary
78 operators](#binary-operator-expressions), and [keywords](#keywords) — are
79 given in a simplified form: as a listing of a table of unquoted, printable
80 whitespace-separated strings. These cases form a subset of the rules regarding
81 the [token](#tokens) rule, and are assumed to be the result of a
82 lexical-analysis phase feeding the parser, driven by a DFA, operating over the
83 disjunction of all such string table entries.
85 When such a string enclosed in double-quotes (`"`) occurs inside the grammar,
86 it is an implicit reference to a single member of such a string table
87 production. See [tokens](#tokens) for more information.
93 Rust input is interpreted as a sequence of Unicode codepoints encoded in UTF-8.
94 Most Rust grammar rules are defined in terms of printable ASCII-range
95 codepoints, but a small number are defined in terms of Unicode properties or
96 explicit codepoint lists. [^inputformat]
98 [^inputformat]: Substitute definitions for the special Unicode productions are
99 provided to the grammar verifier, restricted to ASCII range, when verifying the
100 grammar in this document.
102 ## Special Unicode Productions
104 The following productions in the Rust grammar are defined in terms of Unicode
105 properties: `ident`, `non_null`, `non_star`, `non_eol`, `non_slash_or_star`,
106 `non_single_quote` and `non_double_quote`.
110 The `ident` production is any nonempty Unicode string of the following form:
112 - The first character has property `XID_start`
113 - The remaining characters have property `XID_continue`
115 that does _not_ occur in the set of [keywords](#keywords).
117 > **Note**: `XID_start` and `XID_continue` as character properties cover the
118 > character ranges used to form the more familiar C and Java language-family
121 ### Delimiter-restricted productions
123 Some productions are defined by exclusion of particular Unicode characters:
125 - `non_null` is any single Unicode character aside from `U+0000` (null)
126 - `non_eol` is `non_null` restricted to exclude `U+000A` (`'\n'`)
127 - `non_star` is `non_null` restricted to exclude `U+002A` (`*`)
128 - `non_slash_or_star` is `non_null` restricted to exclude `U+002F` (`/`) and `U+002A` (`*`)
129 - `non_single_quote` is `non_null` restricted to exclude `U+0027` (`'`)
130 - `non_double_quote` is `non_null` restricted to exclude `U+0022` (`"`)
135 comment : block_comment | line_comment ;
136 block_comment : "/*" block_comment_body * "*/" ;
137 block_comment_body : [block_comment | character] * ;
138 line_comment : "//" non_eol * ;
141 Comments in Rust code follow the general C++ style of line and block-comment
142 forms. Nested block comments are supported.
144 Line comments beginning with exactly _three_ slashes (`///`), and block
145 comments beginning with exactly one repeated asterisk in the block-open
146 sequence (`/**`), are interpreted as a special syntax for `doc`
147 [attributes](#attributes). That is, they are equivalent to writing
148 `#[doc="..."]` around the body of the comment (this includes the comment
149 characters themselves, ie `/// Foo` turns into `#[doc="/// Foo"]`).
151 `//!` comments apply to the parent of the comment, rather than the item that
152 follows. `//!` comments are usually used to display information on the crate
155 Non-doc comments are interpreted as a form of whitespace.
160 whitespace_char : '\x20' | '\x09' | '\x0a' | '\x0d' ;
161 whitespace : [ whitespace_char | comment ] + ;
164 The `whitespace_char` production is any nonempty Unicode string consisting of
165 any of the following Unicode characters: `U+0020` (space, `' '`), `U+0009`
166 (tab, `'\t'`), `U+000A` (LF, `'\n'`), `U+000D` (CR, `'\r'`).
168 Rust is a "free-form" language, meaning that all forms of whitespace serve only
169 to separate _tokens_ in the grammar, and have no semantic significance.
171 A Rust program has identical meaning if each whitespace element is replaced
172 with any other legal whitespace element, such as a single space character.
177 simple_token : keyword | unop | binop ;
178 token : simple_token | ident | literal | symbol | whitespace token ;
181 Tokens are primitive productions in the grammar defined by regular
182 (non-recursive) languages. "Simple" tokens are given in [string table
183 production](#string-table-productions) form, and occur in the rest of the
184 grammar as double-quoted strings. Other tokens have exact rules given.
188 <p id="keyword-table-marker"></p>
191 |----------|----------|----------|----------|--------|
192 | abstract | alignof | as | be | box |
193 | break | const | continue | crate | do |
194 | else | enum | extern | false | final |
195 | fn | for | if | impl | in |
196 | let | loop | match | mod | move |
197 | mut | offsetof | once | override | priv |
198 | proc | pub | pure | ref | return |
199 | sizeof | static | self | struct | super |
200 | true | trait | type | typeof | unsafe |
201 | unsized | use | virtual | where | while |
205 Each of these keywords has special meaning in its grammar, and all of them are
206 excluded from the `ident` rule.
208 Note that some of these keywords are reserved, and do not currently do
213 A literal is an expression consisting of a single token, rather than a sequence
214 of tokens, that immediately and directly denotes the value it evaluates to,
215 rather than referring to it by name or some other evaluation rule. A literal is
216 a form of constant expression, so is evaluated (primarily) at compile time.
220 literal : [ string_lit | char_lit | byte_string_lit | byte_lit | num_lit ] lit_suffix ?;
223 The optional suffix is only used for certain numeric literals, but is
224 reserved for future extension, that is, the above gives the lexical
225 grammar, but a Rust parser will reject everything but the 12 special
226 cases mentioned in [Number literals](#number-literals) below.
230 ##### Characters and strings
232 | | Example | Number of `#` pairs allowed | Available characters | Escapes | Equivalent to |
233 |---|---------|-----------------------------|----------------------|---------|---------------|
234 | [Character](#character-literals) | `'H'` | `N/A` | All unicode | `\'` & [Byte escapes](#byte-escapes) & [Unicode escapes](#unicode-escapes) | `N/A` |
235 | [String](#string-literals) | `"hello"` | `N/A` | All unicode | `\"` & [Byte escapes](#byte-escapes) & [Unicode escapes](#unicode-escapes) | `N/A` |
236 | [Raw](#raw-string-literals) | `r##"hello"##` | `0...` | All unicode | `N/A` | `N/A` |
237 | [Byte](#byte-literals) | `b'H'` | `N/A` | All ASCII | `\'` & [Byte escapes](#byte-escapes) | `u8` |
238 | [Byte string](#byte-string-literals) | `b"hello"` | `N/A` | All ASCII | `\"` & [Byte escapes](#byte-escapes) | `&'static [u8]` |
239 | [Raw byte string](#raw-byte-string-literals) | `br##"hello"##` | `0...` | All ASCII | `N/A` | `&'static [u8]` (unsure...not stated) |
245 | `\x7F` | 8-bit character code (exactly 2 digits) |
247 | `\r` | Carriage return |
251 ##### Unicode escapes
254 | `\u7FFF` | 16-bit character code (exactly 4 digits) |
255 | `\U7EEEFFFF` | 32-bit character code (exactly 8 digits) |
259 | [Number literals](#number-literals)`*` | Example | Exponentiation | Suffixes |
260 |----------------------------------------|---------|----------------|----------|
261 | Decimal integer | `98_222i` | `N/A` | Integer suffixes |
262 | Hex integer | `0xffi` | `N/A` | Integer suffixes |
263 | Octal integer | `0o77i` | `N/A` | Integer suffixes |
264 | Binary integer | `0b1111_0000i` | `N/A` | Integer suffixes |
265 | Floating-point | `123.0E+77f64` | `Optional` | Floating-point suffixes |
267 `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64`
270 | Integer | Floating-point |
271 |---------|----------------|
272 | `i` (`int`), `u` (`uint`), `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64` | `f32`, `f64` |
274 #### Character and string literals
277 char_lit : '\x27' char_body '\x27' ;
278 string_lit : '"' string_body * '"' | 'r' raw_string ;
280 char_body : non_single_quote
281 | '\x5c' [ '\x27' | common_escape | unicode_escape ] ;
283 string_body : non_double_quote
284 | '\x5c' [ '\x22' | common_escape | unicode_escape ] ;
285 raw_string : '"' raw_string_body '"' | '#' raw_string '#' ;
287 common_escape : '\x5c'
288 | 'n' | 'r' | 't' | '0'
290 unicode_escape : 'u' hex_digit 4
293 hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
294 | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
296 oct_digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' ;
297 dec_digit : '0' | nonzero_dec ;
298 nonzero_dec: '1' | '2' | '3' | '4'
299 | '5' | '6' | '7' | '8' | '9' ;
302 ##### Character literals
304 A _character literal_ is a single Unicode character enclosed within two
305 `U+0027` (single-quote) characters, with the exception of `U+0027` itself,
306 which must be _escaped_ by a preceding U+005C character (`\`).
308 ##### String literals
310 A _string literal_ is a sequence of any Unicode characters enclosed within two
311 `U+0022` (double-quote) characters, with the exception of `U+0022` itself,
312 which must be _escaped_ by a preceding `U+005C` character (`\`), or a _raw
315 ##### Character escapes
317 Some additional _escapes_ are available in either character or non-raw string
318 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
321 * An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is
322 followed by exactly two _hex digits_. It denotes the Unicode codepoint
323 equal to the provided hex value.
324 * A _16-bit codepoint escape_ starts with `U+0075` (`u`) and is followed
325 by exactly four _hex digits_. It denotes the Unicode codepoint equal to
326 the provided hex value.
327 * A _32-bit codepoint escape_ starts with `U+0055` (`U`) and is followed
328 by exactly eight _hex digits_. It denotes the Unicode codepoint equal to
329 the provided hex value.
330 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
331 (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF),
332 `U+000D` (CR) or `U+0009` (HT) respectively.
333 * The _backslash escape_ is the character `U+005C` (`\`) which must be
334 escaped in order to denote *itself*.
336 ##### Raw string literals
338 Raw string literals do not process any escapes. They start with the character
339 `U+0072` (`r`), followed by zero or more of the character `U+0023` (`#`) and a
340 `U+0022` (double-quote) character. The _raw string body_ is not defined in the
341 EBNF grammar above: it can contain any sequence of Unicode characters and is
342 terminated only by another `U+0022` (double-quote) character, followed by the
343 same number of `U+0023` (`#`) characters that preceded the opening `U+0022`
344 (double-quote) character.
346 All Unicode characters contained in the raw string body represent themselves,
347 the characters `U+0022` (double-quote) (except when followed by at least as
348 many `U+0023` (`#`) characters as were used to start the raw string literal) or
349 `U+005C` (`\`) do not have any special meaning.
351 Examples for string literals:
354 "foo"; r"foo"; // foo
355 "\"foo\""; r#""foo""#; // "foo"
358 r##"foo #"# bar"##; // foo #"# bar
360 "\x52"; "R"; r"R"; // R
361 "\\x52"; r"\x52"; // \x52
364 #### Byte and byte string literals
367 byte_lit : "b\x27" byte_body '\x27' ;
368 byte_string_lit : "b\x22" string_body * '\x22' | "br" raw_byte_string ;
370 byte_body : ascii_non_single_quote
371 | '\x5c' [ '\x27' | common_escape ] ;
373 byte_string_body : ascii_non_double_quote
374 | '\x5c' [ '\x22' | common_escape ] ;
375 raw_byte_string : '"' raw_byte_string_body '"' | '#' raw_byte_string '#' ;
381 A _byte literal_ is a single ASCII character (in the `U+0000` to `U+007F`
382 range) enclosed within two `U+0027` (single-quote) characters, with the
383 exception of `U+0027` itself, which must be _escaped_ by a preceding U+005C
384 character (`\`), or a single _escape_. It is equivalent to a `u8` unsigned
385 8-bit integer _number literal_.
387 ##### Byte string literals
389 A _byte string literal_ is a sequence of ASCII characters and _escapes_
390 enclosed within two `U+0022` (double-quote) characters, with the exception of
391 `U+0022` itself, which must be _escaped_ by a preceding `U+005C` character
392 (`\`), or a _raw byte string literal_. It is equivalent to a `&'static [u8]`
393 borrowed array of unsigned 8-bit integers.
395 Some additional _escapes_ are available in either byte or non-raw byte string
396 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
399 * An _byte escape_ escape starts with `U+0078` (`x`) and is
400 followed by exactly two _hex digits_. It denotes the byte
401 equal to the provided hex value.
402 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
403 (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF),
404 `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.
405 * The _backslash escape_ is the character `U+005C` (`\`) which must be
406 escaped in order to denote its ASCII encoding `0x5C`.
408 ##### Raw byte string literals
410 Raw byte string literals do not process any escapes. They start with the
411 character `U+0062` (`b`), followed by `U+0072` (`r`), followed by zero or more
412 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character. The
413 _raw string body_ is not defined in the EBNF grammar above: it can contain any
414 sequence of ASCII characters and is terminated only by another `U+0022`
415 (double-quote) character, followed by the same number of `U+0023` (`#`)
416 characters that preceded the opening `U+0022` (double-quote) character. A raw
417 byte string literal can not contain any non-ASCII byte.
419 All characters contained in the raw string body represent their ASCII encoding,
420 the characters `U+0022` (double-quote) (except when followed by at least as
421 many `U+0023` (`#`) characters as were used to start the raw string literal) or
422 `U+005C` (`\`) do not have any special meaning.
424 Examples for byte string literals:
427 b"foo"; br"foo"; // foo
428 b"\"foo\""; br#""foo""#; // "foo"
431 br##"foo #"# bar"##; // foo #"# bar
433 b"\x52"; b"R"; br"R"; // R
434 b"\\x52"; br"\x52"; // \x52
440 num_lit : nonzero_dec [ dec_digit | '_' ] * float_suffix ?
441 | '0' [ [ dec_digit | '_' ] * float_suffix ?
442 | 'b' [ '1' | '0' | '_' ] +
443 | 'o' [ oct_digit | '_' ] +
444 | 'x' [ hex_digit | '_' ] + ] ;
446 float_suffix : [ exponent | '.' dec_lit exponent ? ] ? ;
448 exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
449 dec_lit : [ dec_digit | '_' ] + ;
452 A _number literal_ is either an _integer literal_ or a _floating-point
453 literal_. The grammar for recognizing the two kinds of literals is mixed.
455 ##### Integer literals
457 An _integer literal_ has one of four forms:
459 * A _decimal literal_ starts with a *decimal digit* and continues with any
460 mixture of *decimal digits* and _underscores_.
461 * A _hex literal_ starts with the character sequence `U+0030` `U+0078`
462 (`0x`) and continues as any mixture of hex digits and underscores.
463 * An _octal literal_ starts with the character sequence `U+0030` `U+006F`
464 (`0o`) and continues as any mixture of octal digits and underscores.
465 * A _binary literal_ starts with the character sequence `U+0030` `U+0062`
466 (`0b`) and continues as any mixture of binary digits and underscores.
468 Like any literal, an integer literal may be followed (immediately,
469 without any spaces) by an _integer suffix_, which forcibly sets the
470 type of the literal. There are 10 valid values for an integer suffix:
472 * The `i` and `u` suffixes give the literal type `int` or `uint`,
474 * Each of the signed and unsigned machine types `u8`, `i8`,
475 `u16`, `i16`, `u32`, `i32`, `u64` and `i64`
476 give the literal the corresponding machine type.
478 The type of an _unsuffixed_ integer literal is determined by type inference.
479 If an integer type can be _uniquely_ determined from the surrounding program
480 context, the unsuffixed integer literal has that type. If the program context
481 underconstrains the type, it is considered a static type error; if the program
482 context overconstrains the type, it is also considered a static type error.
484 Examples of integer literals of various forms:
491 0o70_i16; // type i16
492 0b1111_1111_1001_0000_i32; // type i32
495 ##### Floating-point literals
497 A _floating-point literal_ has one of two forms:
499 * Two _decimal literals_ separated by a period
500 character `U+002E` (`.`), with an optional _exponent_ trailing after the
501 second decimal literal.
502 * A single _decimal literal_ followed by an _exponent_.
504 By default, a floating-point literal has a generic type, and, like integer
505 literals, the type must be uniquely determined from the context. There are two valid
506 _floating-point suffixes_, `f32` and `f64` (the 32-bit and 64-bit floating point
507 types), which explicitly determine the type of the literal.
509 Examples of floating-point literals of various forms:
512 123.0f64; // type f64
515 12E+99_f64; // type f64
518 ##### Boolean literals
520 The two values of the boolean type are written `true` and `false`.
526 | '#' | '[' | ']' | '(' | ')' | '{' | '}'
530 Symbols are a general class of printable [token](#tokens) that play structural
531 roles in a variety of grammar productions. They are catalogued here for
532 completeness as the set of remaining miscellaneous printable tokens that do not
533 otherwise appear as [unary operators](#unary-operator-expressions), [binary
534 operators](#binary-operator-expressions), or [keywords](#keywords).
540 expr_path : [ "::" ] ident [ "::" expr_path_tail ] + ;
541 expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
544 type_path : ident [ type_path_tail ] + ;
545 type_path_tail : '<' type_expr [ ',' type_expr ] + '>'
549 A _path_ is a sequence of one or more path components _logically_ separated by
550 a namespace qualifier (`::`). If a path consists of only one component, it may
551 refer to either an [item](#items) or a [slot](#memory-slots) in a local control
552 scope. If a path has multiple components, it refers to an item.
554 Every item has a _canonical path_ within its crate, but the path naming an item
555 is only meaningful within a given crate. There is no global namespace across
556 crates; an item's canonical path merely identifies it within the crate.
558 Two examples of simple paths consisting of only identifier components:
565 Path components are usually [identifiers](#identifiers), but the trailing
566 component of a path may be an angle-bracket-enclosed list of type arguments. In
567 [expression](#expressions) context, the type argument list is given after a
568 final (`::`) namespace qualifier in order to disambiguate it from a relational
569 expression involving the less-than symbol (`<`). In type expression context,
570 the final namespace qualifier is omitted.
572 Two examples of paths with type arguments:
575 # struct HashMap<K, V>;
577 # fn id<T>(t: T) -> T { t }
578 type T = HashMap<int,String>; // Type arguments used in a type expression
579 let x = id::<int>(10); // Type arguments used in a call expression
583 Paths can be denoted with various leading qualifiers to change the meaning of
586 * Paths starting with `::` are considered to be global paths where the
587 components of the path start being resolved from the crate root. Each
588 identifier in the path must resolve to an item.
596 ::a::foo(); // call a's foo function
602 * Paths starting with the keyword `super` begin resolution relative to the
603 parent module. Each further identifier must resolve to an item
611 super::a::foo(); // call a's foo function
617 * Paths starting with the keyword `self` begin resolution relative to the
618 current module. Each further identifier must resolve to an item.
630 A number of minor features of Rust are not central enough to have their own
631 syntax, and yet are not implementable as functions. Instead, they are given
632 names, and invoked through a consistent syntax: `name!(...)`. Examples include:
634 * `format!` : format data into a string
635 * `env!` : look up an environment variable's value at compile time
636 * `file!`: return the path to the file being compiled
637 * `stringify!` : pretty-print the Rust expression given as an argument
638 * `include!` : include the Rust expression in the given file
639 * `include_str!` : include the contents of the given file as a string
640 * `include_bin!` : include the contents of the given file as a binary blob
641 * `error!`, `warn!`, `info!`, `debug!` : provide diagnostic information.
643 All of the above extensions are expressions with values.
645 Users of `rustc` can define new syntax extensions in two ways:
647 * [Compiler plugins](guide-plugin.html#syntax-extensions) can include arbitrary
648 Rust code that manipulates syntax trees at compile time.
650 * [Macros](guide-macros.html) define new syntax in a higher-level,
656 expr_macro_rules : "macro_rules" '!' ident '(' macro_rule * ')' ;
657 macro_rule : '(' matcher * ')' "=>" '(' transcriber * ')' ';' ;
658 matcher : '(' matcher * ')' | '[' matcher * ']'
659 | '{' matcher * '}' | '$' ident ':' ident
660 | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]
661 | non_special_token ;
662 transcriber : '(' transcriber * ')' | '[' transcriber * ']'
663 | '{' transcriber * '}' | '$' ident
664 | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]
665 | non_special_token ;
668 User-defined syntax extensions are called "macros", and the `macro_rules`
669 syntax extension defines them. Currently, user-defined macros can expand to
670 expressions, statements, items, or patterns.
672 (A `sep_token` is any token other than `*` and `+`. A `non_special_token` is
673 any token other than a delimiter or `$`.)
675 The macro expander looks up macro invocations by name, and tries each macro
676 rule in turn. It transcribes the first successful match. Matching and
677 transcription are closely related to each other, and we will describe them
682 The macro expander matches and transcribes every token that does not begin with
683 a `$` literally, including delimiters. For parsing reasons, delimiters must be
684 balanced, but they are otherwise not special.
686 In the matcher, `$` _name_ `:` _designator_ matches the nonterminal in the Rust
687 syntax named by _designator_. Valid designators are `item`, `block`, `stmt`,
688 `pat`, `expr`, `ty` (type), `ident`, `path`, `matchers` (lhs of the `=>` in
689 macro rules), `tt` (rhs of the `=>` in macro rules). In the transcriber, the
690 designator is already known, and so only the name of a matched nonterminal
691 comes after the dollar sign.
693 In both the matcher and transcriber, the Kleene star-like operator indicates
694 repetition. The Kleene star operator consists of `$` and parens, optionally
695 followed by a separator token, followed by `*` or `+`. `*` means zero or more
696 repetitions, `+` means at least one repetition. The parens are not matched or
697 transcribed. On the matcher side, a name is bound to _all_ of the names it
698 matches, in a structure that mimics the structure of the repetition encountered
699 on a successful match. The job of the transcriber is to sort that structure
702 The rules for transcription of these repetitions are called "Macro By Example".
703 Essentially, one "layer" of repetition is discharged at a time, and all of them
704 must be discharged by the time a name is transcribed. Therefore, `( $( $i:ident
705 ),* ) => ( $i )` is an invalid macro, but `( $( $i:ident ),* ) => ( $( $i:ident
706 ),* )` is acceptable (if trivial).
708 When Macro By Example encounters a repetition, it examines all of the `$`
709 _name_ s that occur in its body. At the "current layer", they all must repeat
710 the same number of times, so ` ( $( $i:ident ),* ; $( $j:ident ),* ) => ( $(
711 ($i,$j) ),* )` is valid if given the argument `(a,b,c ; d,e,f)`, but not
712 `(a,b,c ; d,e)`. The repetition walks through the choices at that layer in
713 lockstep, so the former input transcribes to `( (a,d), (b,e), (c,f) )`.
715 Nested repetitions are allowed.
717 ### Parsing limitations
719 The parser used by the macro system is reasonably powerful, but the parsing of
720 Rust syntax is restricted in two ways:
722 1. The parser will always parse as much as possible. If it attempts to match
723 `$i:expr [ , ]` against `8 [ , ]`, it will attempt to parse `i` as an array
724 index operation and fail. Adding a separator can solve this problem.
725 2. The parser must have eliminated all ambiguity by the time it reaches a `$`
726 _name_ `:` _designator_. This requirement most often affects name-designator
727 pairs when they occur at the beginning of, or immediately after, a `$(...)*`;
728 requiring a distinctive token in front can solve the problem.
730 ## Syntax extensions useful for the macro author
732 * `log_syntax!` : print out the arguments at compile time
733 * `trace_macros!` : supply `true` or `false` to enable or disable macro expansion logging
734 * `stringify!` : turn the identifier argument into a string literal
735 * `concat!` : concatenates a comma-separated list of literals
736 * `concat_idents!` : create a new identifier by concatenating the arguments
738 # Crates and source files
740 Rust is a *compiled* language. Its semantics obey a *phase distinction*
741 between compile-time and run-time. Those semantic rules that have a *static
742 interpretation* govern the success or failure of compilation. We refer to
743 these rules as "static semantics". Semantic rules called "dynamic semantics"
744 govern the behavior of programs at run-time. A program that fails to compile
745 due to violation of a compile-time rule has no defined dynamic semantics; the
746 compiler should halt with an error report, and produce no executable artifact.
748 The compilation model centers on artifacts called _crates_. Each compilation
749 processes a single crate in source form, and if successful, produces a single
750 crate in binary form: either an executable or a library.[^cratesourcefile]
752 [^cratesourcefile]: A crate is somewhat analogous to an *assembly* in the
753 ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit*
754 in the Owens and Flatt module system, or a *configuration* in Mesa.
756 A _crate_ is a unit of compilation and linking, as well as versioning,
757 distribution and runtime loading. A crate contains a _tree_ of nested
758 [module](#modules) scopes. The top level of this tree is a module that is
759 anonymous (from the point of view of paths within the module) and any item
760 within a crate has a canonical [module path](#paths) denoting its location
761 within the crate's module tree.
763 The Rust compiler is always invoked with a single source file as input, and
764 always produces a single output crate. The processing of that source file may
765 result in other source files being loaded as modules. Source files have the
768 A Rust source file describes a module, the name and location of which —
769 in the module tree of the current crate — are defined from outside the
770 source file: either by an explicit `mod_item` in a referencing source file, or
771 by the name of the crate itself.
773 Each source file contains a sequence of zero or more `item` definitions, and
774 may optionally begin with any number of `attributes` that apply to the
775 containing module. Attributes on the anonymous crate module define important
776 metadata that influences the behavior of the compiler.
779 # #![allow(unused_attribute)]
781 #![crate_name = "projx"]
783 // Specify the output type
784 #![crate_type = "lib"]
787 #![warn(non_camel_case_types)]
790 A crate that contains a `main` function can be compiled to an executable. If a
791 `main` function is present, its return type must be [`unit`](#primitive-types)
792 and it must take no arguments.
794 # Items and attributes
796 Crates contain [items](#items), each of which may have some number of
797 [attributes](#attributes) attached to it.
802 item : mod_item | fn_item | type_item | struct_item | enum_item
803 | static_item | trait_item | impl_item | extern_block ;
806 An _item_ is a component of a crate; some module items can be defined in crate
807 files, but most are defined in source files. Items are organized within a crate
808 by a nested set of [modules](#modules). Every crate has a single "outermost"
809 anonymous module; all further items within the crate have [paths](#paths)
810 within the module tree of the crate.
812 Items are entirely determined at compile-time, generally remain fixed during
813 execution, and may reside in read-only memory.
815 There are several kinds of item:
817 * [modules](#modules)
818 * [functions](#functions)
819 * [type definitions](#type-definitions)
820 * [structures](#structures)
821 * [enumerations](#enumerations)
822 * [static items](#static-items)
824 * [implementations](#implementations)
826 Some items form an implicit scope for the declaration of sub-items. In other
827 words, within a function or module, declarations of items can (in many cases)
828 be mixed with the statements, control blocks, and similar artifacts that
829 otherwise compose the item body. The meaning of these scoped items is the same
830 as if the item was declared outside the scope — it is still a static item
831 — except that the item's *path name* within the module namespace is
832 qualified by the name of the enclosing item, or is private to the enclosing
833 item (in the case of functions). The grammar specifies the exact locations in
834 which sub-item declarations may appear.
838 All items except modules may be *parameterized* by type. Type parameters are
839 given as a comma-separated list of identifiers enclosed in angle brackets
840 (`<...>`), after the name of the item and before its definition. The type
841 parameters of an item are considered "part of the name", not part of the type
842 of the item. A referencing [path](#paths) must (in principle) provide type
843 arguments as a list of comma-separated types enclosed within angle brackets, in
844 order to refer to the type-parameterized item. In practice, the type-inference
845 system can usually infer such argument types from context. There are no
846 general type-parametric types, only type-parametric items. That is, Rust has
847 no notion of type abstraction: there are no first-class "forall" types.
852 mod_item : "mod" ident ( ';' | '{' mod '}' );
853 mod : [ view_item | item ] * ;
856 A module is a container for zero or more [view items](#view-items) and zero or
857 more [items](#items). The view items manage the visibility of the items defined
858 within the module, as well as the visibility of names from outside the module
859 when referenced from inside the module.
861 A _module item_ is a module, surrounded in braces, named, and prefixed with the
862 keyword `mod`. A module item introduces a new, named module into the tree of
863 modules making up a crate. Modules can nest arbitrarily.
865 An example of a module:
869 type Complex = (f64, f64);
870 fn sin(f: f64) -> f64 {
874 fn cos(f: f64) -> f64 {
878 fn tan(f: f64) -> f64 {
885 Modules and types share the same namespace. Declaring a named type with
886 the same name as a module in scope is forbidden: that is, a type definition,
887 trait, struct, enumeration, or type parameter can't shadow the name of a module
888 in scope, or vice versa.
890 A module without a body is loaded from an external file, by default with the
891 same name as the module, plus the `.rs` extension. When a nested submodule is
892 loaded from an external file, it is loaded from a subdirectory path that
893 mirrors the module hierarchy.
896 // Load the `vec` module from `vec.rs`
900 // Load the `local_data` module from `task/local_data.rs`
905 The directories and files used for loading external file modules can be
906 influenced with the `path` attribute.
909 #[path = "task_files"]
911 // Load the `local_data` module from `task_files/tls.rs`
920 view_item : extern_crate_decl | use_decl ;
923 A view item manages the namespace of a module. View items do not define new
924 items, but rather, simply change other items' visibility. There are two
927 * [`extern crate` declarations](#extern-crate-declarations)
928 * [`use` declarations](#use-declarations)
930 ##### Extern crate declarations
933 extern_crate_decl : "extern" "crate" crate_name
934 crate_name: ident | ( string_lit as ident )
937 An _`extern crate` declaration_ specifies a dependency on an external crate.
938 The external crate is then bound into the declaring scope as the `ident`
939 provided in the `extern_crate_decl`.
941 The external crate is resolved to a specific `soname` at compile time, and a
942 runtime linkage requirement to that `soname` is passed to the linker for
943 loading at runtime. The `soname` is resolved at compile time by scanning the
944 compiler's library path and matching the optional `crateid` provided as a
945 string literal against the `crateid` attributes that were declared on the
946 external crate when it was compiled. If no `crateid` is provided, a default
947 `name` attribute is assumed, equal to the `ident` given in the
950 Three examples of `extern crate` declarations:
955 extern crate std; // equivalent to: extern crate std as std;
957 extern crate "std" as ruststd; // linking to 'std' under another name
960 ##### Use declarations
963 use_decl : "pub" ? "use" [ path "as" ident
966 path_glob : ident [ "::" [ path_glob
968 | '{' path_item [ ',' path_item ] * '}' ;
970 path_item : ident | "mod" ;
973 A _use declaration_ creates one or more local name bindings synonymous with
974 some other [path](#paths). Usually a `use` declaration is used to shorten the
975 path required to refer to a module item. These declarations may appear at the
976 top of [modules](#modules) and [blocks](#blocks).
978 > **Note**: Unlike in many languages,
979 > `use` declarations in Rust do *not* declare linkage dependency with external crates.
980 > Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies.
982 Use declarations support a number of convenient shortcuts:
984 * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
985 * Simultaneously binding a list of paths differing only in their final element,
986 using the glob-like brace syntax `use a::b::{c,d,e,f};`
987 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
989 * Simultaneously binding a list of paths differing only in their final element
990 and their immediate parent module, using the `mod` keyword, such as
991 `use a::b::{mod, c, d};`
993 An example of `use` declarations:
996 use std::iter::range_step;
997 use std::option::Option::{Some, None};
998 use std::collections::hash_map::{mod, HashMap};
1001 fn bar(map1: HashMap<String, uint>, map2: hash_map::HashMap<String, uint>){}
1004 // Equivalent to 'std::iter::range_step(0u, 10u, 2u);'
1005 range_step(0u, 10u, 2u);
1007 // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
1008 // std::option::Option::None]);'
1009 foo(vec![Some(1.0f64), None]);
1011 // Both `hash_map` and `HashMap` are in scope.
1012 let map1 = HashMap::new();
1013 let map2 = hash_map::HashMap::new();
1018 Like items, `use` declarations are private to the containing module, by
1019 default. Also like items, a `use` declaration can be public, if qualified by
1020 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
1021 public `use` declaration can therefore _redirect_ some public name to a
1022 different target definition: even a definition with a private canonical path,
1023 inside a different module. If a sequence of such redirections form a cycle or
1024 cannot be resolved unambiguously, they represent a compile-time error.
1026 An example of re-exporting:
1031 pub use quux::foo::{bar, baz};
1040 In this example, the module `quux` re-exports two public names defined in
1043 Also note that the paths contained in `use` items are relative to the crate
1044 root. So, in the previous example, the `use` refers to `quux::foo::{bar,
1045 baz}`, and not simply to `foo::{bar, baz}`. This also means that top-level
1046 module declarations should be at the crate root if direct usage of the declared
1047 modules within `use` items is desired. It is also possible to use `self` and
1048 `super` at the beginning of a `use` item to refer to the current and direct
1049 parent modules respectively. All rules regarding accessing declared modules in
1050 `use` declarations applies to both module declarations and `extern crate`
1053 An example of what will and will not work for `use` items:
1056 # #![allow(unused_imports)]
1057 use foo::core::iter; // good: foo is at the root of the crate
1058 use foo::baz::foobaz; // good: foo is at the root of the crate
1063 use foo::core::iter; // good: foo is at crate root
1064 // use core::iter; // bad: native is not at the crate root
1065 use self::baz::foobaz; // good: self refers to module 'foo'
1066 use foo::bar::foobar; // good: foo is at crate root
1073 use super::bar::foobar; // good: super refers to module 'foo'
1083 A _function item_ defines a sequence of [statements](#statements) and an
1084 optional final [expression](#expressions), along with a name and a set of
1085 parameters. Functions are declared with the keyword `fn`. Functions declare a
1086 set of *input* [*slots*](#memory-slots) as parameters, through which the caller
1087 passes arguments into the function, and an *output* [*slot*](#memory-slots)
1088 through which the function passes results back to the caller.
1090 A function may also be copied into a first class *value*, in which case the
1091 value has the corresponding [*function type*](#function-types), and can be used
1092 otherwise exactly as a function item (with a minor additional cost of calling
1093 the function indirectly).
1095 Every control path in a function logically ends with a `return` expression or a
1096 diverging expression. If the outermost block of a function has a
1097 value-producing expression in its final-expression position, that expression is
1098 interpreted as an implicit `return` expression applied to the final-expression.
1100 An example of a function:
1103 fn add(x: int, y: int) -> int {
1108 As with `let` bindings, function arguments are irrefutable patterns, so any
1109 pattern that is valid in a let binding is also valid as an argument.
1112 fn first((value, _): (int, int)) -> int { value }
1116 #### Generic functions
1118 A _generic function_ allows one or more _parameterized types_ to appear in its
1119 signature. Each type parameter must be explicitly declared, in an
1120 angle-bracket-enclosed, comma-separated list following the function name.
1123 fn iter<T>(seq: &[T], f: |T|) {
1124 for elt in seq.iter() { f(elt); }
1126 fn map<T, U>(seq: &[T], f: |T| -> U) -> Vec<U> {
1127 let mut acc = vec![];
1128 for elt in seq.iter() { acc.push(f(elt)); }
1133 Inside the function signature and body, the name of the type parameter can be
1134 used as a type name.
1136 When a generic function is referenced, its type is instantiated based on the
1137 context of the reference. For example, calling the `iter` function defined
1138 above on `[1, 2]` will instantiate type parameter `T` with `int`, and require
1139 the closure parameter to have type `fn(int)`.
1141 The type parameters can also be explicitly supplied in a trailing
1142 [path](#paths) component after the function name. This might be necessary if
1143 there is not sufficient context to determine the type parameters. For example,
1144 `mem::size_of::<u32>() == 4`.
1146 Since a parameter type is opaque to the generic function, the set of operations
1147 that can be performed on it is limited. Values of parameter type can only be
1151 fn id<T>(x: T) -> T { x }
1154 Similarly, [trait](#traits) bounds can be specified for type parameters to
1155 allow methods with that trait to be called on values of that type.
1159 Unsafe operations are those that potentially violate the memory-safety
1160 guarantees of Rust's static semantics.
1162 The following language level features cannot be used in the safe subset of
1165 - Dereferencing a [raw pointer](#pointer-types).
1166 - Reading or writing a [mutable static variable](#mutable-statics).
1167 - Calling an unsafe function (including an intrinsic or foreign function).
1169 ##### Unsafe functions
1171 Unsafe functions are functions that are not safe in all contexts and/or for all
1172 possible inputs. Such a function must be prefixed with the keyword `unsafe` and
1173 can only be called from an `unsafe` block or another `unsafe` function.
1177 A block of code can be prefixed with the `unsafe` keyword, to permit calling
1178 `unsafe` functions or dereferencing raw pointers within a safe function.
1180 When a programmer has sufficient conviction that a sequence of potentially
1181 unsafe operations is actually safe, they can encapsulate that sequence (taken
1182 as a whole) within an `unsafe` block. The compiler will consider uses of such
1183 code safe, in the surrounding context.
1185 Unsafe blocks are used to wrap foreign libraries, make direct use of hardware
1186 or implement features not directly present in the language. For example, Rust
1187 provides the language features necessary to implement memory-safe concurrency
1188 in the language but the implementation of tasks and message passing is in the
1191 Rust's type system is a conservative approximation of the dynamic safety
1192 requirements, so in some cases there is a performance cost to using safe code.
1193 For example, a doubly-linked list is not a tree structure and can only be
1194 represented with reference-counted pointers in safe code. By using `unsafe`
1195 blocks to represent the reverse links as raw pointers, it can be implemented
1198 ##### Behavior considered undefined
1200 The following is a list of behavior which is forbidden in all Rust code,
1201 including within `unsafe` blocks and `unsafe` functions. Type checking provides
1202 the guarantee that these issues are never caused by safe code.
1205 * Dereferencing a null/dangling raw pointer
1206 * Mutating an immutable value/reference without `UnsafeCell`
1207 * Reads of [undef](http://llvm.org/docs/LangRef.html#undefined-values)
1208 (uninitialized) memory
1209 * Breaking the [pointer aliasing
1210 rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules)
1211 with raw pointers (a subset of the rules used by C)
1212 * Invoking undefined behavior via compiler intrinsics:
1213 * Indexing outside of the bounds of an object with `std::ptr::offset`
1214 (`offset` intrinsic), with
1215 the exception of one byte past the end which is permitted.
1216 * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`
1217 instrinsics) on overlapping buffers
1218 * Invalid values in primitive types, even in private fields/locals:
1219 * Dangling/null references or boxes
1220 * A value other than `false` (0) or `true` (1) in a `bool`
1221 * A discriminant in an `enum` not included in the type definition
1222 * A value in a `char` which is a surrogate or above `char::MAX`
1223 * non-UTF-8 byte sequences in a `str`
1224 * Unwinding into Rust from foreign code or unwinding from Rust into foreign
1225 code. Rust's failure system is not compatible with exception handling in
1226 other languages. Unwinding must be caught and handled at FFI boundaries.
1228 ##### Behaviour not considered unsafe
1230 This is a list of behaviour not considered *unsafe* in Rust terms, but that may
1234 * Reading data from private fields (`std::repr`)
1235 * Leaks due to reference count cycles, even in the global heap
1236 * Exiting without calling destructors
1238 * Accessing/modifying the file system
1239 * Unsigned integer overflow (well-defined as wrapping)
1240 * Signed integer overflow (well-defined as two's complement representation
1243 #### Diverging functions
1245 A special kind of function can be declared with a `!` character where the
1246 output slot type would normally be. For example:
1249 fn my_err(s: &str) -> ! {
1255 We call such functions "diverging" because they never return a value to the
1256 caller. Every control path in a diverging function must end with a `panic!()` or
1257 a call to another diverging function on every control path. The `!` annotation
1258 does *not* denote a type. Rather, the result type of a diverging function is a
1259 special type called $\bot$ ("bottom") that unifies with any type. Rust has no
1262 It might be necessary to declare a diverging function because as mentioned
1263 previously, the typechecker checks that every control path in a function ends
1264 with a [`return`](#return-expressions) or diverging expression. So, if `my_err`
1265 were declared without the `!` annotation, the following code would not
1269 # fn my_err(s: &str) -> ! { panic!() }
1271 fn f(i: int) -> int {
1276 my_err("Bad number!");
1281 This will not compile without the `!` annotation on `my_err`, since the `else`
1282 branch of the conditional in `f` does not return an `int`, as required by the
1283 signature of `f`. Adding the `!` annotation to `my_err` informs the
1284 typechecker that, should control ever enter `my_err`, no further type judgments
1285 about `f` need to hold, since control will never resume in any context that
1286 relies on those judgments. Thus the return type on `f` only needs to reflect
1287 the `if` branch of the conditional.
1289 #### Extern functions
1291 Extern functions are part of Rust's foreign function interface, providing the
1292 opposite functionality to [external blocks](#external-blocks). Whereas
1293 external blocks allow Rust code to call foreign code, extern functions with
1294 bodies defined in Rust code _can be called by foreign code_. They are defined
1295 in the same way as any other Rust function, except that they have the `extern`
1299 // Declares an extern fn, the ABI defaults to "C"
1300 extern fn new_int() -> int { 0 }
1302 // Declares an extern fn with "stdcall" ABI
1303 extern "stdcall" fn new_int_stdcall() -> int { 0 }
1306 Unlike normal functions, extern fns have an `extern "ABI" fn()`. This is the
1307 same type as the functions declared in an extern block.
1310 # extern fn new_int() -> int { 0 }
1311 let fptr: extern "C" fn() -> int = new_int;
1314 Extern functions may be called directly from Rust code as Rust uses large,
1315 contiguous stack segments like C.
1317 ### Type definitions
1319 A _type definition_ defines a new name for an existing [type](#types). Type
1320 definitions are declared with the keyword `type`. Every value has a single,
1321 specific type; the type-specified aspects of a value include:
1323 * Whether the value is composed of sub-values or is indivisible.
1324 * Whether the value represents textual or numerical information.
1325 * Whether the value represents integral or floating-point information.
1326 * The sequence of memory operations required to access the value.
1327 * The [kind](#type-kinds) of the type.
1329 For example, the type `(u8, u8)` defines the set of immutable values that are
1330 composite pairs, each containing two unsigned 8-bit integers accessed by
1331 pattern-matching and laid out in memory with the `x` component preceding the
1335 type Point = (u8, u8);
1336 let p: Point = (41, 68);
1341 A _structure_ is a nominal [structure type](#structure-types) defined with the
1344 An example of a `struct` item and its use:
1347 struct Point {x: int, y: int}
1348 let p = Point {x: 10, y: 11};
1352 A _tuple structure_ is a nominal [tuple type](#tuple-types), also defined with
1353 the keyword `struct`. For example:
1356 struct Point(int, int);
1357 let p = Point(10, 11);
1358 let px: int = match p { Point(x, _) => x };
1361 A _unit-like struct_ is a structure without any fields, defined by leaving off
1362 the list of fields entirely. Such types will have a single value, just like
1363 the [unit value `()`](#unit-and-boolean-literals) of the unit type. For
1368 let c = [Cookie, Cookie, Cookie, Cookie];
1371 The precise memory layout of a structure is not specified. One can specify a
1372 particular layout using the [`repr` attribute](#ffi-attributes).
1376 An _enumeration_ is a simultaneous definition of a nominal [enumerated
1377 type](#enumerated-types) as well as a set of *constructors*, that can be used
1378 to create or pattern-match values of the corresponding enumerated type.
1380 Enumerations are declared with the keyword `enum`.
1382 An example of an `enum` item and its use:
1390 let mut a: Animal = Animal::Dog;
1394 Enumeration constructors can have either named or unnamed fields:
1397 # #![feature(struct_variant)]
1401 Cat { name: String, weight: f64 }
1404 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
1405 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
1409 In this example, `Cat` is a _struct-like enum variant_,
1410 whereas `Dog` is simply called an enum variant.
1415 const_item : "const" ident ':' type '=' expr ';' ;
1418 A *constant item* is a named _constant value_ which is not associated with a
1419 specific memory location in the program. Constants are essentially inlined
1420 wherever they are used, meaning that they are copied directly into the relevant
1421 context when used. References to the same constant are not necessarily
1422 guaranteed to refer to the same memory address.
1424 Constant values must not have destructors, and otherwise permit most forms of
1425 data. Constants may refer to the address of other constants, in which case the
1426 address will have the `static` lifetime. The compiler is, however, still at
1427 liberty to translate the constant many times, so the address referred to may not
1430 Constants must be explicitly typed. The type may be `bool`, `char`, a number, or
1431 a type derived from those primitive types. The derived types are references with
1432 the `static` lifetime, fixed-size arrays, tuples, enum variants, and structs.
1435 const BIT1: uint = 1 << 0;
1436 const BIT2: uint = 1 << 1;
1438 const BITS: [uint, ..2] = [BIT1, BIT2];
1439 const STRING: &'static str = "bitstring";
1441 struct BitsNStrings<'a> {
1442 mybits: [uint, ..2],
1446 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
1455 static_item : "static" ident ':' type '=' expr ';' ;
1458 A *static item* is similar to a *constant*, except that it represents a precise
1459 memory location in the program. A static is never "inlined" at the usage site,
1460 and all references to it refer to the same memory location. Static items have
1461 the `static` lifetime, which outlives all other lifetimes in a Rust program.
1462 Static items may be placed in read-only memory if they do not contain any
1463 interior mutability.
1465 Statics may contain interior mutability through the `UnsafeCell` language item.
1466 All access to a static is safe, but there are a number of restrictions on
1469 * Statics may not contain any destructors.
1470 * The types of static values must ascribe to `Sync` to allow threadsafe access.
1471 * Statics may not refer to other statics by value, only by reference.
1472 * Constants cannot refer to statics.
1474 Constants should in general be preferred over statics, unless large amounts of
1475 data are being stored, or single-address and mutability properties are required.
1478 use std::sync::atomic;
1480 // Note that INIT_ATOMIC_UINT is a *const*, but it may be used to initialize a
1481 // static. This static can be modified, so it is not placed in read-only memory.
1482 static COUNTER: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
1484 // This table is a candidate to be placed in read-only memory.
1485 static TABLE: &'static [uint] = &[1, 2, 3, /* ... */];
1487 for slot in TABLE.iter() {
1488 println!("{}", slot);
1490 COUNTER.fetch_add(1, atomic::SeqCst);
1493 #### Mutable statics
1495 If a static item is declared with the `mut` keyword, then it is allowed to
1496 be modified by the program. One of Rust's goals is to make concurrency bugs
1497 hard to run into, and this is obviously a very large source of race conditions
1498 or other bugs. For this reason, an `unsafe` block is required when either
1499 reading or writing a mutable static variable. Care should be taken to ensure
1500 that modifications to a mutable static are safe with respect to other tasks
1501 running in the same process.
1503 Mutable statics are still very useful, however. They can be used with C
1504 libraries and can also be bound from C libraries (in an `extern` block).
1507 # fn atomic_add(_: &mut uint, _: uint) -> uint { 2 }
1509 static mut LEVELS: uint = 0;
1511 // This violates the idea of no shared state, and this doesn't internally
1512 // protect against races, so this function is `unsafe`
1513 unsafe fn bump_levels_unsafe1() -> uint {
1519 // Assuming that we have an atomic_add function which returns the old value,
1520 // this function is "safe" but the meaning of the return value may not be what
1521 // callers expect, so it's still marked as `unsafe`
1522 unsafe fn bump_levels_unsafe2() -> uint {
1523 return atomic_add(&mut LEVELS, 1);
1527 Mutable statics have the same restrictions as normal statics, except that the
1528 type of the value is not required to ascribe to `Sync`.
1532 A _trait_ describes a set of method types.
1534 Traits can include default implementations of methods, written in terms of some
1535 unknown [`self` type](#self-types); the `self` type may either be completely
1536 unspecified, or constrained by some other trait.
1538 Traits are implemented for specific types through separate
1539 [implementations](#implementations).
1542 # type Surface = int;
1543 # type BoundingBox = int;
1545 fn draw(&self, Surface);
1546 fn bounding_box(&self) -> BoundingBox;
1550 This defines a trait with two methods. All values that have
1551 [implementations](#implementations) of this trait in scope can have their
1552 `draw` and `bounding_box` methods called, using `value.bounding_box()`
1553 [syntax](#method-call-expressions).
1555 Type parameters can be specified for a trait to make it generic. These appear
1556 after the trait name, using the same syntax used in [generic
1557 functions](#generic-functions).
1561 fn len(&self) -> uint;
1562 fn elt_at(&self, n: uint) -> T;
1563 fn iter(&self, |T|);
1567 Generic functions may use traits as _bounds_ on their type parameters. This
1568 will have two effects: only types that have the trait may instantiate the
1569 parameter, and within the generic function, the methods of the trait can be
1570 called on values that have the parameter's type. For example:
1573 # type Surface = int;
1574 # trait Shape { fn draw(&self, Surface); }
1575 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
1581 Traits also define an [object type](#object-types) with the same name as the
1582 trait. Values of this type are created by [casting](#type-cast-expressions)
1583 pointer values (pointing to a type for which an implementation of the given
1584 trait is in scope) to pointers to the trait name, used as a type.
1588 # impl Shape for int { }
1589 # let mycircle = 0i;
1590 let myshape: Box<Shape> = box mycircle as Box<Shape>;
1593 The resulting value is a box containing the value that was cast, along with
1594 information that identifies the methods of the implementation that was used.
1595 Values with a trait type can have [methods called](#method-call-expressions) on
1596 them, for any method in the trait, and can be used to instantiate type
1597 parameters that are bounded by the trait.
1599 Trait methods may be static, which means that they lack a `self` argument.
1600 This means that they can only be called with function call syntax (`f(x)`) and
1601 not method call syntax (`obj.f()`). The way to refer to the name of a static
1602 method is to qualify it with the trait name, treating the trait name like a
1603 module. For example:
1607 fn from_int(n: int) -> Self;
1610 fn from_int(n: int) -> f64 { n as f64 }
1612 let x: f64 = Num::from_int(42);
1615 Traits may inherit from other traits. For example, in
1618 trait Shape { fn area() -> f64; }
1619 trait Circle : Shape { fn radius() -> f64; }
1622 the syntax `Circle : Shape` means that types that implement `Circle` must also
1623 have an implementation for `Shape`. Multiple supertraits are separated by `+`,
1624 `trait Circle : Shape + PartialEq { }`. In an implementation of `Circle` for a
1625 given type `T`, methods can refer to `Shape` methods, since the typechecker
1626 checks that any type with an implementation of `Circle` also has an
1627 implementation of `Shape`.
1629 In type-parameterized functions, methods of the supertrait may be called on
1630 values of subtrait-bound type parameters. Referring to the previous example of
1631 `trait Circle : Shape`:
1634 # trait Shape { fn area(&self) -> f64; }
1635 # trait Circle : Shape { fn radius(&self) -> f64; }
1636 fn radius_times_area<T: Circle>(c: T) -> f64 {
1637 // `c` is both a Circle and a Shape
1638 c.radius() * c.area()
1642 Likewise, supertrait methods may also be called on trait objects.
1645 # trait Shape { fn area(&self) -> f64; }
1646 # trait Circle : Shape { fn radius(&self) -> f64; }
1647 # impl Shape for int { fn area(&self) -> f64 { 0.0 } }
1648 # impl Circle for int { fn radius(&self) -> f64 { 0.0 } }
1650 let mycircle = box mycircle as Box<Circle>;
1651 let nonsense = mycircle.radius() * mycircle.area();
1656 An _implementation_ is an item that implements a [trait](#traits) for a
1659 Implementations are defined with the keyword `impl`.
1662 # struct Point {x: f64, y: f64};
1663 # type Surface = int;
1664 # struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
1665 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
1666 # fn do_draw_circle(s: Surface, c: Circle) { }
1672 impl Shape for Circle {
1673 fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
1674 fn bounding_box(&self) -> BoundingBox {
1675 let r = self.radius;
1676 BoundingBox{x: self.center.x - r, y: self.center.y - r,
1677 width: 2.0 * r, height: 2.0 * r}
1682 It is possible to define an implementation without referring to a trait. The
1683 methods in such an implementation can only be used as direct calls on the
1684 values of the type that the implementation targets. In such an implementation,
1685 the trait type and `for` after `impl` are omitted. Such implementations are
1686 limited to nominal types (enums, structs), and the implementation must appear
1687 in the same module or a sub-module as the `self` type:
1690 struct Point {x: int, y: int}
1694 println!("Point is at ({}, {})", self.x, self.y);
1698 let my_point = Point {x: 10, y:11};
1702 When a trait _is_ specified in an `impl`, all methods declared as part of the
1703 trait must be implemented, with matching types and type parameter counts.
1705 An implementation can take type parameters, which can be different from the
1706 type parameters taken by the trait it implements. Implementation parameters
1707 are written after the `impl` keyword.
1711 impl<T> Seq<T> for Vec<T> {
1714 impl Seq<bool> for u32 {
1715 /* Treat the integer as a sequence of bits */
1722 extern_block_item : "extern" '{' extern_block '}' ;
1723 extern_block : [ foreign_fn ] * ;
1726 External blocks form the basis for Rust's foreign function interface.
1727 Declarations in an external block describe symbols in external, non-Rust
1730 Functions within external blocks are declared in the same way as other Rust
1731 functions, with the exception that they may not have a body and are instead
1732 terminated by a semicolon.
1736 use libc::{c_char, FILE};
1739 fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE;
1744 Functions within external blocks may be called by Rust code, just like
1745 functions defined in Rust. The Rust compiler automatically translates between
1746 the Rust ABI and the foreign ABI.
1748 A number of [attributes](#attributes) control the behavior of external blocks.
1750 By default external blocks assume that the library they are calling uses the
1751 standard C "cdecl" ABI. Other ABIs may be specified using an `abi` string, as
1755 // Interface to the Windows API
1756 extern "stdcall" { }
1759 The `link` attribute allows the name of the library to be specified. When
1760 specified the compiler will attempt to link against the native library of the
1764 #[link(name = "crypto")]
1768 The type of a function declared in an extern block is `extern "abi" fn(A1, ...,
1769 An) -> R`, where `A1...An` are the declared types of its arguments and `R` is
1770 the declared return type.
1772 ## Visibility and Privacy
1774 These two terms are often used interchangeably, and what they are attempting to
1775 convey is the answer to the question "Can this item be used at this location?"
1777 Rust's name resolution operates on a global hierarchy of namespaces. Each level
1778 in the hierarchy can be thought of as some item. The items are one of those
1779 mentioned above, but also include external crates. Declaring or defining a new
1780 module can be thought of as inserting a new tree into the hierarchy at the
1781 location of the definition.
1783 To control whether interfaces can be used across modules, Rust checks each use
1784 of an item to see whether it should be allowed or not. This is where privacy
1785 warnings are generated, or otherwise "you used a private item of another module
1786 and weren't allowed to."
1788 By default, everything in Rust is *private*, with one exception. Enum variants
1789 in a `pub` enum are also public by default. You are allowed to alter this
1790 default visibility with the `priv` keyword. When an item is declared as `pub`,
1791 it can be thought of as being accessible to the outside world. For example:
1795 // Declare a private struct
1798 // Declare a public struct with a private field
1803 // Declare a public enum with two public variants
1805 PubliclyAccessibleState,
1806 PubliclyAccessibleState2,
1810 With the notion of an item being either public or private, Rust allows item
1811 accesses in two cases:
1813 1. If an item is public, then it can be used externally through any of its
1815 2. If an item is private, it may be accessed by the current module and its
1818 These two cases are surprisingly powerful for creating module hierarchies
1819 exposing public APIs while hiding internal implementation details. To help
1820 explain, here's a few use cases and what they would entail.
1822 * A library developer needs to expose functionality to crates which link
1823 against their library. As a consequence of the first case, this means that
1824 anything which is usable externally must be `pub` from the root down to the
1825 destination item. Any private item in the chain will disallow external
1828 * A crate needs a global available "helper module" to itself, but it doesn't
1829 want to expose the helper module as a public API. To accomplish this, the
1830 root of the crate's hierarchy would have a private module which then
1831 internally has a "public api". Because the entire crate is a descendant of
1832 the root, then the entire local crate can access this private module through
1835 * When writing unit tests for a module, it's often a common idiom to have an
1836 immediate child of the module to-be-tested named `mod test`. This module
1837 could access any items of the parent module through the second case, meaning
1838 that internal implementation details could also be seamlessly tested from the
1841 In the second case, it mentions that a private item "can be accessed" by the
1842 current module and its descendants, but the exact meaning of accessing an item
1843 depends on what the item is. Accessing a module, for example, would mean
1844 looking inside of it (to import more items). On the other hand, accessing a
1845 function would mean that it is invoked. Additionally, path expressions and
1846 import statements are considered to access an item in the sense that the
1847 import/expression is only valid if the destination is in the current visibility
1850 Here's an example of a program which exemplifies the three cases outlined
1854 // This module is private, meaning that no external crate can access this
1855 // module. Because it is private at the root of this current crate, however, any
1856 // module in the crate may access any publicly visible item in this module.
1857 mod crate_helper_module {
1859 // This function can be used by anything in the current crate
1860 pub fn crate_helper() {}
1862 // This function *cannot* be used by anything else in the crate. It is not
1863 // publicly visible outside of the `crate_helper_module`, so only this
1864 // current module and its descendants may access it.
1865 fn implementation_detail() {}
1868 // This function is "public to the root" meaning that it's available to external
1869 // crates linking against this one.
1870 pub fn public_api() {}
1872 // Similarly to 'public_api', this module is public so external crates may look
1875 use crate_helper_module;
1877 pub fn my_method() {
1878 // Any item in the local crate may invoke the helper module's public
1879 // interface through a combination of the two rules above.
1880 crate_helper_module::crate_helper();
1883 // This function is hidden to any module which is not a descendant of
1885 fn my_implementation() {}
1891 fn test_my_implementation() {
1892 // Because this module is a descendant of `submodule`, it's allowed
1893 // to access private items inside of `submodule` without a privacy
1895 super::my_implementation();
1903 For a rust program to pass the privacy checking pass, all paths must be valid
1904 accesses given the two rules above. This includes all use statements,
1905 expressions, types, etc.
1907 ### Re-exporting and Visibility
1909 Rust allows publicly re-exporting items through a `pub use` directive. Because
1910 this is a public directive, this allows the item to be used in the current
1911 module through the rules above. It essentially allows public access into the
1912 re-exported item. For example, this program is valid:
1915 pub use self::implementation as api;
1917 mod implementation {
1924 This means that any external crate referencing `implementation::f` would
1925 receive a privacy violation, while the path `api::f` would be allowed.
1927 When re-exporting a private item, it can be thought of as allowing the "privacy
1928 chain" being short-circuited through the reexport instead of passing through
1929 the namespace hierarchy as it normally would.
1934 attribute : "#!" ? '[' meta_item ']' ;
1935 meta_item : ident [ '=' literal
1936 | '(' meta_seq ')' ] ? ;
1937 meta_seq : meta_item [ ',' meta_seq ] ? ;
1940 Any item declaration may have an _attribute_ applied to it. Attributes in Rust
1941 are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
1942 (C#). An attribute is a general, free-form metadatum that is interpreted
1943 according to name, convention, and language and compiler version. Attributes
1944 may appear as any of:
1946 * A single identifier, the attribute name
1947 * An identifier followed by the equals sign '=' and a literal, providing a
1949 * An identifier followed by a parenthesized list of sub-attribute arguments
1951 Attributes with a bang ("!") after the hash ("#") apply to the item that the
1952 attribute is declared within. Attributes that do not have a bang after the hash
1953 apply to the item that follows the attribute.
1955 An example of attributes:
1958 // General metadata applied to the enclosing module or crate.
1959 #![crate_type = "lib"]
1961 // A function marked as a unit test
1967 // A conditionally-compiled module
1968 #[cfg(target_os="linux")]
1973 // A lint attribute used to suppress a warning/error
1974 #[allow(non_camel_case_types)]
1978 > **Note:** At some point in the future, the compiler will distinguish between
1979 > language-reserved and user-available attributes. Until then, there is
1980 > effectively no difference between an attribute handled by a loadable syntax
1981 > extension and the compiler.
1983 ### Crate-only attributes
1985 - `crate_name` - specify the this crate's crate name.
1986 - `crate_type` - see [linkage](#linkage).
1987 - `feature` - see [compiler features](#compiler-features).
1988 - `no_builtins` - disable optimizing certain code patterns to invocations of
1989 library functions that are assumed to exist
1990 - `no_main` - disable emitting the `main` symbol. Useful when some other
1991 object being linked to defines `main`.
1992 - `no_start` - disable linking to the `native` crate, which specifies the
1993 "start" language item.
1994 - `no_std` - disable linking to the `std` crate.
1996 ### Module-only attributes
1998 - `macro_escape` - macros defined in this module will be visible in the
1999 module's parent, after this module has been included.
2000 - `no_implicit_prelude` - disable injecting `use std::prelude::*` in this
2002 - `path` - specifies the file to load the module from. `#[path="foo.rs"] mod
2003 bar;` is equivalent to `mod bar { /* contents of foo.rs */ }`. The path is
2004 taken relative to the directory that the current module is in.
2006 ### Function-only attributes
2008 - `main` - indicates that this function should be passed to the entry point,
2009 rather than the function in the crate root named `main`.
2010 - `plugin_registrar` - mark this function as the registration point for
2011 [compiler plugins][plugin], such as loadable syntax extensions.
2012 - `start` - indicates that this function should be used as the entry point,
2013 overriding the "start" language item. See the "start" [language
2014 item](#language-items) for more details.
2015 - `test` - indicates that this function is a test function, to only be compiled
2016 in case of `--test`.
2018 ### Static-only attributes
2020 - `thread_local` - on a `static mut`, this signals that the value of this
2021 static may change depending on the current thread. The exact consequences of
2022 this are implementation-defined.
2026 On an `extern` block, the following attributes are interpreted:
2028 - `link_args` - specify arguments to the linker, rather than just the library
2029 name and type. This is feature gated and the exact behavior is
2030 implementation-defined (due to variety of linker invocation syntax).
2031 - `link` - indicate that a native library should be linked to for the
2032 declarations in this block to be linked correctly. `link` supports an optional `kind`
2033 key with three possible values: `dylib`, `static`, and `framework`. See [external blocks](#external-blocks) for more about external blocks. Two
2034 examples: `#[link(name = "readline")]` and
2035 `#[link(name = "CoreFoundation", kind = "framework")]`.
2037 On declarations inside an `extern` block, the following attributes are
2040 - `link_name` - the name of the symbol that this function or static should be
2042 - `linkage` - on a static, this specifies the [linkage
2043 type](http://llvm.org/docs/LangRef.html#linkage-types).
2047 - `repr` - on C-like enums, this sets the underlying type used for
2048 representation. Takes one argument, which is the primitive
2049 type this enum should be represented for, or `C`, which specifies that it
2050 should be the default `enum` size of the C ABI for that platform. Note that
2051 enum representation in C is undefined, and this may be incorrect when the C
2052 code is compiled with certain flags.
2056 - `repr` - specifies the representation to use for this struct. Takes a list
2057 of options. The currently accepted ones are `C` and `packed`, which may be
2058 combined. `C` will use a C ABI compatible struct layout, and `packed` will
2059 remove any padding between fields (note that this is very fragile and may
2060 break platforms which require aligned access).
2062 ### Miscellaneous attributes
2064 - `export_name` - on statics and functions, this determines the name of the
2066 - `link_section` - on statics and functions, this specifies the section of the
2067 object file that this item's contents will be placed into.
2068 - `macro_export` - export a macro for cross-crate usage.
2069 - `no_mangle` - on any item, do not apply the standard name mangling. Set the
2070 symbol for this item to its identifier.
2071 - `packed` - on structs or enums, eliminate any padding that would be used to
2073 - `phase` - on `extern crate` statements, allows specifying which "phase" of
2074 compilation the crate should be loaded for. Currently, there are two
2075 choices: `link` and `plugin`. `link` is the default. `plugin` will [load the
2076 crate at compile-time][plugin] and use any syntax extensions or lints that the crate
2077 defines. They can both be specified, `#[phase(link, plugin)]` to use a crate
2078 both at runtime and compiletime.
2079 - `simd` - on certain tuple structs, derive the arithmetic operators, which
2080 lower to the target's SIMD instructions, if any; the `simd` feature gate
2081 is necessary to use this attribute.
2082 - `static_assert` - on statics whose type is `bool`, terminates compilation
2083 with an error if it is not initialized to `true`.
2084 - `unsafe_destructor` - allow implementations of the "drop" language item
2085 where the type it is implemented for does not implement the "send" language
2086 item; the `unsafe_destructor` feature gate is needed to use this attribute
2087 - `unsafe_no_drop_flag` - on structs, remove the flag that prevents
2088 destructors from being run twice. Destructors might be run multiple times on
2089 the same object with this attribute.
2090 - `doc` - Doc comments such as `/// foo` are equivalent to `#[doc = "foo"]`.
2092 ### Conditional compilation
2094 Sometimes one wants to have different compiler outputs from the same code,
2095 depending on build target, such as targeted operating system, or to enable
2098 There are two kinds of configuration options, one that is either defined or not
2099 (`#[cfg(foo)]`), and the other that contains a string that can be checked
2100 against (`#[cfg(bar = "baz")]` (currently only compiler-defined configuration
2101 options can have the latter form).
2104 // The function is only included in the build when compiling for OSX
2105 #[cfg(target_os = "macos")]
2110 // This function is only included when either foo or bar is defined
2111 #[cfg(any(foo, bar))]
2112 fn needs_foo_or_bar() {
2116 // This function is only included when compiling for a unixish OS with a 32-bit
2118 #[cfg(all(unix, target_word_size = "32"))]
2119 fn on_32bit_unix() {
2123 // This function is only included when foo is not defined
2125 fn needs_not_foo() {
2130 This illustrates some conditional compilation can be achieved using the
2131 `#[cfg(...)]` attribute. `any`, `all` and `not` can be used to assemble
2132 arbitrarily complex configurations through nesting.
2134 The following configurations must be defined by the implementation:
2136 * `target_arch = "..."`. Target CPU architecture, such as `"x86"`, `"x86_64"`
2137 `"mips"`, or `"arm"`.
2138 * `target_endian = "..."`. Endianness of the target CPU, either `"little"` or
2140 * `target_family = "..."`. Operating system family of the target, e. g.
2141 `"unix"` or `"windows"`. The value of this configuration option is defined
2142 as a configuration itself, like `unix` or `windows`.
2143 * `target_os = "..."`. Operating system of the target, examples include
2144 `"win32"`, `"macos"`, `"linux"`, `"android"`, `"freebsd"` or `"dragonfly"`.
2145 * `target_word_size = "..."`. Target word size in bits. This is set to `"32"`
2146 for targets with 32-bit pointers, and likewise set to `"64"` for 64-bit
2148 * `unix`. See `target_family`.
2149 * `windows`. See `target_family`.
2151 ### Lint check attributes
2153 A lint check names a potentially undesirable coding pattern, such as
2154 unreachable code or omitted documentation, for the static entity to which the
2157 For any lint check `C`:
2159 * `allow(C)` overrides the check for `C` so that violations will go
2161 * `deny(C)` signals an error after encountering a violation of `C`,
2162 * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint
2164 * `warn(C)` warns about violations of `C` but continues compilation.
2166 The lint checks supported by the compiler can be found via `rustc -W help`,
2167 along with their default settings. [Compiler
2168 plugins](guide-plugin.html#lint-plugins) can provide additional lint checks.
2172 // Missing documentation is ignored here
2173 #[allow(missing_docs)]
2174 pub fn undocumented_one() -> int { 1 }
2176 // Missing documentation signals a warning here
2177 #[warn(missing_docs)]
2178 pub fn undocumented_too() -> int { 2 }
2180 // Missing documentation signals an error here
2181 #[deny(missing_docs)]
2182 pub fn undocumented_end() -> int { 3 }
2186 This example shows how one can use `allow` and `warn` to toggle a particular
2190 #[warn(missing_docs)]
2192 #[allow(missing_docs)]
2194 // Missing documentation is ignored here
2195 pub fn undocumented_one() -> int { 1 }
2197 // Missing documentation signals a warning here,
2198 // despite the allow above.
2199 #[warn(missing_docs)]
2200 pub fn undocumented_two() -> int { 2 }
2203 // Missing documentation signals a warning here
2204 pub fn undocumented_too() -> int { 3 }
2208 This example shows how one can use `forbid` to disallow uses of `allow` for
2212 #[forbid(missing_docs)]
2214 // Attempting to toggle warning signals an error here
2215 #[allow(missing_docs)]
2217 pub fn undocumented_too() -> int { 2 }
2223 Some primitive Rust operations are defined in Rust code, rather than being
2224 implemented directly in C or assembly language. The definitions of these
2225 operations have to be easy for the compiler to find. The `lang` attribute
2226 makes it possible to declare these operations. For example, the `str` module
2227 in the Rust standard library defines the string equality function:
2231 pub fn eq_slice(a: &str, b: &str) -> bool {
2236 The name `str_eq` has a special meaning to the Rust compiler, and the presence
2237 of this definition means that it will use this definition when generating calls
2238 to the string equality function.
2240 A complete list of the built-in language items follows:
2242 #### Built-in Traits
2245 : Types that do not move ownership when used by-value.
2249 : Able to be sent across task boundaries.
2251 : Has a size known at compile time.
2253 : Able to be safely shared between tasks when aliased.
2257 These language items are traits:
2260 : Elements can be added (for example, integers and floats).
2262 : Elements can be subtracted.
2264 : Elements can be multiplied.
2266 : Elements have a division operation.
2268 : Elements have a remainder operation.
2270 : Elements can be negated arithmetically.
2272 : Elements can be negated logically.
2274 : Elements have an exclusive-or operation.
2276 : Elements have a bitwise `and` operation.
2278 : Elements have a bitwise `or` operation.
2280 : Elements have a left shift operation.
2282 : Elements have a right shift operation.
2284 : Elements can be indexed.
2286 : ___Needs filling in___
2288 : Elements can be compared for equality.
2290 : Elements have a partial ordering.
2292 : `*` can be applied, yielding a reference to another type
2294 : `*` can be applied, yielding a mutable reference to another type
2296 These are functions:
2299 : ___Needs filling in___
2301 : ___Needs filling in___
2303 : ___Needs filling in___
2305 : Compare two strings (`&str`) for equality.
2307 : Return a new unique string
2308 containing a copy of the contents of a unique string.
2313 : The type returned by the `type_id` intrinsic.
2315 : A type whose contents can be mutated through an immutable reference
2319 These types help drive the compiler's analysis
2322 : ___Needs filling in___
2324 : This type does not implement "copy", even if eligible
2326 : This type does not implement "send", even if eligible
2328 : This type does not implement "sync", even if eligible
2330 : ___Needs filling in___
2332 : Free memory that was allocated on the exchange heap.
2334 : Allocate memory on the exchange heap.
2335 * `closure_exchange_malloc`
2336 : ___Needs filling in___
2338 : Abort the program with an error.
2339 * `fail_bounds_check`
2340 : Abort the program with a bounds check error.
2342 : Free memory that was allocated on the managed heap.
2344 : ___Needs filling in___
2346 : ___Needs filling in___
2348 : ___Needs filling in___
2349 * `contravariant_lifetime`
2350 : The lifetime parameter should be considered contravariant
2351 * `covariant_lifetime`
2352 : The lifetime parameter should be considered covariant
2353 * `invariant_lifetime`
2354 : The lifetime parameter should be considered invariant
2356 : Allocate memory on the managed heap.
2358 : ___Needs filling in___
2360 : ___Needs filling in___
2362 : ___Needs filling in___
2363 * `contravariant_type`
2364 : The type parameter should be considered contravariant
2366 : The type parameter should be considered covariant
2368 : The type parameter should be considered invariant
2370 : ___Needs filling in___
2372 > **Note:** This list is likely to become out of date. We should auto-generate
2373 > it from `librustc/middle/lang_items.rs`.
2375 ### Inline attributes
2377 The inline attribute is used to suggest to the compiler to perform an inline
2378 expansion and place a copy of the function or static in the caller rather than
2379 generating code to call the function or access the static where it is defined.
2381 The compiler automatically inlines functions based on internal heuristics.
2382 Incorrectly inlining functions can actually making the program slower, so it
2383 should be used with care.
2385 Immutable statics are always considered inlineable unless marked with
2386 `#[inline(never)]`. It is undefined whether two different inlineable statics
2387 have the same memory address. In other words, the compiler is free to collapse
2388 duplicate inlineable statics together.
2390 `#[inline]` and `#[inline(always)]` always causes the function to be serialized
2391 into crate metadata to allow cross-crate inlining.
2393 There are three different types of inline attributes:
2395 * `#[inline]` hints the compiler to perform an inline expansion.
2396 * `#[inline(always)]` asks the compiler to always perform an inline expansion.
2397 * `#[inline(never)]` asks the compiler to never perform an inline expansion.
2401 The `deriving` attribute allows certain traits to be automatically implemented
2402 for data structures. For example, the following will create an `impl` for the
2403 `PartialEq` and `Clone` traits for `Foo`, the type parameter `T` will be given
2404 the `PartialEq` or `Clone` constraints for the appropriate `impl`:
2407 #[deriving(PartialEq, Clone)]
2414 The generated `impl` for `PartialEq` is equivalent to
2417 # struct Foo<T> { a: int, b: T }
2418 impl<T: PartialEq> PartialEq for Foo<T> {
2419 fn eq(&self, other: &Foo<T>) -> bool {
2420 self.a == other.a && self.b == other.b
2423 fn ne(&self, other: &Foo<T>) -> bool {
2424 self.a != other.a || self.b != other.b
2429 Supported traits for `deriving` are:
2431 * Comparison traits: `PartialEq`, `Eq`, `PartialOrd`, `Ord`.
2432 * Serialization: `Encodable`, `Decodable`. These require `serialize`.
2433 * `Clone`, to create `T` from `&T` via a copy.
2434 * `Default`, to create an empty instance of a data type.
2435 * `FromPrimitive`, to create an instance from a numeric primitive.
2436 * `Hash`, to iterate over the bytes in a data type.
2437 * `Rand`, to create a random instance of a data type.
2438 * `Show`, to format a value using the `{}` formatter.
2439 * `Zero`, to create a zero instance of a numeric data type.
2443 One can indicate the stability of an API using the following attributes:
2445 * `deprecated`: This item should no longer be used, e.g. it has been
2446 replaced. No guarantee of backwards-compatibility.
2447 * `experimental`: This item was only recently introduced or is
2448 otherwise in a state of flux. It may change significantly, or even
2449 be removed. No guarantee of backwards-compatibility.
2450 * `unstable`: This item is still under development, but requires more
2451 testing to be considered stable. No guarantee of backwards-compatibility.
2452 * `stable`: This item is considered stable, and will not change
2453 significantly. Guarantee of backwards-compatibility.
2454 * `frozen`: This item is very stable, and is unlikely to
2455 change. Guarantee of backwards-compatibility.
2456 * `locked`: This item will never change unless a serious bug is
2457 found. Guarantee of backwards-compatibility.
2459 These levels are directly inspired by
2460 [Node.js' "stability index"](http://nodejs.org/api/documentation.html).
2462 Stability levels are inherited, so an item's stability attribute is the default
2463 stability for everything nested underneath it.
2465 There are lints for disallowing items marked with certain levels: `deprecated`,
2466 `experimental` and `unstable`. For now, only `deprecated` warns by default, but
2467 this will change once the standard library has been stabilized. Stability
2468 levels are meant to be promises at the crate level, so these lints only apply
2469 when referencing items from an _external_ crate, not to items defined within
2470 the current crate. Items with no stability level are considered to be unstable
2471 for the purposes of the lint. One can give an optional string that will be
2472 displayed when the lint flags the use of an item.
2474 For example, if we define one crate called `stability_levels`:
2477 #[deprecated="replaced by `best`"]
2479 // delete everything
2483 // delete fewer things
2492 then the lints will work as follows for a client crate:
2496 extern crate stability_levels;
2497 use stability_levels::{bad, better, best};
2500 bad(); // "warning: use of deprecated item: replaced by `best`"
2502 better(); // "warning: use of unmarked item"
2504 best(); // no warning
2508 > **Note:** Currently these are only checked when applied to individual
2509 > functions, structs, methods and enum variants, *not* to entire modules,
2510 > traits, impls or enums themselves.
2512 ### Compiler Features
2514 Certain aspects of Rust may be implemented in the compiler, but they're not
2515 necessarily ready for every-day use. These features are often of "prototype
2516 quality" or "almost production ready", but may not be stable enough to be
2517 considered a full-fledged language feature.
2519 For this reason, Rust recognizes a special crate-level attribute of the form:
2522 #![feature(feature1, feature2, feature3)]
2525 This directive informs the compiler that the feature list: `feature1`,
2526 `feature2`, and `feature3` should all be enabled. This is only recognized at a
2527 crate-level, not at a module-level. Without this directive, all features are
2528 considered off, and using the features will result in a compiler error.
2530 The currently implemented features of the reference compiler are:
2532 * `asm` - The `asm!` macro provides a means for inline assembly. This is often
2533 useful, but the exact syntax for this feature along with its
2534 semantics are likely to change, so this macro usage must be opted
2537 * `concat_idents` - Allows use of the `concat_idents` macro, which is in many
2538 ways insufficient for concatenating identifiers, and may be
2539 removed entirely for something more wholesome.
2541 * `default_type_params` - Allows use of default type parameters. The future of
2542 this feature is uncertain.
2544 * `if_let` - Allows use of the `if let` syntax.
2546 * `while_let` - Allows use of the `while let` syntax.
2548 * `intrinsics` - Allows use of the "rust-intrinsics" ABI. Compiler intrinsics
2549 are inherently unstable and no promise about them is made.
2551 * `lang_items` - Allows use of the `#[lang]` attribute. Like `intrinsics`,
2552 lang items are inherently unstable and no promise about them
2555 * `link_args` - This attribute is used to specify custom flags to the linker,
2556 but usage is strongly discouraged. The compiler's usage of the
2557 system linker is not guaranteed to continue in the future, and
2558 if the system linker is not used then specifying custom flags
2559 doesn't have much meaning.
2561 * `linkage` - Allows use of the `linkage` attribute, which is not portable.
2563 * `log_syntax` - Allows use of the `log_syntax` macro attribute, which is a
2564 nasty hack that will certainly be removed.
2566 * `macro_rules` - The definition of new macros. This does not encompass
2567 macro-invocation, that is always enabled by default, this
2568 only covers the definition of new macros. There are currently
2569 various problems with invoking macros, how they interact with
2570 their environment, and possibly how they are used outside of
2571 location in which they are defined. Macro definitions are
2572 likely to change slightly in the future, so they are
2573 currently hidden behind this feature.
2575 * `non_ascii_idents` - The compiler supports the use of non-ascii identifiers,
2576 but the implementation is a little rough around the
2577 edges, so this can be seen as an experimental feature
2578 for now until the specification of identifiers is fully
2581 * `once_fns` - Onceness guarantees a closure is only executed once. Defining a
2582 closure as `once` is unlikely to be supported going forward. So
2583 they are hidden behind this feature until they are to be removed.
2585 * `phase` - Usage of the `#[phase]` attribute allows loading compiler plugins
2586 for custom lints or syntax extensions. The implementation is
2587 considered unwholesome and in need of overhaul, and it is not clear
2588 what they will look like moving forward.
2590 * `plugin_registrar` - Indicates that a crate has [compiler plugins][plugin] that it
2591 wants to load. As with `phase`, the implementation is
2592 in need of an overhaul, and it is not clear that plugins
2593 defined using this will continue to work.
2595 * `quote` - Allows use of the `quote_*!` family of macros, which are
2596 implemented very poorly and will likely change significantly
2597 with a proper implementation.
2599 * `rustc_diagnostic_macros`- A mysterious feature, used in the implementation
2600 of rustc, not meant for mortals.
2602 * `simd` - Allows use of the `#[simd]` attribute, which is overly simple and
2603 not the SIMD interface we want to expose in the long term.
2605 * `struct_inherit` - Allows using struct inheritance, which is barely
2606 implemented and will probably be removed. Don't use this.
2608 * `struct_variant` - Structural enum variants (those with named fields). It is
2609 currently unknown whether this style of enum variant is as
2610 fully supported as the tuple-forms, and it's not certain
2611 that this style of variant should remain in the language.
2612 For now this style of variant is hidden behind a feature
2615 * `thread_local` - The usage of the `#[thread_local]` attribute is experimental
2616 and should be seen as unstable. This attribute is used to
2617 declare a `static` as being unique per-thread leveraging
2618 LLVM's implementation which works in concert with the kernel
2619 loader and dynamic linker. This is not necessarily available
2620 on all platforms, and usage of it is discouraged (rust
2621 focuses more on task-local data instead of thread-local
2624 * `trace_macros` - Allows use of the `trace_macros` macro, which is a nasty
2625 hack that will certainly be removed.
2627 * `unboxed_closures` - Rust's new closure design, which is currently a work in
2628 progress feature with many known bugs.
2630 * `unsafe_destructor` - Allows use of the `#[unsafe_destructor]` attribute,
2631 which is considered wildly unsafe and will be
2632 obsoleted by language improvements.
2634 * `tuple_indexing` - Allows use of tuple indexing (expressions like `expr.0`)
2636 * `associated_types` - Allows type aliases in traits. Experimental.
2638 If a feature is promoted to a language feature, then all existing programs will
2639 start to receive compilation warnings about #[feature] directives which enabled
2640 the new feature (because the directive is no longer necessary). However, if a
2641 feature is decided to be removed from the language, errors will be issued (if
2642 there isn't a parser error first). The directive in this case is no longer
2643 necessary, and it's likely that existing code will break if the feature isn't
2646 If an unknown feature is found in a directive, it results in a compiler error.
2647 An unknown feature is one which has never been recognized by the compiler.
2649 # Statements and expressions
2651 Rust is _primarily_ an expression language. This means that most forms of
2652 value-producing or effect-causing evaluation are directed by the uniform syntax
2653 category of _expressions_. Each kind of expression can typically _nest_ within
2654 each other kind of expression, and rules for evaluation of expressions involve
2655 specifying both the value produced by the expression and the order in which its
2656 sub-expressions are themselves evaluated.
2658 In contrast, statements in Rust serve _mostly_ to contain and explicitly
2659 sequence expression evaluation.
2663 A _statement_ is a component of a block, which is in turn a component of an
2664 outer [expression](#expressions) or [function](#functions).
2666 Rust has two kinds of statement: [declaration
2667 statements](#declaration-statements) and [expression
2668 statements](#expression-statements).
2670 ### Declaration statements
2672 A _declaration statement_ is one that introduces one or more *names* into the
2673 enclosing statement block. The declared names may denote new slots or new
2676 #### Item declarations
2678 An _item declaration statement_ has a syntactic form identical to an
2679 [item](#items) declaration within a module. Declaring an item — a
2680 function, enumeration, structure, type, static, trait, implementation or module
2681 — locally within a statement block is simply a way of restricting its
2682 scope to a narrow region containing all of its uses; it is otherwise identical
2683 in meaning to declaring the item outside the statement block.
2685 > **Note**: there is no implicit capture of the function's dynamic environment when
2686 > declaring a function-local item.
2688 #### Slot declarations
2691 let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
2692 init : [ '=' ] expr ;
2695 A _slot declaration_ introduces a new set of slots, given by a pattern. The
2696 pattern may be followed by a type annotation, and/or an initializer expression.
2697 When no type annotation is given, the compiler will infer the type, or signal
2698 an error if insufficient type information is available for definite inference.
2699 Any slots introduced by a slot declaration are visible from the point of
2700 declaration until the end of the enclosing block scope.
2702 ### Expression statements
2704 An _expression statement_ is one that evaluates an [expression](#expressions)
2705 and ignores its result. The type of an expression statement `e;` is always
2706 `()`, regardless of the type of `e`. As a rule, an expression statement's
2707 purpose is to trigger the effects of evaluating its expression.
2711 An expression may have two roles: it always produces a *value*, and it may have
2712 *effects* (otherwise known as "side effects"). An expression *evaluates to* a
2713 value, and has effects during *evaluation*. Many expressions contain
2714 sub-expressions (operands). The meaning of each kind of expression dictates
2717 * Whether or not to evaluate the sub-expressions when evaluating the expression
2718 * The order in which to evaluate the sub-expressions
2719 * How to combine the sub-expressions' values to obtain the value of the expression
2721 In this way, the structure of expressions dictates the structure of execution.
2722 Blocks are just another kind of expression, so blocks, statements, expressions,
2723 and blocks again can recursively nest inside each other to an arbitrary depth.
2725 #### Lvalues, rvalues and temporaries
2727 Expressions are divided into two main categories: _lvalues_ and _rvalues_.
2728 Likewise within each expression, sub-expressions may occur in _lvalue context_
2729 or _rvalue context_. The evaluation of an expression depends both on its own
2730 category and the context it occurs within.
2732 An lvalue is an expression that represents a memory location. These expressions
2733 are [paths](#path-expressions) (which refer to local variables, function and
2734 method arguments, or static variables), dereferences (`*expr`), [indexing
2735 expressions](#index-expressions) (`expr[expr]`), and [field
2736 references](#field-expressions) (`expr.f`). All other expressions are rvalues.
2738 The left operand of an [assignment](#assignment-expressions) or
2739 [compound-assignment](#compound-assignment-expressions) expression is an lvalue
2740 context, as is the single operand of a unary
2741 [borrow](#unary-operator-expressions). All other expression contexts are
2744 When an lvalue is evaluated in an _lvalue context_, it denotes a memory
2745 location; when evaluated in an _rvalue context_, it denotes the value held _in_
2746 that memory location.
2748 When an rvalue is used in an lvalue context, a temporary un-named lvalue is
2749 created and used instead. A temporary's lifetime equals the largest lifetime
2750 of any reference that points to it.
2752 #### Moved and copied types
2754 When a [local variable](#memory-slots) is used as an
2755 [rvalue](#lvalues,-rvalues-and-temporaries) the variable will either be moved
2756 or copied, depending on its type. For types that contain [owning
2757 pointers](#pointer-types) or values that implement the special trait `Drop`,
2758 the variable is moved. All other types are copied.
2760 ### Literal expressions
2762 A _literal expression_ consists of one of the [literal](#literals) forms
2763 described earlier. It directly describes a number, character, string, boolean
2764 value, or the unit value.
2768 "hello"; // string type
2769 '5'; // character type
2773 ### Path expressions
2775 A [path](#paths) used as an expression context denotes either a local variable
2776 or an item. Path expressions are [lvalues](#lvalues,-rvalues-and-temporaries).
2778 ### Tuple expressions
2780 Tuples are written by enclosing zero or more comma-separated expressions in
2781 parentheses. They are used to create [tuple-typed](#tuple-types) values.
2789 ### Unit expressions
2791 The expression `()` denotes the _unit value_, the only value of the type with
2794 ### Structure expressions
2797 struct_expr : expr_path '{' ident ':' expr
2798 [ ',' ident ':' expr ] *
2801 [ ',' expr ] * ')' |
2805 There are several forms of structure expressions. A _structure expression_
2806 consists of the [path](#paths) of a [structure item](#structures), followed by
2807 a brace-enclosed list of one or more comma-separated name-value pairs,
2808 providing the field values of a new instance of the structure. A field name
2809 can be any identifier, and is separated from its value expression by a colon.
2810 The location denoted by a structure field is mutable if and only if the
2811 enclosing structure is mutable.
2813 A _tuple structure expression_ consists of the [path](#paths) of a [structure
2814 item](#structures), followed by a parenthesized list of one or more
2815 comma-separated expressions (in other words, the path of a structure item
2816 followed by a tuple expression). The structure item must be a tuple structure
2819 A _unit-like structure expression_ consists only of the [path](#paths) of a
2820 [structure item](#structures).
2822 The following are examples of structure expressions:
2825 # struct Point { x: f64, y: f64 }
2826 # struct TuplePoint(f64, f64);
2827 # mod game { pub struct User<'a> { pub name: &'a str, pub age: uint, pub score: uint } }
2828 # struct Cookie; fn some_fn<T>(t: T) {}
2829 Point {x: 10.0, y: 20.0};
2830 TuplePoint(10.0, 20.0);
2831 let u = game::User {name: "Joe", age: 35, score: 100_000};
2832 some_fn::<Cookie>(Cookie);
2835 A structure expression forms a new value of the named structure type. Note
2836 that for a given *unit-like* structure type, this will always be the same
2839 A structure expression can terminate with the syntax `..` followed by an
2840 expression to denote a functional update. The expression following `..` (the
2841 base) must have the same structure type as the new structure type being formed.
2842 The entire expression denotes the result of constructing a new structure (with
2843 the same type as the base expression) with the given values for the fields that
2844 were explicitly specified and the values in the base expression for all other
2848 # struct Point3d { x: int, y: int, z: int }
2849 let base = Point3d {x: 1, y: 2, z: 3};
2850 Point3d {y: 0, z: 10, .. base};
2853 ### Block expressions
2856 block_expr : '{' [ view_item ] *
2857 [ stmt ';' | item ] *
2861 A _block expression_ is similar to a module in terms of the declarations that
2862 are possible. Each block conceptually introduces a new namespace scope. View
2863 items can bring new names into scopes and declared items are in scope for only
2866 A block will execute each statement sequentially, and then execute the
2867 expression (if given). If the final expression is omitted, the type and return
2868 value of the block are `()`, but if it is provided, the type and return value
2869 of the block are that of the expression itself.
2871 ### Method-call expressions
2874 method_call_expr : expr '.' ident paren_expr_list ;
2877 A _method call_ consists of an expression followed by a single dot, an
2878 identifier, and a parenthesized expression-list. Method calls are resolved to
2879 methods on specific traits, either statically dispatching to a method if the
2880 exact `self`-type of the left-hand-side is known, or dynamically dispatching if
2881 the left-hand-side expression is an indirect [object type](#object-types).
2883 ### Field expressions
2886 field_expr : expr '.' ident ;
2889 A _field expression_ consists of an expression followed by a single dot and an
2890 identifier, when not immediately followed by a parenthesized expression-list
2891 (the latter is a [method call expression](#method-call-expressions)). A field
2892 expression denotes a field of a [structure](#structure-types).
2897 (Struct {a: 10, b: 20}).a;
2900 A field access is an [lvalue](#lvalues,-rvalues-and-temporaries) referring to
2901 the value of that field. When the type providing the field inherits mutability,
2902 it can be [assigned](#assignment-expressions) to.
2904 Also, if the type of the expression to the left of the dot is a pointer, it is
2905 automatically dereferenced to make the field access possible.
2907 ### Array expressions
2910 array_expr : '[' "mut" ? vec_elems? ']' ;
2912 array_elems : [expr [',' expr]*] | [expr ',' ".." expr] ;
2915 An [array](#array,-and-slice-types) _expression_ is written by enclosing zero
2916 or more comma-separated expressions of uniform type in square brackets.
2918 In the `[expr ',' ".." expr]` form, the expression after the `".."` must be a
2919 constant expression that can be evaluated at compile time, such as a
2920 [literal](#literals) or a [static item](#static-items).
2924 ["a", "b", "c", "d"];
2925 [0i, ..128]; // array with 128 zeros
2926 [0u8, 0u8, 0u8, 0u8];
2929 ### Index expressions
2932 idx_expr : expr '[' expr ']' ;
2935 [Array](#array,-and-slice-types)-typed expressions can be indexed by
2936 writing a square-bracket-enclosed expression (the index) after them. When the
2937 array is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can
2940 Indices are zero-based, and may be of any integral type. Vector access is
2941 bounds-checked at run-time. When the check fails, it will put the task in a
2946 (["a", "b"])[10]; // panics
2949 ### Unary operator expressions
2951 Rust defines six symbolic unary operators. They are all written as prefix
2952 operators, before the expression they apply to.
2955 : Negation. May only be applied to numeric types.
2957 : Dereference. When applied to a [pointer](#pointer-types) it denotes the
2958 pointed-to location. For pointers to mutable locations, the resulting
2959 [lvalue](#lvalues,-rvalues-and-temporaries) can be assigned to.
2960 On non-pointer types, it calls the `deref` method of the `std::ops::Deref`
2961 trait, or the `deref_mut` method of the `std::ops::DerefMut` trait (if
2962 implemented by the type and required for an outer expression that will or
2963 could mutate the dereference), and produces the result of dereferencing the
2964 `&` or `&mut` borrowed pointer returned from the overload method.
2967 : Logical negation. On the boolean type, this flips between `true` and
2968 `false`. On integer types, this inverts the individual bits in the
2969 two's complement representation of the value.
2971 : [Boxing](#pointer-types) operators. Allocate a box to hold the value they
2972 are applied to, and store the value in it. `box` creates a box.
2974 : Borrow operator. Returns a reference, pointing to its operand. The operand
2975 of a borrow is statically proven to outlive the resulting pointer. If the
2976 borrow-checker cannot prove this, it is a compilation error.
2978 ### Binary operator expressions
2981 binop_expr : expr binop expr ;
2984 Binary operators expressions are given in terms of [operator
2985 precedence](#operator-precedence).
2987 #### Arithmetic operators
2989 Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
2990 defined in the `std::ops` module of the `std` library. This means that
2991 arithmetic operators can be overridden for user-defined types. The default
2992 meaning of the operators on standard types is given here.
2995 : Addition and array/string concatenation.
2996 Calls the `add` method on the `std::ops::Add` trait.
2999 Calls the `sub` method on the `std::ops::Sub` trait.
3002 Calls the `mul` method on the `std::ops::Mul` trait.
3005 Calls the `div` method on the `std::ops::Div` trait.
3008 Calls the `rem` method on the `std::ops::Rem` trait.
3010 #### Bitwise operators
3012 Like the [arithmetic operators](#arithmetic-operators), bitwise operators are
3013 syntactic sugar for calls to methods of built-in traits. This means that
3014 bitwise operators can be overridden for user-defined types. The default
3015 meaning of the operators on standard types is given here.
3019 Calls the `bitand` method of the `std::ops::BitAnd` trait.
3022 Calls the `bitor` method of the `std::ops::BitOr` trait.
3025 Calls the `bitxor` method of the `std::ops::BitXor` trait.
3027 : Logical left shift.
3028 Calls the `shl` method of the `std::ops::Shl` trait.
3030 : Logical right shift.
3031 Calls the `shr` method of the `std::ops::Shr` trait.
3033 #### Lazy boolean operators
3035 The operators `||` and `&&` may be applied to operands of boolean type. The
3036 `||` operator denotes logical 'or', and the `&&` operator denotes logical
3037 'and'. They differ from `|` and `&` in that the right-hand operand is only
3038 evaluated when the left-hand operand does not already determine the result of
3039 the expression. That is, `||` only evaluates its right-hand operand when the
3040 left-hand operand evaluates to `false`, and `&&` only when it evaluates to
3043 #### Comparison operators
3045 Comparison operators are, like the [arithmetic
3046 operators](#arithmetic-operators), and [bitwise operators](#bitwise-operators),
3047 syntactic sugar for calls to built-in traits. This means that comparison
3048 operators can be overridden for user-defined types. The default meaning of the
3049 operators on standard types is given here.
3053 Calls the `eq` method on the `std::cmp::PartialEq` trait.
3056 Calls the `ne` method on the `std::cmp::PartialEq` trait.
3059 Calls the `lt` method on the `std::cmp::PartialOrd` trait.
3062 Calls the `gt` method on the `std::cmp::PartialOrd` trait.
3064 : Less than or equal.
3065 Calls the `le` method on the `std::cmp::PartialOrd` trait.
3067 : Greater than or equal.
3068 Calls the `ge` method on the `std::cmp::PartialOrd` trait.
3070 #### Type cast expressions
3072 A type cast expression is denoted with the binary operator `as`.
3074 Executing an `as` expression casts the value on the left-hand side to the type
3075 on the right-hand side.
3077 A numeric value can be cast to any numeric type. A raw pointer value can be
3078 cast to or from any integral type or raw pointer type. Any other cast is
3079 unsupported and will fail to compile.
3081 An example of an `as` expression:
3084 # fn sum(v: &[f64]) -> f64 { 0.0 }
3085 # fn len(v: &[f64]) -> int { 0 }
3087 fn avg(v: &[f64]) -> f64 {
3088 let sum: f64 = sum(v);
3089 let sz: f64 = len(v) as f64;
3094 #### Assignment expressions
3096 An _assignment expression_ consists of an
3097 [lvalue](#lvalues,-rvalues-and-temporaries) expression followed by an equals
3098 sign (`=`) and an [rvalue](#lvalues,-rvalues-and-temporaries) expression.
3100 Evaluating an assignment expression [either copies or
3101 moves](#moved-and-copied-types) its right-hand operand to its left-hand
3111 #### Compound assignment expressions
3113 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>` operators may be
3114 composed with the `=` operator. The expression `lval OP= val` is equivalent to
3115 `lval = lval OP val`. For example, `x = x + 1` may be written as `x += 1`.
3117 Any such expression always has the [`unit`](#primitive-types) type.
3119 #### Operator precedence
3121 The precedence of Rust binary operators is ordered as follows, going from
3124 ```{.text .precedence}
3139 Operators at the same precedence level are evaluated left-to-right. [Unary
3140 operators](#unary-operator-expressions) have the same precedence level and it
3141 is stronger than any of the binary operators'.
3143 ### Grouped expressions
3145 An expression enclosed in parentheses evaluates to the result of the enclosed
3146 expression. Parentheses can be used to explicitly specify evaluation order
3147 within an expression.
3150 paren_expr : '(' expr ')' ;
3153 An example of a parenthesized expression:
3156 let x: int = (2 + 3) * 4;
3160 ### Call expressions
3163 expr_list : [ expr [ ',' expr ]* ] ? ;
3164 paren_expr_list : '(' expr_list ')' ;
3165 call_expr : expr paren_expr_list ;
3168 A _call expression_ invokes a function, providing zero or more input slots and
3169 an optional reference slot to serve as the function's output, bound to the
3170 `lval` on the right hand side of the call. If the function eventually returns,
3171 then the expression completes.
3173 Some examples of call expressions:
3176 # fn add(x: int, y: int) -> int { 0 }
3178 let x: int = add(1, 2);
3179 let pi: Option<f32> = from_str("3.14");
3182 ### Lambda expressions
3185 ident_list : [ ident [ ',' ident ]* ] ? ;
3186 lambda_expr : '|' ident_list '|' expr ;
3189 A _lambda expression_ (sometimes called an "anonymous function expression")
3190 defines a function and denotes it as a value, in a single expression. A lambda
3191 expression is a pipe-symbol-delimited (`|`) list of identifiers followed by an
3194 A lambda expression denotes a function that maps a list of parameters
3195 (`ident_list`) onto the expression that follows the `ident_list`. The
3196 identifiers in the `ident_list` are the parameters to the function. These
3197 parameters' types need not be specified, as the compiler infers them from
3200 Lambda expressions are most useful when passing functions as arguments to other
3201 functions, as an abbreviation for defining and capturing a separate function.
3203 Significantly, lambda expressions _capture their environment_, which regular
3204 [function definitions](#functions) do not. The exact type of capture depends
3205 on the [function type](#function-types) inferred for the lambda expression. In
3206 the simplest and least-expensive form (analogous to a ```|| { }``` expression),
3207 the lambda expression captures its environment by reference, effectively
3208 borrowing pointers to all outer variables mentioned inside the function.
3209 Alternately, the compiler may infer that a lambda expression should copy or
3210 move values (depending on their type.) from the environment into the lambda
3211 expression's captured environment.
3213 In this example, we define a function `ten_times` that takes a higher-order
3214 function argument, and call it with a lambda expression as an argument.
3217 fn ten_times(f: |int|) {
3225 ten_times(|j| println!("hello, {}", j));
3231 while_expr : "while" no_struct_literal_expr '{' block '}' ;
3234 A `while` loop begins by evaluating the boolean loop conditional expression.
3235 If the loop conditional expression evaluates to `true`, the loop body block
3236 executes and control returns to the loop conditional expression. If the loop
3237 conditional expression evaluates to `false`, the `while` expression completes.
3252 A `loop` expression denotes an infinite loop.
3255 loop_expr : [ lifetime ':' ] "loop" '{' block '}';
3258 A `loop` expression may optionally have a _label_. If a label is present, then
3259 labeled `break` and `continue` expressions nested within this loop may exit out
3260 of this loop or return control to its head. See [Break
3261 expressions](#break-expressions) and [Continue
3262 expressions](#continue-expressions).
3264 ### Break expressions
3267 break_expr : "break" [ lifetime ];
3270 A `break` expression has an optional _label_. If the label is absent, then
3271 executing a `break` expression immediately terminates the innermost loop
3272 enclosing it. It is only permitted in the body of a loop. If the label is
3273 present, then `break foo` terminates the loop with label `foo`, which need not
3274 be the innermost label enclosing the `break` expression, but must enclose it.
3276 ### Continue expressions
3279 continue_expr : "continue" [ lifetime ];
3282 A `continue` expression has an optional _label_. If the label is absent, then
3283 executing a `continue` expression immediately terminates the current iteration
3284 of the innermost loop enclosing it, returning control to the loop *head*. In
3285 the case of a `while` loop, the head is the conditional expression controlling
3286 the loop. In the case of a `for` loop, the head is the call-expression
3287 controlling the loop. If the label is present, then `continue foo` returns
3288 control to the head of the loop with label `foo`, which need not be the
3289 innermost label enclosing the `break` expression, but must enclose it.
3291 A `continue` expression is only permitted in the body of a loop.
3296 for_expr : "for" pat "in" no_struct_literal_expr '{' block '}' ;
3299 A `for` expression is a syntactic construct for looping over elements provided
3300 by an implementation of `std::iter::Iterator`.
3302 An example of a for loop over the contents of an array:
3306 # fn bar(f: Foo) { }
3311 let v: &[Foo] = &[a, b, c];
3318 An example of a for loop over a series of integers:
3321 # fn bar(b:uint) { }
3322 for i in range(0u, 256) {
3330 if_expr : "if" no_struct_literal_expr '{' block '}'
3333 else_tail : "else" [ if_expr | if_let_expr
3337 An `if` expression is a conditional branch in program control. The form of an
3338 `if` expression is a condition expression, followed by a consequent block, any
3339 number of `else if` conditions and blocks, and an optional trailing `else`
3340 block. The condition expressions must have type `bool`. If a condition
3341 expression evaluates to `true`, the consequent block is executed and any
3342 subsequent `else if` or `else` block is skipped. If a condition expression
3343 evaluates to `false`, the consequent block is skipped and any subsequent `else
3344 if` condition is evaluated. If all `if` and `else if` conditions evaluate to
3345 `false` then any `else` block is executed.
3347 ### Match expressions
3350 match_expr : "match" no_struct_literal_expr '{' match_arm * '}' ;
3352 match_arm : attribute * match_pat "=>" [ expr "," | '{' block '}' ] ;
3354 match_pat : pat [ '|' pat ] * [ "if" expr ] ? ;
3357 A `match` expression branches on a *pattern*. The exact form of matching that
3358 occurs depends on the pattern. Patterns consist of some combination of
3359 literals, destructured arrays or enum constructors, structures and tuples,
3360 variable binding specifications, wildcards (`..`), and placeholders (`_`). A
3361 `match` expression has a *head expression*, which is the value to compare to
3362 the patterns. The type of the patterns must equal the type of the head
3365 In a pattern whose head expression has an `enum` type, a placeholder (`_`)
3366 stands for a *single* data field, whereas a wildcard `..` stands for *all* the
3367 fields of a particular variant. For example:
3370 enum List<X> { Nil, Cons(X, Box<List<X>>) }
3372 let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil));
3375 List::Cons(_, box List::Nil) => panic!("singleton list"),
3376 List::Cons(..) => return,
3377 List::Nil => panic!("empty list")
3381 The first pattern matches lists constructed by applying `Cons` to any head
3382 value, and a tail value of `box Nil`. The second pattern matches _any_ list
3383 constructed with `Cons`, ignoring the values of its arguments. The difference
3384 between `_` and `..` is that the pattern `C(_)` is only type-correct if `C` has
3385 exactly one argument, while the pattern `C(..)` is type-correct for any enum
3386 variant `C`, regardless of how many arguments `C` has.
3388 Used inside an array pattern, `..` stands for any number of elements, when the
3389 `advanced_slice_patterns` feature gate is turned on. This wildcard can be used
3390 at most once for a given array, which implies that it cannot be used to
3391 specifically match elements that are at an unknown distance from both ends of a
3392 array, like `[.., 42, ..]`. If followed by a variable name, it will bind the
3393 corresponding slice to the variable. Example:
3396 # #![feature(advanced_slice_patterns)]
3397 fn is_symmetric(list: &[uint]) -> bool {
3400 [x, inside.., y] if x == y => is_symmetric(inside),
3406 let sym = &[0, 1, 4, 2, 4, 1, 0];
3407 let not_sym = &[0, 1, 7, 2, 4, 1, 0];
3408 assert!(is_symmetric(sym));
3409 assert!(!is_symmetric(not_sym));
3413 A `match` behaves differently depending on whether or not the head expression
3414 is an [lvalue or an rvalue](#lvalues,-rvalues-and-temporaries). If the head
3415 expression is an rvalue, it is first evaluated into a temporary location, and
3416 the resulting value is sequentially compared to the patterns in the arms until
3417 a match is found. The first arm with a matching pattern is chosen as the branch
3418 target of the `match`, any variables bound by the pattern are assigned to local
3419 variables in the arm's block, and control enters the block.
3421 When the head expression is an lvalue, the match does not allocate a temporary
3422 location (however, a by-value binding may copy or move from the lvalue). When
3423 possible, it is preferable to match on lvalues, as the lifetime of these
3424 matches inherits the lifetime of the lvalue, rather than being restricted to
3425 the inside of the match.
3427 An example of a `match` expression:
3430 # fn process_pair(a: int, b: int) { }
3431 # fn process_ten() { }
3433 enum List<X> { Nil, Cons(X, Box<List<X>>) }
3435 let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil));
3438 List::Cons(a, box List::Cons(b, _)) => {
3441 List::Cons(10, _) => {
3453 Patterns that bind variables default to binding to a copy or move of the
3454 matched value (depending on the matched value's type). This can be changed to
3455 bind to a reference by using the `ref` keyword, or to a mutable reference using
3458 Subpatterns can also be bound to variables by the use of the syntax `variable @
3459 subpattern`. For example:
3462 enum List { Nil, Cons(uint, Box<List>) }
3464 fn is_sorted(list: &List) -> bool {
3466 List::Nil | List::Cons(_, box List::Nil) => true,
3467 List::Cons(x, ref r @ box List::Cons(_, _)) => {
3469 box List::Cons(y, _) => (x <= y) && is_sorted(&**r),
3477 let a = List::Cons(6, box List::Cons(7, box List::Cons(42, box List::Nil)));
3478 assert!(is_sorted(&a));
3483 Patterns can also dereference pointers by using the `&`, `box` symbols,
3484 as appropriate. For example, these two matches on `x: &int` are equivalent:
3488 let y = match *x { 0 => "zero", _ => "some" };
3489 let z = match x { &0 => "zero", _ => "some" };
3494 A pattern that's just an identifier, like `Nil` in the previous example, could
3495 either refer to an enum variant that's in scope, or bind a new variable. The
3496 compiler resolves this ambiguity by forbidding variable bindings that occur in
3497 `match` patterns from shadowing names of variants that are in scope. For
3498 example, wherever `List` is in scope, a `match` pattern would not be able to
3499 bind `Nil` as a new name. The compiler interprets a variable pattern `x` as a
3500 binding _only_ if there is no variant named `x` in scope. A convention you can
3501 use to avoid conflicts is simply to name variants with upper-case letters, and
3502 local variables with lower-case letters.
3504 Multiple match patterns may be joined with the `|` operator. A range of values
3505 may be specified with `...`. For example:
3510 let message = match x {
3511 0 | 1 => "not many",
3517 Range patterns only work on scalar types (like integers and characters; not
3518 like arrays and structs, which have sub-components). A range pattern may not
3519 be a sub-range of another range pattern inside the same `match`.
3521 Finally, match patterns can accept *pattern guards* to further refine the
3522 criteria for matching a case. Pattern guards appear after the pattern and
3523 consist of a bool-typed expression following the `if` keyword. A pattern guard
3524 may refer to the variables bound within the pattern they follow.
3527 # let maybe_digit = Some(0);
3528 # fn process_digit(i: int) { }
3529 # fn process_other(i: int) { }
3531 let message = match maybe_digit {
3532 Some(x) if x < 10 => process_digit(x),
3533 Some(x) => process_other(x),
3538 ### If let expressions
3541 if_let_expr : "if" "let" pat '=' expr '{' block '}'
3543 else_tail : "else" [ if_expr | if_let_expr | '{' block '}' ] ;
3546 An `if let` expression is semantically identical to an `if` expression but in place
3547 of a condition expression it expects a refutable let statement. If the value of the
3548 expression on the right hand side of the let statement matches the pattern, the corresponding
3549 block will execute, otherwise flow proceeds to the first `else` block that follows.
3554 while_let_expr : "while" "let" pat '=' expr '{' block '}' ;
3557 A `while let` loop is semantically identical to a `while` loop but in place of a
3558 condition expression it expects a refutable let statement. If the value of the
3559 expression on the right hand side of the let statement matches the pattern, the
3560 loop body block executes and control returns to the pattern matching statement.
3561 Otherwise, the while expression completes.
3563 ### Return expressions
3566 return_expr : "return" expr ? ;
3569 Return expressions are denoted with the keyword `return`. Evaluating a `return`
3570 expression moves its argument into the output slot of the current function,
3571 destroys the current function activation frame, and transfers control to the
3574 An example of a `return` expression:
3577 fn max(a: int, b: int) -> int {
3589 Every slot, item and value in a Rust program has a type. The _type_ of a
3590 *value* defines the interpretation of the memory holding it.
3592 Built-in types and type-constructors are tightly integrated into the language,
3593 in nontrivial ways that are not possible to emulate in user-defined types.
3594 User-defined types have limited capabilities.
3598 The primitive types are the following:
3600 * The "unit" type `()`, having the single "unit" value `()` (occasionally called
3602 * The boolean type `bool` with values `true` and `false`.
3603 * The machine types.
3604 * The machine-dependent integer and floating-point types.
3606 [^unittype]: The "unit" value `()` is *not* a sentinel "null pointer" value for
3607 reference slots; the "unit" type is the implicit return type from functions
3608 otherwise lacking a return type, and can be used in other contexts (such as
3609 message-sending or type-parametric code) as a zero-size type.]
3613 The machine types are the following:
3615 * The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from
3616 the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1] and
3617 [0, 2^64 - 1] respectively.
3619 * The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with
3620 values drawn from the integer intervals [-(2^(7)), 2^7 - 1],
3621 [-(2^(15)), 2^15 - 1], [-(2^(31)), 2^31 - 1], [-(2^(63)), 2^63 - 1]
3624 * The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and
3625 `f64`, respectively.
3627 #### Machine-dependent integer types
3629 The `uint` type is an unsigned integer type with the same number of bits as the
3630 platform's pointer type. It can represent every memory address in the process.
3632 The `int` type is a signed integer type with the same number of bits as the
3633 platform's pointer type. The theoretical upper bound on object and array size
3634 is the maximum `int` value. This ensures that `int` can be used to calculate
3635 differences between pointers into an object or array and can address every byte
3636 within an object along with one byte past the end.
3640 The types `char` and `str` hold textual data.
3642 A value of type `char` is a [Unicode scalar value](
3643 http://www.unicode.org/glossary/#unicode_scalar_value) (ie. a code point that
3644 is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to
3645 0xD7FF or 0xE000 to 0x10FFFF range. A `[char]` array is effectively an UCS-4 /
3648 A value of type `str` is a Unicode string, represented as an array of 8-bit
3649 unsigned bytes holding a sequence of UTF-8 codepoints. Since `str` is of
3650 unknown size, it is not a _first class_ type, but can only be instantiated
3651 through a pointer type, such as `&str` or `String`.
3655 A tuple *type* is a heterogeneous product of other types, called the *elements*
3656 of the tuple. It has no nominal name and is instead structurally typed.
3658 Tuple types and values are denoted by listing the types or values of their
3659 elements, respectively, in a parenthesized, comma-separated list.
3661 Because tuple elements don't have a name, they can only be accessed by
3664 The members of a tuple are laid out in memory contiguously, in order specified
3667 An example of a tuple type and its use:
3670 type Pair<'a> = (int, &'a str);
3671 let p: Pair<'static> = (10, "hello");
3673 assert!(b != "world");
3676 ### Array, and Slice types
3678 Rust has two different types for a list of items:
3680 * `[T ..N]`, an 'array'
3681 * `&[T]`, a 'slice'.
3683 An array has a fixed size, and can be allocated on either the stack or the
3686 A slice is a 'view' into an array. It doesn't own the data it points
3689 An example of each kind:
3692 let vec: Vec<int> = vec![1, 2, 3];
3693 let arr: [int, ..3] = [1, 2, 3];
3694 let s: &[int] = vec.as_slice();
3697 As you can see, the `vec!` macro allows you to create a `Vec<T>` easily. The
3698 `vec!` macro is also part of the standard library, rather than the language.
3700 All in-bounds elements of arrays, and slices are always initialized, and access
3701 to an array or slice is always bounds-checked.
3705 A `struct` *type* is a heterogeneous product of other types, called the
3706 *fields* of the type.[^structtype]
3708 [^structtype]: `struct` types are analogous `struct` types in C,
3709 the *record* types of the ML family,
3710 or the *structure* types of the Lisp family.
3712 New instances of a `struct` can be constructed with a [struct
3713 expression](#structure-expressions).
3715 The memory layout of a `struct` is undefined by default to allow for compiler
3716 optimizations like field reordering, but it can be fixed with the
3717 `#[repr(...)]` attribute. In either case, fields may be given in any order in
3718 a corresponding struct *expression*; the resulting `struct` value will always
3719 have the same memory layout.
3721 The fields of a `struct` may be qualified by [visibility
3722 modifiers](#re-exporting-and-visibility), to allow access to data in a
3723 structure outside a module.
3725 A _tuple struct_ type is just like a structure type, except that the fields are
3728 A _unit-like struct_ type is like a structure type, except that it has no
3729 fields. The one value constructed by the associated [structure
3730 expression](#structure-expressions) is the only value that inhabits such a
3733 ### Enumerated types
3735 An *enumerated type* is a nominal, heterogeneous disjoint union type, denoted
3736 by the name of an [`enum` item](#enumerations). [^enumtype]
3738 [^enumtype]: The `enum` type is analogous to a `data` constructor declaration in
3739 ML, or a *pick ADT* in Limbo.
3741 An [`enum` item](#enumerations) declares both the type and a number of *variant
3742 constructors*, each of which is independently named and takes an optional tuple
3745 New instances of an `enum` can be constructed by calling one of the variant
3746 constructors, in a [call expression](#call-expressions).
3748 Any `enum` value consumes as much memory as the largest variant constructor for
3749 its corresponding `enum` type.
3751 Enum types cannot be denoted *structurally* as types, but must be denoted by
3752 named reference to an [`enum` item](#enumerations).
3756 Nominal types — [enumerations](#enumerated-types) and
3757 [structures](#structure-types) — may be recursive. That is, each `enum`
3758 constructor or `struct` field may refer, directly or indirectly, to the
3759 enclosing `enum` or `struct` type itself. Such recursion has restrictions:
3761 * Recursive types must include a nominal type in the recursion
3762 (not mere [type definitions](#type-definitions),
3763 or other structural types such as [arrays](#array,-and-slice-types) or [tuples](#tuple-types)).
3764 * A recursive `enum` item must have at least one non-recursive constructor
3765 (in order to give the recursion a basis case).
3766 * The size of a recursive type must be finite;
3767 in other words the recursive fields of the type must be [pointer types](#pointer-types).
3768 * Recursive type definitions can cross module boundaries, but not module *visibility* boundaries,
3769 or crate boundaries (in order to simplify the module system and type checker).
3771 An example of a *recursive* type and its use:
3776 Cons(T, Box<List<T>>)
3779 let a: List<int> = List::Cons(7, box List::Cons(13, box List::Nil));
3784 All pointers in Rust are explicit first-class values. They can be copied,
3785 stored into data structures, and returned from functions. There are two
3786 varieties of pointer in Rust:
3789 : These point to memory _owned by some other value_.
3790 A reference type is written `&type` for some lifetime-variable `f`,
3791 or just `&'a type` when you need an explicit lifetime.
3792 Copying a reference is a "shallow" operation:
3793 it involves only copying the pointer itself.
3794 Releasing a reference typically has no effect on the value it points to,
3795 with the exception of temporary values, which are released when the last
3796 reference to them is released.
3798 * Raw pointers (`*`)
3799 : Raw pointers are pointers without safety or liveness guarantees.
3800 Raw pointers are written as `*const T` or `*mut T`,
3801 for example `*const int` means a raw pointer to an integer.
3802 Copying or dropping a raw pointer has no effect on the lifecycle of any
3803 other value. Dereferencing a raw pointer or converting it to any other
3804 pointer type is an [`unsafe` operation](#unsafe-functions).
3805 Raw pointers are generally discouraged in Rust code;
3806 they exist to support interoperability with foreign code,
3807 and writing performance-critical or low-level functions.
3809 The standard library contains additional 'smart pointer' types beyond references
3814 The function type constructor `fn` forms new function types. A function type
3815 consists of a possibly-empty set of function-type modifiers (such as `unsafe`
3816 or `extern`), a sequence of input types and an output type.
3818 An example of a `fn` type:
3821 fn add(x: int, y: int) -> int {
3825 let mut x = add(5,7);
3827 type Binop<'a> = |int,int|: 'a -> int;
3828 let bo: Binop = add;
3834 ```{.ebnf .notation}
3835 closure_type := [ 'unsafe' ] [ '<' lifetime-list '>' ] '|' arg-list '|'
3836 [ ':' bound-list ] [ '->' type ]
3837 procedure_type := 'proc' [ '<' lifetime-list '>' ] '(' arg-list ')'
3838 [ ':' bound-list ] [ '->' type ]
3839 lifetime-list := lifetime | lifetime ',' lifetime-list
3840 arg-list := ident ':' type | ident ':' type ',' arg-list
3841 bound-list := bound | bound '+' bound-list
3842 bound := path | lifetime
3845 The type of a closure mapping an input of type `A` to an output of type `B` is
3846 `|A| -> B`. A closure with no arguments or return values has type `||`.
3847 Similarly, a procedure mapping `A` to `B` is `proc(A) -> B` and a no-argument
3848 and no-return value closure has type `proc()`.
3850 An example of creating and calling a closure:
3853 let captured_var = 10i;
3855 let closure_no_args = || println!("captured_var={}", captured_var);
3857 let closure_args = |arg: int| -> int {
3858 println!("captured_var={}, arg={}", captured_var, arg);
3859 arg // Note lack of semicolon after 'arg'
3862 fn call_closure(c1: ||, c2: |int| -> int) {
3867 call_closure(closure_no_args, closure_args);
3871 Unlike closures, procedures may only be invoked once, but own their
3872 environment, and are allowed to move out of their environment. Procedures are
3873 allocated on the heap (unlike closures). An example of creating and calling a
3877 let string = "Hello".to_string();
3879 // Creates a new procedure, passing it to the `spawn` function.
3881 println!("{} world!", string);
3884 // the variable `string` has been moved into the previous procedure, so it is
3885 // no longer usable.
3888 // Create an invoke a procedure. Note that the procedure is *moved* when
3889 // invoked, so it cannot be invoked again.
3890 let f = proc(n: int) { n + 22 };
3891 println!("answer: {}", f(20));
3897 Every trait item (see [traits](#traits)) defines a type with the same name as
3898 the trait. This type is called the _object type_ of the trait. Object types
3899 permit "late binding" of methods, dispatched using _virtual method tables_
3900 ("vtables"). Whereas most calls to trait methods are "early bound" (statically
3901 resolved) to specific implementations at compile time, a call to a method on an
3902 object type is only resolved to a vtable entry at compile time. The actual
3903 implementation for each vtable entry can vary on an object-by-object basis.
3905 Given a pointer-typed expression `E` of type `&T` or `Box<T>`, where `T`
3906 implements trait `R`, casting `E` to the corresponding pointer type `&R` or
3907 `Box<R>` results in a value of the _object type_ `R`. This result is
3908 represented as a pair of pointers: the vtable pointer for the `T`
3909 implementation of `R`, and the pointer value of `E`.
3911 An example of an object type:
3915 fn stringify(&self) -> String;
3918 impl Printable for int {
3919 fn stringify(&self) -> String { self.to_string() }
3922 fn print(a: Box<Printable>) {
3923 println!("{}", a.stringify());
3927 print(box 10i as Box<Printable>);
3931 In this example, the trait `Printable` occurs as an object type in both the
3932 type signature of `print`, and the cast expression in `main`.
3936 Within the body of an item that has type parameter declarations, the names of
3937 its type parameters are types:
3940 fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
3944 let first: B = f(xs[0].clone());
3945 let mut rest: Vec<B> = map(f, xs.slice(1, xs.len()));
3946 rest.insert(0, first);
3951 Here, `first` has type `B`, referring to `map`'s `B` type parameter; and `rest`
3952 has type `Vec<B>`, a vector type with element type `B`.
3956 The special type `self` has a meaning within methods inside an impl item. It
3957 refers to the type of the implicit `self` argument. For example, in:
3961 fn make_string(&self) -> String;
3964 impl Printable for String {
3965 fn make_string(&self) -> String {
3971 `self` refers to the value of type `String` that is the receiver for a call to
3972 the method `make_string`.
3976 Types in Rust are categorized into kinds, based on various properties of the
3977 components of the type. The kinds are:
3980 : Types of this kind can be safely sent between tasks.
3981 This kind includes scalars, boxes, procs, and
3982 structural types containing only other owned types.
3983 All `Send` types are `'static`.
3985 : Types of this kind consist of "Plain Old Data"
3986 which can be copied by simply moving bits.
3987 All values of this kind can be implicitly copied.
3988 This kind includes scalars and immutable references,
3989 as well as structural types containing other `Copy` types.
3991 : Types of this kind do not contain any references (except for
3992 references with the `static` lifetime, which are allowed).
3993 This can be a useful guarantee for code
3994 that breaks borrowing assumptions
3995 using [`unsafe` operations](#unsafe-functions).
3997 : This is not strictly a kind,
3998 but its presence interacts with kinds:
3999 the `Drop` trait provides a single method `drop`
4000 that takes no parameters,
4001 and is run when values of the type are dropped.
4002 Such a method is called a "destructor",
4003 and are always executed in "top-down" order:
4004 a value is completely destroyed
4005 before any of the values it owns run their destructors.
4006 Only `Send` types can implement `Drop`.
4009 : Types with destructors, closure environments,
4010 and various other _non-first-class_ types,
4011 are not copyable at all.
4012 Such types can usually only be accessed through pointers,
4013 or in some cases, moved between mutable locations.
4015 Kinds can be supplied as _bounds_ on type parameters, like traits, in which
4016 case the parameter is constrained to types satisfying that kind.
4018 By default, type parameters do not carry any assumed kind-bounds at all. When
4019 instantiating a type parameter, the kind bounds on the parameter are checked to
4020 be the same or narrower than the kind of the type that it is instantiated with.
4022 Sending operations are not part of the Rust language, but are implemented in
4023 the library. Generic functions that send values bound the kind of these values
4026 # Memory and concurrency models
4028 Rust has a memory model centered around concurrently-executing _tasks_. Thus
4029 its memory model and its concurrency model are best discussed simultaneously,
4030 as parts of each only make sense when considered from the perspective of the
4033 When reading about the memory model, keep in mind that it is partitioned in
4034 order to support tasks; and when reading about tasks, keep in mind that their
4035 isolation and communication mechanisms are only possible due to the ownership
4036 and lifetime semantics of the memory model.
4040 A Rust program's memory consists of a static set of *items*, a set of
4041 [tasks](#tasks) each with its own *stack*, and a *heap*. Immutable portions of
4042 the heap may be shared between tasks, mutable portions may not.
4044 Allocations in the stack consist of *slots*, and allocations in the heap
4047 ### Memory allocation and lifetime
4049 The _items_ of a program are those functions, modules and types that have their
4050 value calculated at compile-time and stored uniquely in the memory image of the
4051 rust process. Items are neither dynamically allocated nor freed.
4053 A task's _stack_ consists of activation frames automatically allocated on entry
4054 to each function as the task executes. A stack allocation is reclaimed when
4055 control leaves the frame containing it.
4057 The _heap_ is a general term that describes boxes. The lifetime of an
4058 allocation in the heap depends on the lifetime of the box values pointing to
4059 it. Since box values may themselves be passed in and out of frames, or stored
4060 in the heap, heap allocations may outlive the frame they are allocated within.
4062 ### Memory ownership
4064 A task owns all memory it can *safely* reach through local variables, as well
4065 as boxes and references.
4067 When a task sends a value that has the `Send` trait to another task, it loses
4068 ownership of the value sent and can no longer refer to it. This is statically
4069 guaranteed by the combined use of "move semantics", and the compiler-checked
4070 _meaning_ of the `Send` trait: it is only instantiated for (transitively)
4071 sendable kinds of data constructor and pointers, never including references.
4073 When a stack frame is exited, its local allocations are all released, and its
4074 references to boxes are dropped.
4076 When a task finishes, its stack is necessarily empty and it therefore has no
4077 references to any boxes; the remainder of its heap is immediately freed.
4081 A task's stack contains slots.
4083 A _slot_ is a component of a stack frame, either a function parameter, a
4084 [temporary](#lvalues,-rvalues-and-temporaries), or a local variable.
4086 A _local variable_ (or *stack-local* allocation) holds a value directly,
4087 allocated within the stack's memory. The value is a part of the stack frame.
4089 Local variables are immutable unless declared otherwise like: `let mut x = ...`.
4091 Function parameters are immutable unless declared with `mut`. The `mut` keyword
4092 applies only to the following parameter (so `|mut x, y|` and `fn f(mut x:
4093 Box<int>, y: Box<int>)` declare one mutable variable `x` and one immutable
4096 Methods that take either `self` or `Box<Self>` can optionally place them in a
4097 mutable slot by prefixing them with `mut` (similar to regular arguments):
4101 fn change(mut self) -> Self;
4102 fn modify(mut self: Box<Self>) -> Box<Self>;
4106 Local variables are not initialized when allocated; the entire frame worth of
4107 local variables are allocated at once, on frame-entry, in an uninitialized
4108 state. Subsequent statements within a function may or may not initialize the
4109 local variables. Local variables can be used only after they have been
4110 initialized; this is enforced by the compiler.
4114 A _box_ is a reference to a heap allocation holding another value, which is
4115 constructed by the prefix operator `box`. When the standard library is in use,
4116 the type of a box is `std::owned::Box<T>`.
4118 An example of a box type and value:
4121 let x: Box<int> = box 10;
4124 Box values exist in 1:1 correspondence with their heap allocation, copying a
4125 box value makes a shallow copy of the pointer. Rust will consider a shallow
4126 copy of a box to move ownership of the value. After a value has been moved,
4127 the source location cannot be used unless it is reinitialized.
4130 let x: Box<int> = box 10;
4132 // attempting to use `x` will result in an error here
4137 An executing Rust program consists of a tree of tasks. A Rust _task_ consists
4138 of an entry function, a stack, a set of outgoing communication channels and
4139 incoming communication ports, and ownership of some portion of the heap of a
4140 single operating-system process.
4142 ### Communication between tasks
4144 Rust tasks are isolated and generally unable to interfere with one another's
4145 memory directly, except through [`unsafe` code](#unsafe-functions). All
4146 contact between tasks is mediated by safe forms of ownership transfer, and data
4147 races on memory are prohibited by the type system.
4149 When you wish to send data between tasks, the values are restricted to the
4150 [`Send` type-kind](#type-kinds). Restricting communication interfaces to this
4151 kind ensures that no references move between tasks. Thus access to an entire
4152 data structure can be mediated through its owning "root" value; no further
4153 locking or copying is required to avoid data races within the substructure of
4158 The _lifecycle_ of a task consists of a finite set of states and events that
4159 cause transitions between the states. The lifecycle states of a task are:
4166 A task begins its lifecycle — once it has been spawned — in the
4167 *running* state. In this state it executes the statements of its entry
4168 function, and any functions called by the entry function.
4170 A task may transition from the *running* state to the *blocked* state any time
4171 it makes a blocking communication call. When the call can be completed —
4172 when a message arrives at a sender, or a buffer opens to receive a message
4173 — then the blocked task will unblock and transition back to *running*.
4175 A task may transition to the *panicked* state at any time, due being killed by
4176 some external event or internally, from the evaluation of a `panic!()` macro.
4177 Once *panicking*, a task unwinds its stack and transitions to the *dead* state.
4178 Unwinding the stack of a task is done by the task itself, on its own control
4179 stack. If a value with a destructor is freed during unwinding, the code for the
4180 destructor is run, also on the task's control stack. Running the destructor
4181 code causes a temporary transition to a *running* state, and allows the
4182 destructor code to cause any subsequent state transitions. The original task
4183 of unwinding and panicking thereby may suspend temporarily, and may involve
4184 (recursive) unwinding of the stack of a failed destructor. Nonetheless, the
4185 outermost unwinding activity will continue until the stack is unwound and the
4186 task transitions to the *dead* state. There is no way to "recover" from task
4187 panics. Once a task has temporarily suspended its unwinding in the *panicking*
4188 state, a panic occurring from within this destructor results in *hard* panic.
4189 A hard panic currently results in the process aborting.
4191 A task in the *dead* state cannot transition to other states; it exists only to
4192 have its termination status inspected by other tasks, and/or to await
4193 reclamation when the last reference to it drops.
4195 # Runtime services, linkage and debugging
4197 The Rust _runtime_ is a relatively compact collection of Rust code that
4198 provides fundamental services and datatypes to all Rust tasks at run-time. It
4199 is smaller and simpler than many modern language runtimes. It is tightly
4200 integrated into the language's execution model of memory, tasks, communication
4203 ### Memory allocation
4205 The runtime memory-management system is based on a _service-provider
4206 interface_, through which the runtime requests blocks of memory from its
4207 environment and releases them back to its environment when they are no longer
4208 needed. The default implementation of the service-provider interface consists
4209 of the C runtime functions `malloc` and `free`.
4211 The runtime memory-management system, in turn, supplies Rust tasks with
4212 facilities for allocating releasing stacks, as well as allocating and freeing
4217 The runtime provides C and Rust code to assist with various built-in types,
4218 such as arrays, strings, and the low level communication system (ports,
4221 Support for other built-in types such as simple types, tuples and enums is
4222 open-coded by the Rust compiler.
4224 ### Task scheduling and communication
4226 The runtime provides code to manage inter-task communication. This includes
4227 the system of task-lifecycle state transitions depending on the contents of
4228 queues, as well as code to copy values between queues and their recipients and
4229 to serialize values for transmission over operating-system inter-process
4230 communication facilities.
4234 The Rust compiler supports various methods to link crates together both
4235 statically and dynamically. This section will explore the various methods to
4236 link Rust crates together, and more information about native libraries can be
4237 found in the [ffi guide][ffi].
4239 In one session of compilation, the compiler can generate multiple artifacts
4240 through the usage of either command line flags or the `crate_type` attribute.
4241 If one or more command line flag is specified, all `crate_type` attributes will
4242 be ignored in favor of only building the artifacts specified by command line.
4244 * `--crate-type=bin`, `#[crate_type = "bin"]` - A runnable executable will be
4245 produced. This requires that there is a `main` function in the crate which
4246 will be run when the program begins executing. This will link in all Rust and
4247 native dependencies, producing a distributable binary.
4249 * `--crate-type=lib`, `#[crate_type = "lib"]` - A Rust library will be produced.
4250 This is an ambiguous concept as to what exactly is produced because a library
4251 can manifest itself in several forms. The purpose of this generic `lib` option
4252 is to generate the "compiler recommended" style of library. The output library
4253 will always be usable by rustc, but the actual type of library may change from
4254 time-to-time. The remaining output types are all different flavors of
4255 libraries, and the `lib` type can be seen as an alias for one of them (but the
4256 actual one is compiler-defined).
4258 * `--crate-type=dylib`, `#[crate_type = "dylib"]` - A dynamic Rust library will
4259 be produced. This is different from the `lib` output type in that this forces
4260 dynamic library generation. The resulting dynamic library can be used as a
4261 dependency for other libraries and/or executables. This output type will
4262 create `*.so` files on linux, `*.dylib` files on osx, and `*.dll` files on
4265 * `--crate-type=staticlib`, `#[crate_type = "staticlib"]` - A static system
4266 library will be produced. This is different from other library outputs in that
4267 the Rust compiler will never attempt to link to `staticlib` outputs. The
4268 purpose of this output type is to create a static library containing all of
4269 the local crate's code along with all upstream dependencies. The static
4270 library is actually a `*.a` archive on linux and osx and a `*.lib` file on
4271 windows. This format is recommended for use in situations such as linking
4272 Rust code into an existing non-Rust application because it will not have
4273 dynamic dependencies on other Rust code.
4275 * `--crate-type=rlib`, `#[crate_type = "rlib"]` - A "Rust library" file will be
4276 produced. This is used as an intermediate artifact and can be thought of as a
4277 "static Rust library". These `rlib` files, unlike `staticlib` files, are
4278 interpreted by the Rust compiler in future linkage. This essentially means
4279 that `rustc` will look for metadata in `rlib` files like it looks for metadata
4280 in dynamic libraries. This form of output is used to produce statically linked
4281 executables as well as `staticlib` outputs.
4283 Note that these outputs are stackable in the sense that if multiple are
4284 specified, then the compiler will produce each form of output at once without
4285 having to recompile. However, this only applies for outputs specified by the
4286 same method. If only `crate_type` attributes are specified, then they will all
4287 be built, but if one or more `--crate-type` command line flag is specified,
4288 then only those outputs will be built.
4290 With all these different kinds of outputs, if crate A depends on crate B, then
4291 the compiler could find B in various different forms throughout the system. The
4292 only forms looked for by the compiler, however, are the `rlib` format and the
4293 dynamic library format. With these two options for a dependent library, the
4294 compiler must at some point make a choice between these two formats. With this
4295 in mind, the compiler follows these rules when determining what format of
4296 dependencies will be used:
4298 1. If a static library is being produced, all upstream dependencies are
4299 required to be available in `rlib` formats. This requirement stems from the
4300 reason that a dynamic library cannot be converted into a static format.
4302 Note that it is impossible to link in native dynamic dependencies to a static
4303 library, and in this case warnings will be printed about all unlinked native
4304 dynamic dependencies.
4306 2. If an `rlib` file is being produced, then there are no restrictions on what
4307 format the upstream dependencies are available in. It is simply required that
4308 all upstream dependencies be available for reading metadata from.
4310 The reason for this is that `rlib` files do not contain any of their upstream
4311 dependencies. It wouldn't be very efficient for all `rlib` files to contain a
4312 copy of `libstd.rlib`!
4314 3. If an executable is being produced and the `-C prefer-dynamic` flag is not
4315 specified, then dependencies are first attempted to be found in the `rlib`
4316 format. If some dependencies are not available in an rlib format, then
4317 dynamic linking is attempted (see below).
4319 4. If a dynamic library or an executable that is being dynamically linked is
4320 being produced, then the compiler will attempt to reconcile the available
4321 dependencies in either the rlib or dylib format to create a final product.
4323 A major goal of the compiler is to ensure that a library never appears more
4324 than once in any artifact. For example, if dynamic libraries B and C were
4325 each statically linked to library A, then a crate could not link to B and C
4326 together because there would be two copies of A. The compiler allows mixing
4327 the rlib and dylib formats, but this restriction must be satisfied.
4329 The compiler currently implements no method of hinting what format a library
4330 should be linked with. When dynamically linking, the compiler will attempt to
4331 maximize dynamic dependencies while still allowing some dependencies to be
4332 linked in via an rlib.
4334 For most situations, having all libraries available as a dylib is recommended
4335 if dynamically linking. For other situations, the compiler will emit a
4336 warning if it is unable to determine which formats to link each library with.
4338 In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for
4339 all compilation needs, and the other options are just available if more
4340 fine-grained control is desired over the output format of a Rust crate.
4342 # Appendix: Rationales and design tradeoffs
4346 # Appendix: Influences and further references
4350 > The essential problem that must be solved in making a fault-tolerant
4351 > software system is therefore that of fault-isolation. Different programmers
4352 > will write different modules, some modules will be correct, others will have
4353 > errors. We do not want the errors in one module to adversely affect the
4354 > behaviour of a module which does not have any errors.
4356 > — Joe Armstrong
4358 > In our approach, all data is private to some process, and processes can
4359 > only communicate through communications channels. *Security*, as used
4360 > in this paper, is the property which guarantees that processes in a system
4361 > cannot affect each other except by explicit communication.
4363 > When security is absent, nothing which can be proven about a single module
4364 > in isolation can be guaranteed to hold when that module is embedded in a
4367 > — Robert Strom and Shaula Yemini
4369 > Concurrent and applicative programming complement each other. The
4370 > ability to send messages on channels provides I/O without side effects,
4371 > while the avoidance of shared data helps keep concurrent processes from
4376 Rust is not a particularly original language. It may however appear unusual by
4377 contemporary standards, as its design elements are drawn from a number of
4378 "historical" languages that have, with a few exceptions, fallen out of favour.
4379 Five prominent lineages contribute the most, though their influences have come
4380 and gone during the course of Rust's development:
4382 * The NIL (1981) and Hermes (1990) family. These languages were developed by
4383 Robert Strom, Shaula Yemini, David Bacon and others in their group at IBM
4384 Watson Research Center (Yorktown Heights, NY, USA).
4386 * The Erlang (1987) language, developed by Joe Armstrong, Robert Virding, Claes
4387 Wikström, Mike Williams and others in their group at the Ericsson Computer
4388 Science Laboratory (Älvsjö, Stockholm, Sweden) .
4390 * The Sather (1990) language, developed by Stephen Omohundro, Chu-Cheow Lim,
4391 Heinz Schmidt and others in their group at The International Computer
4392 Science Institute of the University of California, Berkeley (Berkeley, CA,
4395 * The Newsqueak (1988), Alef (1995), and Limbo (1996) family. These
4396 languages were developed by Rob Pike, Phil Winterbottom, Sean Dorward and
4397 others in their group at Bell Labs Computing Sciences Research Center
4398 (Murray Hill, NJ, USA).
4400 * The Napier (1985) and Napier88 (1988) family. These languages were
4401 developed by Malcolm Atkinson, Ron Morrison and others in their group at
4402 the University of St. Andrews (St. Andrews, Fife, UK).
4404 Additional specific influences can be seen from the following languages:
4406 * The structural algebraic types and compilation manager of SML.
4407 * The attribute and assembly systems of C#.
4408 * The references and deterministic destructor system of C++.
4409 * The memory region systems of the ML Kit and Cyclone.
4410 * The typeclass system of Haskell.
4411 * The lexical identifier rule of Python.
4412 * The block syntax of Ruby.
4414 [ffi]: guide-ffi.html
4415 [plugin]: guide-plugin.html