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 | macro | match | mod |
197 | move | mut | offsetof | override | priv |
198 | pub | pure | ref | return | sizeof |
199 | static | self | struct | super | true |
200 | trait | type | typeof | unsafe | unsized |
201 | use | virtual | where | while | yield |
204 Each of these keywords has special meaning in its grammar, and all of them are
205 excluded from the `ident` rule.
207 Note that some of these keywords are reserved, and do not currently do
212 A literal is an expression consisting of a single token, rather than a sequence
213 of tokens, that immediately and directly denotes the value it evaluates to,
214 rather than referring to it by name or some other evaluation rule. A literal is
215 a form of constant expression, so is evaluated (primarily) at compile time.
219 literal : [ string_lit | char_lit | byte_string_lit | byte_lit | num_lit ] lit_suffix ?;
222 The optional suffix is only used for certain numeric literals, but is
223 reserved for future extension, that is, the above gives the lexical
224 grammar, but a Rust parser will reject everything but the 12 special
225 cases mentioned in [Number literals](#number-literals) below.
229 ##### Characters and strings
231 | | Example | Number of `#` pairs allowed | Available characters | Escapes | Equivalent to |
232 |---|---------|-----------------------------|----------------------|---------|---------------|
233 | [Character](#character-literals) | `'H'` | `N/A` | All unicode | `\'` & [Byte escapes](#byte-escapes) & [Unicode escapes](#unicode-escapes) | `N/A` |
234 | [String](#string-literals) | `"hello"` | `N/A` | All unicode | `\"` & [Byte escapes](#byte-escapes) & [Unicode escapes](#unicode-escapes) | `N/A` |
235 | [Raw](#raw-string-literals) | `r##"hello"##` | `0...` | All unicode | `N/A` | `N/A` |
236 | [Byte](#byte-literals) | `b'H'` | `N/A` | All ASCII | `\'` & [Byte escapes](#byte-escapes) | `u8` |
237 | [Byte string](#byte-string-literals) | `b"hello"` | `N/A` | All ASCII | `\"` & [Byte escapes](#byte-escapes) | `&'static [u8]` |
238 | [Raw byte string](#raw-byte-string-literals) | `br##"hello"##` | `0...` | All ASCII | `N/A` | `&'static [u8]` (unsure...not stated) |
244 | `\x7F` | 8-bit character code (exactly 2 digits) |
246 | `\r` | Carriage return |
250 ##### Unicode escapes
253 | `\u7FFF` | 16-bit character code (exactly 4 digits) |
254 | `\U7EEEFFFF` | 32-bit character code (exactly 8 digits) |
258 | [Number literals](#number-literals)`*` | Example | Exponentiation | Suffixes |
259 |----------------------------------------|---------|----------------|----------|
260 | Decimal integer | `98_222i` | `N/A` | Integer suffixes |
261 | Hex integer | `0xffi` | `N/A` | Integer suffixes |
262 | Octal integer | `0o77i` | `N/A` | Integer suffixes |
263 | Binary integer | `0b1111_0000i` | `N/A` | Integer suffixes |
264 | Floating-point | `123.0E+77f64` | `Optional` | Floating-point suffixes |
266 `*` All number literals allow `_` as a visual separator: `1_234.0E+18f64`
269 | Integer | Floating-point |
270 |---------|----------------|
271 | `i` (`int`), `u` (`uint`), `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64` | `f32`, `f64` |
273 #### Character and string literals
276 char_lit : '\x27' char_body '\x27' ;
277 string_lit : '"' string_body * '"' | 'r' raw_string ;
279 char_body : non_single_quote
280 | '\x5c' [ '\x27' | common_escape | unicode_escape ] ;
282 string_body : non_double_quote
283 | '\x5c' [ '\x22' | common_escape | unicode_escape ] ;
284 raw_string : '"' raw_string_body '"' | '#' raw_string '#' ;
286 common_escape : '\x5c'
287 | 'n' | 'r' | 't' | '0'
289 unicode_escape : 'u' hex_digit 4
292 hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
293 | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
295 oct_digit : '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' ;
296 dec_digit : '0' | nonzero_dec ;
297 nonzero_dec: '1' | '2' | '3' | '4'
298 | '5' | '6' | '7' | '8' | '9' ;
301 ##### Character literals
303 A _character literal_ is a single Unicode character enclosed within two
304 `U+0027` (single-quote) characters, with the exception of `U+0027` itself,
305 which must be _escaped_ by a preceding U+005C character (`\`).
307 ##### String literals
309 A _string literal_ is a sequence of any Unicode characters enclosed within two
310 `U+0022` (double-quote) characters, with the exception of `U+0022` itself,
311 which must be _escaped_ by a preceding `U+005C` character (`\`), or a _raw
314 ##### Character escapes
316 Some additional _escapes_ are available in either character or non-raw string
317 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
320 * An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is
321 followed by exactly two _hex digits_. It denotes the Unicode codepoint
322 equal to the provided hex value.
323 * A _16-bit codepoint escape_ starts with `U+0075` (`u`) and is followed
324 by exactly four _hex digits_. It denotes the Unicode codepoint equal to
325 the provided hex value.
326 * A _32-bit codepoint escape_ starts with `U+0055` (`U`) and is followed
327 by exactly eight _hex digits_. It denotes the Unicode codepoint equal to
328 the provided hex value.
329 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
330 (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF),
331 `U+000D` (CR) or `U+0009` (HT) respectively.
332 * The _backslash escape_ is the character `U+005C` (`\`) which must be
333 escaped in order to denote *itself*.
335 ##### Raw string literals
337 Raw string literals do not process any escapes. They start with the character
338 `U+0072` (`r`), followed by zero or more of the character `U+0023` (`#`) and a
339 `U+0022` (double-quote) character. The _raw string body_ is not defined in the
340 EBNF grammar above: it can contain any sequence of Unicode characters and is
341 terminated only by another `U+0022` (double-quote) character, followed by the
342 same number of `U+0023` (`#`) characters that preceded the opening `U+0022`
343 (double-quote) character.
345 All Unicode characters contained in the raw string body represent themselves,
346 the characters `U+0022` (double-quote) (except when followed by at least as
347 many `U+0023` (`#`) characters as were used to start the raw string literal) or
348 `U+005C` (`\`) do not have any special meaning.
350 Examples for string literals:
353 "foo"; r"foo"; // foo
354 "\"foo\""; r#""foo""#; // "foo"
357 r##"foo #"# bar"##; // foo #"# bar
359 "\x52"; "R"; r"R"; // R
360 "\\x52"; r"\x52"; // \x52
363 #### Byte and byte string literals
366 byte_lit : "b\x27" byte_body '\x27' ;
367 byte_string_lit : "b\x22" string_body * '\x22' | "br" raw_byte_string ;
369 byte_body : ascii_non_single_quote
370 | '\x5c' [ '\x27' | common_escape ] ;
372 byte_string_body : ascii_non_double_quote
373 | '\x5c' [ '\x22' | common_escape ] ;
374 raw_byte_string : '"' raw_byte_string_body '"' | '#' raw_byte_string '#' ;
380 A _byte literal_ is a single ASCII character (in the `U+0000` to `U+007F`
381 range) enclosed within two `U+0027` (single-quote) characters, with the
382 exception of `U+0027` itself, which must be _escaped_ by a preceding U+005C
383 character (`\`), or a single _escape_. It is equivalent to a `u8` unsigned
384 8-bit integer _number literal_.
386 ##### Byte string literals
388 A _byte string literal_ is a sequence of ASCII characters and _escapes_
389 enclosed within two `U+0022` (double-quote) characters, with the exception of
390 `U+0022` itself, which must be _escaped_ by a preceding `U+005C` character
391 (`\`), or a _raw byte string literal_. It is equivalent to a `&'static [u8]`
392 borrowed array of unsigned 8-bit integers.
394 Some additional _escapes_ are available in either byte or non-raw byte string
395 literals. An escape starts with a `U+005C` (`\`) and continues with one of the
398 * An _byte escape_ escape starts with `U+0078` (`x`) and is
399 followed by exactly two _hex digits_. It denotes the byte
400 equal to the provided hex value.
401 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
402 (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF),
403 `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.
404 * The _backslash escape_ is the character `U+005C` (`\`) which must be
405 escaped in order to denote its ASCII encoding `0x5C`.
407 ##### Raw byte string literals
409 Raw byte string literals do not process any escapes. They start with the
410 character `U+0062` (`b`), followed by `U+0072` (`r`), followed by zero or more
411 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character. The
412 _raw string body_ is not defined in the EBNF grammar above: it can contain any
413 sequence of ASCII characters and is terminated only by another `U+0022`
414 (double-quote) character, followed by the same number of `U+0023` (`#`)
415 characters that preceded the opening `U+0022` (double-quote) character. A raw
416 byte string literal can not contain any non-ASCII byte.
418 All characters contained in the raw string body represent their ASCII encoding,
419 the characters `U+0022` (double-quote) (except when followed by at least as
420 many `U+0023` (`#`) characters as were used to start the raw string literal) or
421 `U+005C` (`\`) do not have any special meaning.
423 Examples for byte string literals:
426 b"foo"; br"foo"; // foo
427 b"\"foo\""; br#""foo""#; // "foo"
430 br##"foo #"# bar"##; // foo #"# bar
432 b"\x52"; b"R"; br"R"; // R
433 b"\\x52"; br"\x52"; // \x52
439 num_lit : nonzero_dec [ dec_digit | '_' ] * float_suffix ?
440 | '0' [ [ dec_digit | '_' ] * float_suffix ?
441 | 'b' [ '1' | '0' | '_' ] +
442 | 'o' [ oct_digit | '_' ] +
443 | 'x' [ hex_digit | '_' ] + ] ;
445 float_suffix : [ exponent | '.' dec_lit exponent ? ] ? ;
447 exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
448 dec_lit : [ dec_digit | '_' ] + ;
451 A _number literal_ is either an _integer literal_ or a _floating-point
452 literal_. The grammar for recognizing the two kinds of literals is mixed.
454 ##### Integer literals
456 An _integer literal_ has one of four forms:
458 * A _decimal literal_ starts with a *decimal digit* and continues with any
459 mixture of *decimal digits* and _underscores_.
460 * A _hex literal_ starts with the character sequence `U+0030` `U+0078`
461 (`0x`) and continues as any mixture of hex digits and underscores.
462 * An _octal literal_ starts with the character sequence `U+0030` `U+006F`
463 (`0o`) and continues as any mixture of octal digits and underscores.
464 * A _binary literal_ starts with the character sequence `U+0030` `U+0062`
465 (`0b`) and continues as any mixture of binary digits and underscores.
467 Like any literal, an integer literal may be followed (immediately,
468 without any spaces) by an _integer suffix_, which forcibly sets the
469 type of the literal. There are 10 valid values for an integer suffix:
471 * The `i` and `u` suffixes give the literal type `int` or `uint`,
473 * Each of the signed and unsigned machine types `u8`, `i8`,
474 `u16`, `i16`, `u32`, `i32`, `u64` and `i64`
475 give the literal the corresponding machine type.
477 The type of an _unsuffixed_ integer literal is determined by type inference.
478 If an integer type can be _uniquely_ determined from the surrounding program
479 context, the unsuffixed integer literal has that type. If the program context
480 underconstrains the type, it is considered a static type error; if the program
481 context overconstrains the type, it is also considered a static type error.
483 Examples of integer literals of various forms:
490 0o70_i16; // type i16
491 0b1111_1111_1001_0000_i32; // type i32
494 ##### Floating-point literals
496 A _floating-point literal_ has one of two forms:
498 * A _decimal literal_ followed by a period character `U+002E` (`.`). This is
499 optionally followed by another decimal literal, with an optional _exponent_.
500 * A single _decimal literal_ followed by an _exponent_.
502 By default, a floating-point literal has a generic type, and, like integer
503 literals, the type must be uniquely determined from the context. There are two valid
504 _floating-point suffixes_, `f32` and `f64` (the 32-bit and 64-bit floating point
505 types), which explicitly determine the type of the literal.
507 Examples of floating-point literals of various forms:
510 123.0f64; // type f64
513 12E+99_f64; // type f64
514 let x: f64 = 2.; // type f64
517 This last example is different because it is not possible to use the suffix
518 syntax with a floating point literal ending in a period. `2.f64` would attempt
519 to call a method named `f64` on `2`.
521 #### Boolean literals
523 The two values of the boolean type are written `true` and `false`.
529 | '#' | '[' | ']' | '(' | ')' | '{' | '}'
533 Symbols are a general class of printable [token](#tokens) that play structural
534 roles in a variety of grammar productions. They are catalogued here for
535 completeness as the set of remaining miscellaneous printable tokens that do not
536 otherwise appear as [unary operators](#unary-operator-expressions), [binary
537 operators](#binary-operator-expressions), or [keywords](#keywords).
543 expr_path : [ "::" ] ident [ "::" expr_path_tail ] + ;
544 expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
547 type_path : ident [ type_path_tail ] + ;
548 type_path_tail : '<' type_expr [ ',' type_expr ] + '>'
552 A _path_ is a sequence of one or more path components _logically_ separated by
553 a namespace qualifier (`::`). If a path consists of only one component, it may
554 refer to either an [item](#items) or a [slot](#memory-slots) in a local control
555 scope. If a path has multiple components, it refers to an item.
557 Every item has a _canonical path_ within its crate, but the path naming an item
558 is only meaningful within a given crate. There is no global namespace across
559 crates; an item's canonical path merely identifies it within the crate.
561 Two examples of simple paths consisting of only identifier components:
568 Path components are usually [identifiers](#identifiers), but the trailing
569 component of a path may be an angle-bracket-enclosed list of type arguments. In
570 [expression](#expressions) context, the type argument list is given after a
571 final (`::`) namespace qualifier in order to disambiguate it from a relational
572 expression involving the less-than symbol (`<`). In type expression context,
573 the final namespace qualifier is omitted.
575 Two examples of paths with type arguments:
578 # struct HashMap<K, V>;
580 # fn id<T>(t: T) -> T { t }
581 type T = HashMap<int,String>; // Type arguments used in a type expression
582 let x = id::<int>(10); // Type arguments used in a call expression
586 Paths can be denoted with various leading qualifiers to change the meaning of
589 * Paths starting with `::` are considered to be global paths where the
590 components of the path start being resolved from the crate root. Each
591 identifier in the path must resolve to an item.
599 ::a::foo(); // call a's foo function
605 * Paths starting with the keyword `super` begin resolution relative to the
606 parent module. Each further identifier must resolve to an item
614 super::a::foo(); // call a's foo function
620 * Paths starting with the keyword `self` begin resolution relative to the
621 current module. Each further identifier must resolve to an item.
633 A number of minor features of Rust are not central enough to have their own
634 syntax, and yet are not implementable as functions. Instead, they are given
635 names, and invoked through a consistent syntax: `name!(...)`. Examples include:
637 * `format!` : format data into a string
638 * `env!` : look up an environment variable's value at compile time
639 * `file!`: return the path to the file being compiled
640 * `stringify!` : pretty-print the Rust expression given as an argument
641 * `include!` : include the Rust expression in the given file
642 * `include_str!` : include the contents of the given file as a string
643 * `include_bytes!` : include the contents of the given file as a binary blob
644 * `error!`, `warn!`, `info!`, `debug!` : provide diagnostic information.
646 All of the above extensions are expressions with values.
648 Users of `rustc` can define new syntax extensions in two ways:
650 * [Compiler plugins](guide-plugin.html#syntax-extensions) can include arbitrary
651 Rust code that manipulates syntax trees at compile time.
653 * [Macros](guide-macros.html) define new syntax in a higher-level,
659 expr_macro_rules : "macro_rules" '!' ident '(' macro_rule * ')' ;
660 macro_rule : '(' matcher * ')' "=>" '(' transcriber * ')' ';' ;
661 matcher : '(' matcher * ')' | '[' matcher * ']'
662 | '{' matcher * '}' | '$' ident ':' ident
663 | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]
664 | non_special_token ;
665 transcriber : '(' transcriber * ')' | '[' transcriber * ']'
666 | '{' transcriber * '}' | '$' ident
667 | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]
668 | non_special_token ;
671 `macro_rules` allows users to define syntax extension in a declarative way. We
672 call such extensions "macros by example" or simply "macros" — to be distinguished
673 from the "procedural macros" defined in [compiler plugins][plugin].
675 Currently, macros can expand to expressions, statements, items, or patterns.
677 (A `sep_token` is any token other than `*` and `+`. A `non_special_token` is
678 any token other than a delimiter or `$`.)
680 The macro expander looks up macro invocations by name, and tries each macro
681 rule in turn. It transcribes the first successful match. Matching and
682 transcription are closely related to each other, and we will describe them
687 The macro expander matches and transcribes every token that does not begin with
688 a `$` literally, including delimiters. For parsing reasons, delimiters must be
689 balanced, but they are otherwise not special.
691 In the matcher, `$` _name_ `:` _designator_ matches the nonterminal in the Rust
692 syntax named by _designator_. Valid designators are `item`, `block`, `stmt`,
693 `pat`, `expr`, `ty` (type), `ident`, `path`, `matchers` (lhs of the `=>` in
694 macro rules), `tt` (rhs of the `=>` in macro rules). In the transcriber, the
695 designator is already known, and so only the name of a matched nonterminal
696 comes after the dollar sign.
698 In both the matcher and transcriber, the Kleene star-like operator indicates
699 repetition. The Kleene star operator consists of `$` and parens, optionally
700 followed by a separator token, followed by `*` or `+`. `*` means zero or more
701 repetitions, `+` means at least one repetition. The parens are not matched or
702 transcribed. On the matcher side, a name is bound to _all_ of the names it
703 matches, in a structure that mimics the structure of the repetition encountered
704 on a successful match. The job of the transcriber is to sort that structure
707 The rules for transcription of these repetitions are called "Macro By Example".
708 Essentially, one "layer" of repetition is discharged at a time, and all of them
709 must be discharged by the time a name is transcribed. Therefore, `( $( $i:ident
710 ),* ) => ( $i )` is an invalid macro, but `( $( $i:ident ),* ) => ( $( $i:ident
711 ),* )` is acceptable (if trivial).
713 When Macro By Example encounters a repetition, it examines all of the `$`
714 _name_ s that occur in its body. At the "current layer", they all must repeat
715 the same number of times, so ` ( $( $i:ident ),* ; $( $j:ident ),* ) => ( $(
716 ($i,$j) ),* )` is valid if given the argument `(a,b,c ; d,e,f)`, but not
717 `(a,b,c ; d,e)`. The repetition walks through the choices at that layer in
718 lockstep, so the former input transcribes to `( (a,d), (b,e), (c,f) )`.
720 Nested repetitions are allowed.
722 ### Parsing limitations
724 The parser used by the macro system is reasonably powerful, but the parsing of
725 Rust syntax is restricted in two ways:
727 1. The parser will always parse as much as possible. If it attempts to match
728 `$i:expr [ , ]` against `8 [ , ]`, it will attempt to parse `i` as an array
729 index operation and fail. Adding a separator can solve this problem.
730 2. The parser must have eliminated all ambiguity by the time it reaches a `$`
731 _name_ `:` _designator_. This requirement most often affects name-designator
732 pairs when they occur at the beginning of, or immediately after, a `$(...)*`;
733 requiring a distinctive token in front can solve the problem.
735 ## Syntax extensions useful for the macro author
737 * `log_syntax!` : print out the arguments at compile time
738 * `trace_macros!` : supply `true` or `false` to enable or disable macro expansion logging
739 * `stringify!` : turn the identifier argument into a string literal
740 * `concat!` : concatenates a comma-separated list of literals
741 * `concat_idents!` : create a new identifier by concatenating the arguments
743 # Crates and source files
745 Rust is a *compiled* language. Its semantics obey a *phase distinction*
746 between compile-time and run-time. Those semantic rules that have a *static
747 interpretation* govern the success or failure of compilation. We refer to
748 these rules as "static semantics". Semantic rules called "dynamic semantics"
749 govern the behavior of programs at run-time. A program that fails to compile
750 due to violation of a compile-time rule has no defined dynamic semantics; the
751 compiler should halt with an error report, and produce no executable artifact.
753 The compilation model centers on artifacts called _crates_. Each compilation
754 processes a single crate in source form, and if successful, produces a single
755 crate in binary form: either an executable or a library.[^cratesourcefile]
757 [^cratesourcefile]: A crate is somewhat analogous to an *assembly* in the
758 ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit*
759 in the Owens and Flatt module system, or a *configuration* in Mesa.
761 A _crate_ is a unit of compilation and linking, as well as versioning,
762 distribution and runtime loading. A crate contains a _tree_ of nested
763 [module](#modules) scopes. The top level of this tree is a module that is
764 anonymous (from the point of view of paths within the module) and any item
765 within a crate has a canonical [module path](#paths) denoting its location
766 within the crate's module tree.
768 The Rust compiler is always invoked with a single source file as input, and
769 always produces a single output crate. The processing of that source file may
770 result in other source files being loaded as modules. Source files have the
773 A Rust source file describes a module, the name and location of which —
774 in the module tree of the current crate — are defined from outside the
775 source file: either by an explicit `mod_item` in a referencing source file, or
776 by the name of the crate itself.
778 Each source file contains a sequence of zero or more `item` definitions, and
779 may optionally begin with any number of `attributes` that apply to the
780 containing module. Attributes on the anonymous crate module define important
781 metadata that influences the behavior of the compiler.
784 # #![allow(unused_attribute)]
786 #![crate_name = "projx"]
788 // Specify the output type
789 #![crate_type = "lib"]
792 #![warn(non_camel_case_types)]
795 A crate that contains a `main` function can be compiled to an executable. If a
796 `main` function is present, its return type must be [`unit`](#primitive-types)
797 and it must take no arguments.
799 # Items and attributes
801 Crates contain [items](#items), each of which may have some number of
802 [attributes](#attributes) attached to it.
807 item : mod_item | fn_item | type_item | struct_item | enum_item
808 | static_item | trait_item | impl_item | extern_block ;
811 An _item_ is a component of a crate; some module items can be defined in crate
812 files, but most are defined in source files. Items are organized within a crate
813 by a nested set of [modules](#modules). Every crate has a single "outermost"
814 anonymous module; all further items within the crate have [paths](#paths)
815 within the module tree of the crate.
817 Items are entirely determined at compile-time, generally remain fixed during
818 execution, and may reside in read-only memory.
820 There are several kinds of item:
822 * [modules](#modules)
823 * [functions](#functions)
824 * [type definitions](#type-definitions)
825 * [structures](#structures)
826 * [enumerations](#enumerations)
827 * [static items](#static-items)
829 * [implementations](#implementations)
831 Some items form an implicit scope for the declaration of sub-items. In other
832 words, within a function or module, declarations of items can (in many cases)
833 be mixed with the statements, control blocks, and similar artifacts that
834 otherwise compose the item body. The meaning of these scoped items is the same
835 as if the item was declared outside the scope — it is still a static item
836 — except that the item's *path name* within the module namespace is
837 qualified by the name of the enclosing item, or is private to the enclosing
838 item (in the case of functions). The grammar specifies the exact locations in
839 which sub-item declarations may appear.
843 All items except modules may be *parameterized* by type. Type parameters are
844 given as a comma-separated list of identifiers enclosed in angle brackets
845 (`<...>`), after the name of the item and before its definition. The type
846 parameters of an item are considered "part of the name", not part of the type
847 of the item. A referencing [path](#paths) must (in principle) provide type
848 arguments as a list of comma-separated types enclosed within angle brackets, in
849 order to refer to the type-parameterized item. In practice, the type-inference
850 system can usually infer such argument types from context. There are no
851 general type-parametric types, only type-parametric items. That is, Rust has
852 no notion of type abstraction: there are no first-class "forall" types.
857 mod_item : "mod" ident ( ';' | '{' mod '}' );
858 mod : [ view_item | item ] * ;
861 A module is a container for zero or more [view items](#view-items) and zero or
862 more [items](#items). The view items manage the visibility of the items defined
863 within the module, as well as the visibility of names from outside the module
864 when referenced from inside the module.
866 A _module item_ is a module, surrounded in braces, named, and prefixed with the
867 keyword `mod`. A module item introduces a new, named module into the tree of
868 modules making up a crate. Modules can nest arbitrarily.
870 An example of a module:
874 type Complex = (f64, f64);
875 fn sin(f: f64) -> f64 {
879 fn cos(f: f64) -> f64 {
883 fn tan(f: f64) -> f64 {
890 Modules and types share the same namespace. Declaring a named type with
891 the same name as a module in scope is forbidden: that is, a type definition,
892 trait, struct, enumeration, or type parameter can't shadow the name of a module
893 in scope, or vice versa.
895 A module without a body is loaded from an external file, by default with the
896 same name as the module, plus the `.rs` extension. When a nested submodule is
897 loaded from an external file, it is loaded from a subdirectory path that
898 mirrors the module hierarchy.
901 // Load the `vec` module from `vec.rs`
905 // Load the `local_data` module from `thread/local_data.rs`
910 The directories and files used for loading external file modules can be
911 influenced with the `path` attribute.
914 #[path = "thread_files"]
916 // Load the `local_data` module from `thread_files/tls.rs`
925 view_item : extern_crate_decl | use_decl ;
928 A view item manages the namespace of a module. View items do not define new
929 items, but rather, simply change other items' visibility. There are two
932 * [`extern crate` declarations](#extern-crate-declarations)
933 * [`use` declarations](#use-declarations)
935 ##### Extern crate declarations
938 extern_crate_decl : "extern" "crate" crate_name
939 crate_name: ident | ( string_lit "as" ident )
942 An _`extern crate` declaration_ specifies a dependency on an external crate.
943 The external crate is then bound into the declaring scope as the `ident`
944 provided in the `extern_crate_decl`.
946 The external crate is resolved to a specific `soname` at compile time, and a
947 runtime linkage requirement to that `soname` is passed to the linker for
948 loading at runtime. The `soname` is resolved at compile time by scanning the
949 compiler's library path and matching the optional `crateid` provided as a
950 string literal against the `crateid` attributes that were declared on the
951 external crate when it was compiled. If no `crateid` is provided, a default
952 `name` attribute is assumed, equal to the `ident` given in the
955 Three examples of `extern crate` declarations:
960 extern crate std; // equivalent to: extern crate std as std;
962 extern crate "std" as ruststd; // linking to 'std' under another name
965 ##### Use declarations
968 use_decl : "pub" ? "use" [ path "as" ident
971 path_glob : ident [ "::" [ path_glob
973 | '{' path_item [ ',' path_item ] * '}' ;
975 path_item : ident | "mod" ;
978 A _use declaration_ creates one or more local name bindings synonymous with
979 some other [path](#paths). Usually a `use` declaration is used to shorten the
980 path required to refer to a module item. These declarations may appear at the
981 top of [modules](#modules) and [blocks](#blocks).
983 > **Note**: Unlike in many languages,
984 > `use` declarations in Rust do *not* declare linkage dependency with external crates.
985 > Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies.
987 Use declarations support a number of convenient shortcuts:
989 * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`.
990 * Simultaneously binding a list of paths differing only in their final element,
991 using the glob-like brace syntax `use a::b::{c,d,e,f};`
992 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
994 * Simultaneously binding a list of paths differing only in their final element
995 and their immediate parent module, using the `mod` keyword, such as
996 `use a::b::{mod, c, d};`
998 An example of `use` declarations:
1001 use std::iter::range_step;
1002 use std::option::Option::{Some, None};
1003 use std::collections::hash_map::{mod, HashMap};
1006 fn bar(map1: HashMap<String, uint>, map2: hash_map::HashMap<String, uint>){}
1009 // Equivalent to 'std::iter::range_step(0u, 10u, 2u);'
1010 range_step(0u, 10u, 2u);
1012 // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
1013 // std::option::Option::None]);'
1014 foo(vec![Some(1.0f64), None]);
1016 // Both `hash_map` and `HashMap` are in scope.
1017 let map1 = HashMap::new();
1018 let map2 = hash_map::HashMap::new();
1023 Like items, `use` declarations are private to the containing module, by
1024 default. Also like items, a `use` declaration can be public, if qualified by
1025 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
1026 public `use` declaration can therefore _redirect_ some public name to a
1027 different target definition: even a definition with a private canonical path,
1028 inside a different module. If a sequence of such redirections form a cycle or
1029 cannot be resolved unambiguously, they represent a compile-time error.
1031 An example of re-exporting:
1036 pub use quux::foo::{bar, baz};
1045 In this example, the module `quux` re-exports two public names defined in
1048 Also note that the paths contained in `use` items are relative to the crate
1049 root. So, in the previous example, the `use` refers to `quux::foo::{bar,
1050 baz}`, and not simply to `foo::{bar, baz}`. This also means that top-level
1051 module declarations should be at the crate root if direct usage of the declared
1052 modules within `use` items is desired. It is also possible to use `self` and
1053 `super` at the beginning of a `use` item to refer to the current and direct
1054 parent modules respectively. All rules regarding accessing declared modules in
1055 `use` declarations applies to both module declarations and `extern crate`
1058 An example of what will and will not work for `use` items:
1061 # #![allow(unused_imports)]
1062 use foo::core::iter; // good: foo is at the root of the crate
1063 use foo::baz::foobaz; // good: foo is at the root of the crate
1068 use foo::core::iter; // good: foo is at crate root
1069 // use core::iter; // bad: native is not at the crate root
1070 use self::baz::foobaz; // good: self refers to module 'foo'
1071 use foo::bar::foobar; // good: foo is at crate root
1078 use super::bar::foobar; // good: super refers to module 'foo'
1088 A _function item_ defines a sequence of [statements](#statements) and an
1089 optional final [expression](#expressions), along with a name and a set of
1090 parameters. Functions are declared with the keyword `fn`. Functions declare a
1091 set of *input* [*slots*](#memory-slots) as parameters, through which the caller
1092 passes arguments into the function, and an *output* [*slot*](#memory-slots)
1093 through which the function passes results back to the caller.
1095 A function may also be copied into a first class *value*, in which case the
1096 value has the corresponding [*function type*](#function-types), and can be used
1097 otherwise exactly as a function item (with a minor additional cost of calling
1098 the function indirectly).
1100 Every control path in a function logically ends with a `return` expression or a
1101 diverging expression. If the outermost block of a function has a
1102 value-producing expression in its final-expression position, that expression is
1103 interpreted as an implicit `return` expression applied to the final-expression.
1105 An example of a function:
1108 fn add(x: int, y: int) -> int {
1113 As with `let` bindings, function arguments are irrefutable patterns, so any
1114 pattern that is valid in a let binding is also valid as an argument.
1117 fn first((value, _): (int, int)) -> int { value }
1121 #### Generic functions
1123 A _generic function_ allows one or more _parameterized types_ to appear in its
1124 signature. Each type parameter must be explicitly declared, in an
1125 angle-bracket-enclosed, comma-separated list following the function name.
1128 fn iter<T>(seq: &[T], f: |T|) {
1129 for elt in seq.iter() { f(elt); }
1131 fn map<T, U>(seq: &[T], f: |T| -> U) -> Vec<U> {
1132 let mut acc = vec![];
1133 for elt in seq.iter() { acc.push(f(elt)); }
1138 Inside the function signature and body, the name of the type parameter can be
1139 used as a type name.
1141 When a generic function is referenced, its type is instantiated based on the
1142 context of the reference. For example, calling the `iter` function defined
1143 above on `[1, 2]` will instantiate type parameter `T` with `int`, and require
1144 the closure parameter to have type `fn(int)`.
1146 The type parameters can also be explicitly supplied in a trailing
1147 [path](#paths) component after the function name. This might be necessary if
1148 there is not sufficient context to determine the type parameters. For example,
1149 `mem::size_of::<u32>() == 4`.
1151 Since a parameter type is opaque to the generic function, the set of operations
1152 that can be performed on it is limited. Values of parameter type can only be
1156 fn id<T>(x: T) -> T { x }
1159 Similarly, [trait](#traits) bounds can be specified for type parameters to
1160 allow methods with that trait to be called on values of that type.
1164 Unsafe operations are those that potentially violate the memory-safety
1165 guarantees of Rust's static semantics.
1167 The following language level features cannot be used in the safe subset of
1170 - Dereferencing a [raw pointer](#pointer-types).
1171 - Reading or writing a [mutable static variable](#mutable-statics).
1172 - Calling an unsafe function (including an intrinsic or foreign function).
1174 ##### Unsafe functions
1176 Unsafe functions are functions that are not safe in all contexts and/or for all
1177 possible inputs. Such a function must be prefixed with the keyword `unsafe` and
1178 can only be called from an `unsafe` block or another `unsafe` function.
1182 A block of code can be prefixed with the `unsafe` keyword, to permit calling
1183 `unsafe` functions or dereferencing raw pointers within a safe function.
1185 When a programmer has sufficient conviction that a sequence of potentially
1186 unsafe operations is actually safe, they can encapsulate that sequence (taken
1187 as a whole) within an `unsafe` block. The compiler will consider uses of such
1188 code safe, in the surrounding context.
1190 Unsafe blocks are used to wrap foreign libraries, make direct use of hardware
1191 or implement features not directly present in the language. For example, Rust
1192 provides the language features necessary to implement memory-safe concurrency
1193 in the language but the implementation of threads and message passing is in the
1196 Rust's type system is a conservative approximation of the dynamic safety
1197 requirements, so in some cases there is a performance cost to using safe code.
1198 For example, a doubly-linked list is not a tree structure and can only be
1199 represented with reference-counted pointers in safe code. By using `unsafe`
1200 blocks to represent the reverse links as raw pointers, it can be implemented
1203 ##### Behavior considered undefined
1205 The following is a list of behavior which is forbidden in all Rust code,
1206 including within `unsafe` blocks and `unsafe` functions. Type checking provides
1207 the guarantee that these issues are never caused by safe code.
1210 * Dereferencing a null/dangling raw pointer
1211 * Mutating an immutable value/reference without `UnsafeCell`
1212 * Reads of [undef](http://llvm.org/docs/LangRef.html#undefined-values)
1213 (uninitialized) memory
1214 * Breaking the [pointer aliasing
1215 rules](http://llvm.org/docs/LangRef.html#pointer-aliasing-rules)
1216 with raw pointers (a subset of the rules used by C)
1217 * Invoking undefined behavior via compiler intrinsics:
1218 * Indexing outside of the bounds of an object with `std::ptr::offset`
1219 (`offset` intrinsic), with
1220 the exception of one byte past the end which is permitted.
1221 * Using `std::ptr::copy_nonoverlapping_memory` (`memcpy32`/`memcpy64`
1222 instrinsics) on overlapping buffers
1223 * Invalid values in primitive types, even in private fields/locals:
1224 * Dangling/null references or boxes
1225 * A value other than `false` (0) or `true` (1) in a `bool`
1226 * A discriminant in an `enum` not included in the type definition
1227 * A value in a `char` which is a surrogate or above `char::MAX`
1228 * non-UTF-8 byte sequences in a `str`
1229 * Unwinding into Rust from foreign code or unwinding from Rust into foreign
1230 code. Rust's failure system is not compatible with exception handling in
1231 other languages. Unwinding must be caught and handled at FFI boundaries.
1233 ##### Behaviour not considered unsafe
1235 This is a list of behaviour not considered *unsafe* in Rust terms, but that may
1239 * Reading data from private fields (`std::repr`)
1240 * Leaks due to reference count cycles, even in the global heap
1241 * Exiting without calling destructors
1243 * Accessing/modifying the file system
1244 * Unsigned integer overflow (well-defined as wrapping)
1245 * Signed integer overflow (well-defined as two's complement representation
1248 #### Diverging functions
1250 A special kind of function can be declared with a `!` character where the
1251 output slot type would normally be. For example:
1254 fn my_err(s: &str) -> ! {
1260 We call such functions "diverging" because they never return a value to the
1261 caller. Every control path in a diverging function must end with a `panic!()` or
1262 a call to another diverging function on every control path. The `!` annotation
1263 does *not* denote a type. Rather, the result type of a diverging function is a
1264 special type called ⊥ ("bottom") that unifies with any type. Rust has no
1267 It might be necessary to declare a diverging function because as mentioned
1268 previously, the typechecker checks that every control path in a function ends
1269 with a [`return`](#return-expressions) or diverging expression. So, if `my_err`
1270 were declared without the `!` annotation, the following code would not
1274 # fn my_err(s: &str) -> ! { panic!() }
1276 fn f(i: int) -> int {
1281 my_err("Bad number!");
1286 This will not compile without the `!` annotation on `my_err`, since the `else`
1287 branch of the conditional in `f` does not return an `int`, as required by the
1288 signature of `f`. Adding the `!` annotation to `my_err` informs the
1289 typechecker that, should control ever enter `my_err`, no further type judgments
1290 about `f` need to hold, since control will never resume in any context that
1291 relies on those judgments. Thus the return type on `f` only needs to reflect
1292 the `if` branch of the conditional.
1294 #### Extern functions
1296 Extern functions are part of Rust's foreign function interface, providing the
1297 opposite functionality to [external blocks](#external-blocks). Whereas
1298 external blocks allow Rust code to call foreign code, extern functions with
1299 bodies defined in Rust code _can be called by foreign code_. They are defined
1300 in the same way as any other Rust function, except that they have the `extern`
1304 // Declares an extern fn, the ABI defaults to "C"
1305 extern fn new_int() -> int { 0 }
1307 // Declares an extern fn with "stdcall" ABI
1308 extern "stdcall" fn new_int_stdcall() -> int { 0 }
1311 Unlike normal functions, extern fns have an `extern "ABI" fn()`. This is the
1312 same type as the functions declared in an extern block.
1315 # extern fn new_int() -> int { 0 }
1316 let fptr: extern "C" fn() -> int = new_int;
1319 Extern functions may be called directly from Rust code as Rust uses large,
1320 contiguous stack segments like C.
1324 A _type alias_ defines a new name for an existing [type](#types). Type
1325 aliases are declared with the keyword `type`. Every value has a single,
1326 specific type; the type-specified aspects of a value include:
1328 * Whether the value is composed of sub-values or is indivisible.
1329 * Whether the value represents textual or numerical information.
1330 * Whether the value represents integral or floating-point information.
1331 * The sequence of memory operations required to access the value.
1332 * The [kind](#type-kinds) of the type.
1334 For example, the type `(u8, u8)` defines the set of immutable values that are
1335 composite pairs, each containing two unsigned 8-bit integers accessed by
1336 pattern-matching and laid out in memory with the `x` component preceding the
1340 type Point = (u8, u8);
1341 let p: Point = (41, 68);
1346 A _structure_ is a nominal [structure type](#structure-types) defined with the
1349 An example of a `struct` item and its use:
1352 struct Point {x: int, y: int}
1353 let p = Point {x: 10, y: 11};
1357 A _tuple structure_ is a nominal [tuple type](#tuple-types), also defined with
1358 the keyword `struct`. For example:
1361 struct Point(int, int);
1362 let p = Point(10, 11);
1363 let px: int = match p { Point(x, _) => x };
1366 A _unit-like struct_ is a structure without any fields, defined by leaving off
1367 the list of fields entirely. Such types will have a single value, just like
1368 the [unit value `()`](#unit-and-boolean-literals) of the unit type. For
1373 let c = [Cookie, Cookie, Cookie, Cookie];
1376 The precise memory layout of a structure is not specified. One can specify a
1377 particular layout using the [`repr` attribute](#ffi-attributes).
1381 An _enumeration_ is a simultaneous definition of a nominal [enumerated
1382 type](#enumerated-types) as well as a set of *constructors*, that can be used
1383 to create or pattern-match values of the corresponding enumerated type.
1385 Enumerations are declared with the keyword `enum`.
1387 An example of an `enum` item and its use:
1395 let mut a: Animal = Animal::Dog;
1399 Enumeration constructors can have either named or unnamed fields:
1402 # #![feature(struct_variant)]
1406 Cat { name: String, weight: f64 }
1409 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
1410 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
1414 In this example, `Cat` is a _struct-like enum variant_,
1415 whereas `Dog` is simply called an enum variant.
1420 const_item : "const" ident ':' type '=' expr ';' ;
1423 A *constant item* is a named _constant value_ which is not associated with a
1424 specific memory location in the program. Constants are essentially inlined
1425 wherever they are used, meaning that they are copied directly into the relevant
1426 context when used. References to the same constant are not necessarily
1427 guaranteed to refer to the same memory address.
1429 Constant values must not have destructors, and otherwise permit most forms of
1430 data. Constants may refer to the address of other constants, in which case the
1431 address will have the `static` lifetime. The compiler is, however, still at
1432 liberty to translate the constant many times, so the address referred to may not
1435 Constants must be explicitly typed. The type may be `bool`, `char`, a number, or
1436 a type derived from those primitive types. The derived types are references with
1437 the `static` lifetime, fixed-size arrays, tuples, enum variants, and structs.
1440 const BIT1: uint = 1 << 0;
1441 const BIT2: uint = 1 << 1;
1443 const BITS: [uint; 2] = [BIT1, BIT2];
1444 const STRING: &'static str = "bitstring";
1446 struct BitsNStrings<'a> {
1451 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
1460 static_item : "static" ident ':' type '=' expr ';' ;
1463 A *static item* is similar to a *constant*, except that it represents a precise
1464 memory location in the program. A static is never "inlined" at the usage site,
1465 and all references to it refer to the same memory location. Static items have
1466 the `static` lifetime, which outlives all other lifetimes in a Rust program.
1467 Static items may be placed in read-only memory if they do not contain any
1468 interior mutability.
1470 Statics may contain interior mutability through the `UnsafeCell` language item.
1471 All access to a static is safe, but there are a number of restrictions on
1474 * Statics may not contain any destructors.
1475 * The types of static values must ascribe to `Sync` to allow threadsafe access.
1476 * Statics may not refer to other statics by value, only by reference.
1477 * Constants cannot refer to statics.
1479 Constants should in general be preferred over statics, unless large amounts of
1480 data are being stored, or single-address and mutability properties are required.
1483 use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};;
1485 // Note that ATOMIC_UINT_INIT is a *const*, but it may be used to initialize a
1486 // static. This static can be modified, so it is not placed in read-only memory.
1487 static COUNTER: AtomicUint = ATOMIC_UINT_INIT;
1489 // This table is a candidate to be placed in read-only memory.
1490 static TABLE: &'static [uint] = &[1, 2, 3, /* ... */];
1492 for slot in TABLE.iter() {
1493 println!("{}", slot);
1495 COUNTER.fetch_add(1, Ordering::SeqCst);
1498 #### Mutable statics
1500 If a static item is declared with the `mut` keyword, then it is allowed to
1501 be modified by the program. One of Rust's goals is to make concurrency bugs
1502 hard to run into, and this is obviously a very large source of race conditions
1503 or other bugs. For this reason, an `unsafe` block is required when either
1504 reading or writing a mutable static variable. Care should be taken to ensure
1505 that modifications to a mutable static are safe with respect to other threads
1506 running in the same process.
1508 Mutable statics are still very useful, however. They can be used with C
1509 libraries and can also be bound from C libraries (in an `extern` block).
1512 # fn atomic_add(_: &mut uint, _: uint) -> uint { 2 }
1514 static mut LEVELS: uint = 0;
1516 // This violates the idea of no shared state, and this doesn't internally
1517 // protect against races, so this function is `unsafe`
1518 unsafe fn bump_levels_unsafe1() -> uint {
1524 // Assuming that we have an atomic_add function which returns the old value,
1525 // this function is "safe" but the meaning of the return value may not be what
1526 // callers expect, so it's still marked as `unsafe`
1527 unsafe fn bump_levels_unsafe2() -> uint {
1528 return atomic_add(&mut LEVELS, 1);
1532 Mutable statics have the same restrictions as normal statics, except that the
1533 type of the value is not required to ascribe to `Sync`.
1537 A _trait_ describes a set of method types.
1539 Traits can include default implementations of methods, written in terms of some
1540 unknown [`self` type](#self-types); the `self` type may either be completely
1541 unspecified, or constrained by some other trait.
1543 Traits are implemented for specific types through separate
1544 [implementations](#implementations).
1547 # type Surface = int;
1548 # type BoundingBox = int;
1550 fn draw(&self, Surface);
1551 fn bounding_box(&self) -> BoundingBox;
1555 This defines a trait with two methods. All values that have
1556 [implementations](#implementations) of this trait in scope can have their
1557 `draw` and `bounding_box` methods called, using `value.bounding_box()`
1558 [syntax](#method-call-expressions).
1560 Type parameters can be specified for a trait to make it generic. These appear
1561 after the trait name, using the same syntax used in [generic
1562 functions](#generic-functions).
1566 fn len(&self) -> uint;
1567 fn elt_at(&self, n: uint) -> T;
1568 fn iter<F>(&self, F) where F: Fn(T);
1572 Generic functions may use traits as _bounds_ on their type parameters. This
1573 will have two effects: only types that have the trait may instantiate the
1574 parameter, and within the generic function, the methods of the trait can be
1575 called on values that have the parameter's type. For example:
1578 # type Surface = int;
1579 # trait Shape { fn draw(&self, Surface); }
1580 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
1586 Traits also define an [object type](#object-types) with the same name as the
1587 trait. Values of this type are created by [casting](#type-cast-expressions)
1588 pointer values (pointing to a type for which an implementation of the given
1589 trait is in scope) to pointers to the trait name, used as a type.
1593 # impl Shape for int { }
1594 # let mycircle = 0i;
1595 let myshape: Box<Shape> = box mycircle as Box<Shape>;
1598 The resulting value is a box containing the value that was cast, along with
1599 information that identifies the methods of the implementation that was used.
1600 Values with a trait type can have [methods called](#method-call-expressions) on
1601 them, for any method in the trait, and can be used to instantiate type
1602 parameters that are bounded by the trait.
1604 Trait methods may be static, which means that they lack a `self` argument.
1605 This means that they can only be called with function call syntax (`f(x)`) and
1606 not method call syntax (`obj.f()`). The way to refer to the name of a static
1607 method is to qualify it with the trait name, treating the trait name like a
1608 module. For example:
1612 fn from_int(n: int) -> Self;
1615 fn from_int(n: int) -> f64 { n as f64 }
1617 let x: f64 = Num::from_int(42);
1620 Traits may inherit from other traits. For example, in
1623 trait Shape { fn area() -> f64; }
1624 trait Circle : Shape { fn radius() -> f64; }
1627 the syntax `Circle : Shape` means that types that implement `Circle` must also
1628 have an implementation for `Shape`. Multiple supertraits are separated by `+`,
1629 `trait Circle : Shape + PartialEq { }`. In an implementation of `Circle` for a
1630 given type `T`, methods can refer to `Shape` methods, since the typechecker
1631 checks that any type with an implementation of `Circle` also has an
1632 implementation of `Shape`.
1634 In type-parameterized functions, methods of the supertrait may be called on
1635 values of subtrait-bound type parameters. Referring to the previous example of
1636 `trait Circle : Shape`:
1639 # trait Shape { fn area(&self) -> f64; }
1640 # trait Circle : Shape { fn radius(&self) -> f64; }
1641 fn radius_times_area<T: Circle>(c: T) -> f64 {
1642 // `c` is both a Circle and a Shape
1643 c.radius() * c.area()
1647 Likewise, supertrait methods may also be called on trait objects.
1650 # trait Shape { fn area(&self) -> f64; }
1651 # trait Circle : Shape { fn radius(&self) -> f64; }
1652 # impl Shape for int { fn area(&self) -> f64 { 0.0 } }
1653 # impl Circle for int { fn radius(&self) -> f64 { 0.0 } }
1655 let mycircle = box mycircle as Box<Circle>;
1656 let nonsense = mycircle.radius() * mycircle.area();
1661 An _implementation_ is an item that implements a [trait](#traits) for a
1664 Implementations are defined with the keyword `impl`.
1667 # struct Point {x: f64, y: f64};
1668 # impl Copy for Point {}
1669 # type Surface = int;
1670 # struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
1671 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
1672 # fn do_draw_circle(s: Surface, c: Circle) { }
1678 impl Copy for Circle {}
1680 impl Shape for Circle {
1681 fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
1682 fn bounding_box(&self) -> BoundingBox {
1683 let r = self.radius;
1684 BoundingBox{x: self.center.x - r, y: self.center.y - r,
1685 width: 2.0 * r, height: 2.0 * r}
1690 It is possible to define an implementation without referring to a trait. The
1691 methods in such an implementation can only be used as direct calls on the
1692 values of the type that the implementation targets. In such an implementation,
1693 the trait type and `for` after `impl` are omitted. Such implementations are
1694 limited to nominal types (enums, structs), and the implementation must appear
1695 in the same module or a sub-module as the `self` type:
1698 struct Point {x: int, y: int}
1702 println!("Point is at ({}, {})", self.x, self.y);
1706 let my_point = Point {x: 10, y:11};
1710 When a trait _is_ specified in an `impl`, all methods declared as part of the
1711 trait must be implemented, with matching types and type parameter counts.
1713 An implementation can take type parameters, which can be different from the
1714 type parameters taken by the trait it implements. Implementation parameters
1715 are written after the `impl` keyword.
1719 impl<T> Seq<T> for Vec<T> {
1722 impl Seq<bool> for u32 {
1723 /* Treat the integer as a sequence of bits */
1730 extern_block_item : "extern" '{' extern_block '}' ;
1731 extern_block : [ foreign_fn ] * ;
1734 External blocks form the basis for Rust's foreign function interface.
1735 Declarations in an external block describe symbols in external, non-Rust
1738 Functions within external blocks are declared in the same way as other Rust
1739 functions, with the exception that they may not have a body and are instead
1740 terminated by a semicolon.
1744 use libc::{c_char, FILE};
1747 fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE;
1752 Functions within external blocks may be called by Rust code, just like
1753 functions defined in Rust. The Rust compiler automatically translates between
1754 the Rust ABI and the foreign ABI.
1756 A number of [attributes](#attributes) control the behavior of external blocks.
1758 By default external blocks assume that the library they are calling uses the
1759 standard C "cdecl" ABI. Other ABIs may be specified using an `abi` string, as
1763 // Interface to the Windows API
1764 extern "stdcall" { }
1767 The `link` attribute allows the name of the library to be specified. When
1768 specified the compiler will attempt to link against the native library of the
1772 #[link(name = "crypto")]
1776 The type of a function declared in an extern block is `extern "abi" fn(A1, ...,
1777 An) -> R`, where `A1...An` are the declared types of its arguments and `R` is
1778 the declared return type.
1780 ## Visibility and Privacy
1782 These two terms are often used interchangeably, and what they are attempting to
1783 convey is the answer to the question "Can this item be used at this location?"
1785 Rust's name resolution operates on a global hierarchy of namespaces. Each level
1786 in the hierarchy can be thought of as some item. The items are one of those
1787 mentioned above, but also include external crates. Declaring or defining a new
1788 module can be thought of as inserting a new tree into the hierarchy at the
1789 location of the definition.
1791 To control whether interfaces can be used across modules, Rust checks each use
1792 of an item to see whether it should be allowed or not. This is where privacy
1793 warnings are generated, or otherwise "you used a private item of another module
1794 and weren't allowed to."
1796 By default, everything in Rust is *private*, with one exception. Enum variants
1797 in a `pub` enum are also public by default. You are allowed to alter this
1798 default visibility with the `priv` keyword. When an item is declared as `pub`,
1799 it can be thought of as being accessible to the outside world. For example:
1802 # #![allow(missing_copy_implementations)]
1804 // Declare a private struct
1807 // Declare a public struct with a private field
1812 // Declare a public enum with two public variants
1814 PubliclyAccessibleState,
1815 PubliclyAccessibleState2,
1819 With the notion of an item being either public or private, Rust allows item
1820 accesses in two cases:
1822 1. If an item is public, then it can be used externally through any of its
1824 2. If an item is private, it may be accessed by the current module and its
1827 These two cases are surprisingly powerful for creating module hierarchies
1828 exposing public APIs while hiding internal implementation details. To help
1829 explain, here's a few use cases and what they would entail.
1831 * A library developer needs to expose functionality to crates which link
1832 against their library. As a consequence of the first case, this means that
1833 anything which is usable externally must be `pub` from the root down to the
1834 destination item. Any private item in the chain will disallow external
1837 * A crate needs a global available "helper module" to itself, but it doesn't
1838 want to expose the helper module as a public API. To accomplish this, the
1839 root of the crate's hierarchy would have a private module which then
1840 internally has a "public api". Because the entire crate is a descendant of
1841 the root, then the entire local crate can access this private module through
1844 * When writing unit tests for a module, it's often a common idiom to have an
1845 immediate child of the module to-be-tested named `mod test`. This module
1846 could access any items of the parent module through the second case, meaning
1847 that internal implementation details could also be seamlessly tested from the
1850 In the second case, it mentions that a private item "can be accessed" by the
1851 current module and its descendants, but the exact meaning of accessing an item
1852 depends on what the item is. Accessing a module, for example, would mean
1853 looking inside of it (to import more items). On the other hand, accessing a
1854 function would mean that it is invoked. Additionally, path expressions and
1855 import statements are considered to access an item in the sense that the
1856 import/expression is only valid if the destination is in the current visibility
1859 Here's an example of a program which exemplifies the three cases outlined
1863 // This module is private, meaning that no external crate can access this
1864 // module. Because it is private at the root of this current crate, however, any
1865 // module in the crate may access any publicly visible item in this module.
1866 mod crate_helper_module {
1868 // This function can be used by anything in the current crate
1869 pub fn crate_helper() {}
1871 // This function *cannot* be used by anything else in the crate. It is not
1872 // publicly visible outside of the `crate_helper_module`, so only this
1873 // current module and its descendants may access it.
1874 fn implementation_detail() {}
1877 // This function is "public to the root" meaning that it's available to external
1878 // crates linking against this one.
1879 pub fn public_api() {}
1881 // Similarly to 'public_api', this module is public so external crates may look
1884 use crate_helper_module;
1886 pub fn my_method() {
1887 // Any item in the local crate may invoke the helper module's public
1888 // interface through a combination of the two rules above.
1889 crate_helper_module::crate_helper();
1892 // This function is hidden to any module which is not a descendant of
1894 fn my_implementation() {}
1900 fn test_my_implementation() {
1901 // Because this module is a descendant of `submodule`, it's allowed
1902 // to access private items inside of `submodule` without a privacy
1904 super::my_implementation();
1912 For a rust program to pass the privacy checking pass, all paths must be valid
1913 accesses given the two rules above. This includes all use statements,
1914 expressions, types, etc.
1916 ### Re-exporting and Visibility
1918 Rust allows publicly re-exporting items through a `pub use` directive. Because
1919 this is a public directive, this allows the item to be used in the current
1920 module through the rules above. It essentially allows public access into the
1921 re-exported item. For example, this program is valid:
1924 pub use self::implementation as api;
1926 mod implementation {
1933 This means that any external crate referencing `implementation::f` would
1934 receive a privacy violation, while the path `api::f` would be allowed.
1936 When re-exporting a private item, it can be thought of as allowing the "privacy
1937 chain" being short-circuited through the reexport instead of passing through
1938 the namespace hierarchy as it normally would.
1943 attribute : "#!" ? '[' meta_item ']' ;
1944 meta_item : ident [ '=' literal
1945 | '(' meta_seq ')' ] ? ;
1946 meta_seq : meta_item [ ',' meta_seq ] ? ;
1949 Any item declaration may have an _attribute_ applied to it. Attributes in Rust
1950 are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334
1951 (C#). An attribute is a general, free-form metadatum that is interpreted
1952 according to name, convention, and language and compiler version. Attributes
1953 may appear as any of:
1955 * A single identifier, the attribute name
1956 * An identifier followed by the equals sign '=' and a literal, providing a
1958 * An identifier followed by a parenthesized list of sub-attribute arguments
1960 Attributes with a bang ("!") after the hash ("#") apply to the item that the
1961 attribute is declared within. Attributes that do not have a bang after the hash
1962 apply to the item that follows the attribute.
1964 An example of attributes:
1967 // General metadata applied to the enclosing module or crate.
1968 #![crate_type = "lib"]
1970 // A function marked as a unit test
1976 // A conditionally-compiled module
1977 #[cfg(target_os="linux")]
1982 // A lint attribute used to suppress a warning/error
1983 #[allow(non_camel_case_types)]
1987 > **Note:** At some point in the future, the compiler will distinguish between
1988 > language-reserved and user-available attributes. Until then, there is
1989 > effectively no difference between an attribute handled by a loadable syntax
1990 > extension and the compiler.
1992 ### Crate-only attributes
1994 - `crate_name` - specify the this crate's crate name.
1995 - `crate_type` - see [linkage](#linkage).
1996 - `feature` - see [compiler features](#compiler-features).
1997 - `no_builtins` - disable optimizing certain code patterns to invocations of
1998 library functions that are assumed to exist
1999 - `no_main` - disable emitting the `main` symbol. Useful when some other
2000 object being linked to defines `main`.
2001 - `no_start` - disable linking to the `native` crate, which specifies the
2002 "start" language item.
2003 - `no_std` - disable linking to the `std` crate.
2005 ### Module-only attributes
2007 - `no_implicit_prelude` - disable injecting `use std::prelude::*` in this
2009 - `path` - specifies the file to load the module from. `#[path="foo.rs"] mod
2010 bar;` is equivalent to `mod bar { /* contents of foo.rs */ }`. The path is
2011 taken relative to the directory that the current module is in.
2013 ### Function-only attributes
2015 - `main` - indicates that this function should be passed to the entry point,
2016 rather than the function in the crate root named `main`.
2017 - `plugin_registrar` - mark this function as the registration point for
2018 [compiler plugins][plugin], such as loadable syntax extensions.
2019 - `start` - indicates that this function should be used as the entry point,
2020 overriding the "start" language item. See the "start" [language
2021 item](#language-items) for more details.
2022 - `test` - indicates that this function is a test function, to only be compiled
2023 in case of `--test`.
2025 ### Static-only attributes
2027 - `thread_local` - on a `static mut`, this signals that the value of this
2028 static may change depending on the current thread. The exact consequences of
2029 this are implementation-defined.
2033 On an `extern` block, the following attributes are interpreted:
2035 - `link_args` - specify arguments to the linker, rather than just the library
2036 name and type. This is feature gated and the exact behavior is
2037 implementation-defined (due to variety of linker invocation syntax).
2038 - `link` - indicate that a native library should be linked to for the
2039 declarations in this block to be linked correctly. `link` supports an optional `kind`
2040 key with three possible values: `dylib`, `static`, and `framework`. See [external blocks](#external-blocks) for more about external blocks. Two
2041 examples: `#[link(name = "readline")]` and
2042 `#[link(name = "CoreFoundation", kind = "framework")]`.
2044 On declarations inside an `extern` block, the following attributes are
2047 - `link_name` - the name of the symbol that this function or static should be
2049 - `linkage` - on a static, this specifies the [linkage
2050 type](http://llvm.org/docs/LangRef.html#linkage-types).
2054 - `repr` - on C-like enums, this sets the underlying type used for
2055 representation. Takes one argument, which is the primitive
2056 type this enum should be represented for, or `C`, which specifies that it
2057 should be the default `enum` size of the C ABI for that platform. Note that
2058 enum representation in C is undefined, and this may be incorrect when the C
2059 code is compiled with certain flags.
2063 - `repr` - specifies the representation to use for this struct. Takes a list
2064 of options. The currently accepted ones are `C` and `packed`, which may be
2065 combined. `C` will use a C ABI compatible struct layout, and `packed` will
2066 remove any padding between fields (note that this is very fragile and may
2067 break platforms which require aligned access).
2069 ### Macro- and plugin-related attributes
2071 - `macro_use` on a `mod` — macros defined in this module will be visible in the
2072 module's parent, after this module has been included.
2074 - `macro_use` on an `extern crate` — load macros from this crate. An optional
2075 list of names `#[macro_use(foo, bar)]` restricts the import to just those
2076 macros named. The `extern crate` must appear at the crate root, not inside
2077 `mod`, which ensures proper function of the [`$crate` macro
2078 variable](guide-macros.html#the-variable-$crate).
2080 - `macro_reexport` on an `extern crate` — re-export the named macros.
2082 - `macro_export` - export a macro for cross-crate usage.
2084 - `plugin` on an `extern crate` — load this crate as a [compiler
2085 plugin][plugin]. The `plugin` feature gate is required. Any arguments to
2086 the attribute, e.g. `#[plugin=...]` or `#[plugin(...)]`, are provided to the
2089 - `no_link` on an `extern crate` — even if we load this crate for macros or
2090 compiler plugins, don't link it into the output.
2092 See the [macros guide](guide-macros.html#scoping-and-macro-import/export) for
2093 more information on macro scope.
2096 ### Miscellaneous attributes
2098 - `export_name` - on statics and functions, this determines the name of the
2100 - `link_section` - on statics and functions, this specifies the section of the
2101 object file that this item's contents will be placed into.
2102 - `no_mangle` - on any item, do not apply the standard name mangling. Set the
2103 symbol for this item to its identifier.
2104 - `packed` - on structs or enums, eliminate any padding that would be used to
2106 - `simd` - on certain tuple structs, derive the arithmetic operators, which
2107 lower to the target's SIMD instructions, if any; the `simd` feature gate
2108 is necessary to use this attribute.
2109 - `static_assert` - on statics whose type is `bool`, terminates compilation
2110 with an error if it is not initialized to `true`.
2111 - `unsafe_destructor` - allow implementations of the "drop" language item
2112 where the type it is implemented for does not implement the "send" language
2113 item; the `unsafe_destructor` feature gate is needed to use this attribute
2114 - `unsafe_no_drop_flag` - on structs, remove the flag that prevents
2115 destructors from being run twice. Destructors might be run multiple times on
2116 the same object with this attribute.
2117 - `doc` - Doc comments such as `/// foo` are equivalent to `#[doc = "foo"]`.
2119 ### Conditional compilation
2121 Sometimes one wants to have different compiler outputs from the same code,
2122 depending on build target, such as targeted operating system, or to enable
2125 There are two kinds of configuration options, one that is either defined or not
2126 (`#[cfg(foo)]`), and the other that contains a string that can be checked
2127 against (`#[cfg(bar = "baz")]` (currently only compiler-defined configuration
2128 options can have the latter form).
2131 // The function is only included in the build when compiling for OSX
2132 #[cfg(target_os = "macos")]
2137 // This function is only included when either foo or bar is defined
2138 #[cfg(any(foo, bar))]
2139 fn needs_foo_or_bar() {
2143 // This function is only included when compiling for a unixish OS with a 32-bit
2145 #[cfg(all(unix, target_word_size = "32"))]
2146 fn on_32bit_unix() {
2150 // This function is only included when foo is not defined
2152 fn needs_not_foo() {
2157 This illustrates some conditional compilation can be achieved using the
2158 `#[cfg(...)]` attribute. `any`, `all` and `not` can be used to assemble
2159 arbitrarily complex configurations through nesting.
2161 The following configurations must be defined by the implementation:
2163 * `target_arch = "..."`. Target CPU architecture, such as `"x86"`, `"x86_64"`
2164 `"mips"`, `"arm"`, or `"aarch64"`.
2165 * `target_endian = "..."`. Endianness of the target CPU, either `"little"` or
2167 * `target_family = "..."`. Operating system family of the target, e. g.
2168 `"unix"` or `"windows"`. The value of this configuration option is defined
2169 as a configuration itself, like `unix` or `windows`.
2170 * `target_os = "..."`. Operating system of the target, examples include
2171 `"win32"`, `"macos"`, `"linux"`, `"android"`, `"freebsd"` or `"dragonfly"`.
2172 * `target_word_size = "..."`. Target word size in bits. This is set to `"32"`
2173 for targets with 32-bit pointers, and likewise set to `"64"` for 64-bit
2175 * `unix`. See `target_family`.
2176 * `windows`. See `target_family`.
2178 ### Lint check attributes
2180 A lint check names a potentially undesirable coding pattern, such as
2181 unreachable code or omitted documentation, for the static entity to which the
2184 For any lint check `C`:
2186 * `allow(C)` overrides the check for `C` so that violations will go
2188 * `deny(C)` signals an error after encountering a violation of `C`,
2189 * `forbid(C)` is the same as `deny(C)`, but also forbids changing the lint
2191 * `warn(C)` warns about violations of `C` but continues compilation.
2193 The lint checks supported by the compiler can be found via `rustc -W help`,
2194 along with their default settings. [Compiler
2195 plugins](guide-plugin.html#lint-plugins) can provide additional lint checks.
2199 // Missing documentation is ignored here
2200 #[allow(missing_docs)]
2201 pub fn undocumented_one() -> int { 1 }
2203 // Missing documentation signals a warning here
2204 #[warn(missing_docs)]
2205 pub fn undocumented_too() -> int { 2 }
2207 // Missing documentation signals an error here
2208 #[deny(missing_docs)]
2209 pub fn undocumented_end() -> int { 3 }
2213 This example shows how one can use `allow` and `warn` to toggle a particular
2217 #[warn(missing_docs)]
2219 #[allow(missing_docs)]
2221 // Missing documentation is ignored here
2222 pub fn undocumented_one() -> int { 1 }
2224 // Missing documentation signals a warning here,
2225 // despite the allow above.
2226 #[warn(missing_docs)]
2227 pub fn undocumented_two() -> int { 2 }
2230 // Missing documentation signals a warning here
2231 pub fn undocumented_too() -> int { 3 }
2235 This example shows how one can use `forbid` to disallow uses of `allow` for
2239 #[forbid(missing_docs)]
2241 // Attempting to toggle warning signals an error here
2242 #[allow(missing_docs)]
2244 pub fn undocumented_too() -> int { 2 }
2250 Some primitive Rust operations are defined in Rust code, rather than being
2251 implemented directly in C or assembly language. The definitions of these
2252 operations have to be easy for the compiler to find. The `lang` attribute
2253 makes it possible to declare these operations. For example, the `str` module
2254 in the Rust standard library defines the string equality function:
2258 pub fn eq_slice(a: &str, b: &str) -> bool {
2263 The name `str_eq` has a special meaning to the Rust compiler, and the presence
2264 of this definition means that it will use this definition when generating calls
2265 to the string equality function.
2267 A complete list of the built-in language items follows:
2269 #### Built-in Traits
2272 : Types that do not move ownership when used by-value.
2276 : Able to be sent across thread boundaries.
2278 : Has a size known at compile time.
2280 : Able to be safely shared between threads when aliased.
2284 These language items are traits:
2287 : Elements can be added (for example, integers and floats).
2289 : Elements can be subtracted.
2291 : Elements can be multiplied.
2293 : Elements have a division operation.
2295 : Elements have a remainder operation.
2297 : Elements can be negated arithmetically.
2299 : Elements can be negated logically.
2301 : Elements have an exclusive-or operation.
2303 : Elements have a bitwise `and` operation.
2305 : Elements have a bitwise `or` operation.
2307 : Elements have a left shift operation.
2309 : Elements have a right shift operation.
2311 : Elements can be indexed.
2313 : ___Needs filling in___
2315 : Elements can be compared for equality.
2317 : Elements have a partial ordering.
2319 : `*` can be applied, yielding a reference to another type
2321 : `*` can be applied, yielding a mutable reference to another type
2323 These are functions:
2326 : ___Needs filling in___
2328 : ___Needs filling in___
2330 : ___Needs filling in___
2332 : Compare two strings (`&str`) for equality.
2334 : Return a new unique string
2335 containing a copy of the contents of a unique string.
2340 : The type returned by the `type_id` intrinsic.
2342 : A type whose contents can be mutated through an immutable reference
2346 These types help drive the compiler's analysis
2349 : ___Needs filling in___
2351 : This type does not implement "copy", even if eligible
2353 : This type does not implement "send", even if eligible
2355 : This type does not implement "sync", even if eligible
2357 : ___Needs filling in___
2359 : Free memory that was allocated on the exchange heap.
2361 : Allocate memory on the exchange heap.
2362 * `closure_exchange_malloc`
2363 : ___Needs filling in___
2365 : Abort the program with an error.
2366 * `fail_bounds_check`
2367 : Abort the program with a bounds check error.
2369 : Free memory that was allocated on the managed heap.
2371 : ___Needs filling in___
2373 : ___Needs filling in___
2375 : ___Needs filling in___
2376 * `contravariant_lifetime`
2377 : The lifetime parameter should be considered contravariant
2378 * `covariant_lifetime`
2379 : The lifetime parameter should be considered covariant
2380 * `invariant_lifetime`
2381 : The lifetime parameter should be considered invariant
2383 : Allocate memory on the managed heap.
2385 : ___Needs filling in___
2387 : ___Needs filling in___
2389 : ___Needs filling in___
2390 * `contravariant_type`
2391 : The type parameter should be considered contravariant
2393 : The type parameter should be considered covariant
2395 : The type parameter should be considered invariant
2397 : ___Needs filling in___
2399 > **Note:** This list is likely to become out of date. We should auto-generate
2400 > it from `librustc/middle/lang_items.rs`.
2402 ### Inline attributes
2404 The inline attribute is used to suggest to the compiler to perform an inline
2405 expansion and place a copy of the function or static in the caller rather than
2406 generating code to call the function or access the static where it is defined.
2408 The compiler automatically inlines functions based on internal heuristics.
2409 Incorrectly inlining functions can actually making the program slower, so it
2410 should be used with care.
2412 Immutable statics are always considered inlineable unless marked with
2413 `#[inline(never)]`. It is undefined whether two different inlineable statics
2414 have the same memory address. In other words, the compiler is free to collapse
2415 duplicate inlineable statics together.
2417 `#[inline]` and `#[inline(always)]` always causes the function to be serialized
2418 into crate metadata to allow cross-crate inlining.
2420 There are three different types of inline attributes:
2422 * `#[inline]` hints the compiler to perform an inline expansion.
2423 * `#[inline(always)]` asks the compiler to always perform an inline expansion.
2424 * `#[inline(never)]` asks the compiler to never perform an inline expansion.
2428 The `deriving` attribute allows certain traits to be automatically implemented
2429 for data structures. For example, the following will create an `impl` for the
2430 `PartialEq` and `Clone` traits for `Foo`, the type parameter `T` will be given
2431 the `PartialEq` or `Clone` constraints for the appropriate `impl`:
2434 #[deriving(PartialEq, Clone)]
2441 The generated `impl` for `PartialEq` is equivalent to
2444 # struct Foo<T> { a: int, b: T }
2445 impl<T: PartialEq> PartialEq for Foo<T> {
2446 fn eq(&self, other: &Foo<T>) -> bool {
2447 self.a == other.a && self.b == other.b
2450 fn ne(&self, other: &Foo<T>) -> bool {
2451 self.a != other.a || self.b != other.b
2456 Supported traits for `deriving` are:
2458 * Comparison traits: `PartialEq`, `Eq`, `PartialOrd`, `Ord`.
2459 * Serialization: `Encodable`, `Decodable`. These require `serialize`.
2460 * `Clone`, to create `T` from `&T` via a copy.
2461 * `Default`, to create an empty instance of a data type.
2462 * `FromPrimitive`, to create an instance from a numeric primitive.
2463 * `Hash`, to iterate over the bytes in a data type.
2464 * `Rand`, to create a random instance of a data type.
2465 * `Show`, to format a value using the `{}` formatter.
2466 * `Zero`, to create a zero instance of a numeric data type.
2470 One can indicate the stability of an API using the following attributes:
2472 * `deprecated`: This item should no longer be used, e.g. it has been
2473 replaced. No guarantee of backwards-compatibility.
2474 * `experimental`: This item was only recently introduced or is
2475 otherwise in a state of flux. It may change significantly, or even
2476 be removed. No guarantee of backwards-compatibility.
2477 * `unstable`: This item is still under development, but requires more
2478 testing to be considered stable. No guarantee of backwards-compatibility.
2479 * `stable`: This item is considered stable, and will not change
2480 significantly. Guarantee of backwards-compatibility.
2481 * `frozen`: This item is very stable, and is unlikely to
2482 change. Guarantee of backwards-compatibility.
2483 * `locked`: This item will never change unless a serious bug is
2484 found. Guarantee of backwards-compatibility.
2486 These levels are directly inspired by
2487 [Node.js' "stability index"](http://nodejs.org/api/documentation.html).
2489 Stability levels are inherited, so an item's stability attribute is the default
2490 stability for everything nested underneath it.
2492 There are lints for disallowing items marked with certain levels: `deprecated`,
2493 `experimental` and `unstable`. For now, only `deprecated` warns by default, but
2494 this will change once the standard library has been stabilized. Stability
2495 levels are meant to be promises at the crate level, so these lints only apply
2496 when referencing items from an _external_ crate, not to items defined within
2497 the current crate. Items with no stability level are considered to be unstable
2498 for the purposes of the lint. One can give an optional string that will be
2499 displayed when the lint flags the use of an item.
2501 For example, if we define one crate called `stability_levels`:
2504 #[deprecated="replaced by `best`"]
2506 // delete everything
2510 // delete fewer things
2519 then the lints will work as follows for a client crate:
2523 extern crate stability_levels;
2524 use stability_levels::{bad, better, best};
2527 bad(); // "warning: use of deprecated item: replaced by `best`"
2529 better(); // "warning: use of unmarked item"
2531 best(); // no warning
2535 > **Note:** Currently these are only checked when applied to individual
2536 > functions, structs, methods and enum variants, *not* to entire modules,
2537 > traits, impls or enums themselves.
2539 ### Compiler Features
2541 Certain aspects of Rust may be implemented in the compiler, but they're not
2542 necessarily ready for every-day use. These features are often of "prototype
2543 quality" or "almost production ready", but may not be stable enough to be
2544 considered a full-fledged language feature.
2546 For this reason, Rust recognizes a special crate-level attribute of the form:
2549 #![feature(feature1, feature2, feature3)]
2552 This directive informs the compiler that the feature list: `feature1`,
2553 `feature2`, and `feature3` should all be enabled. This is only recognized at a
2554 crate-level, not at a module-level. Without this directive, all features are
2555 considered off, and using the features will result in a compiler error.
2557 The currently implemented features of the reference compiler are:
2559 * `asm` - The `asm!` macro provides a means for inline assembly. This is often
2560 useful, but the exact syntax for this feature along with its
2561 semantics are likely to change, so this macro usage must be opted
2564 * `concat_idents` - Allows use of the `concat_idents` macro, which is in many
2565 ways insufficient for concatenating identifiers, and may be
2566 removed entirely for something more wholesome.
2568 * `default_type_params` - Allows use of default type parameters. The future of
2569 this feature is uncertain.
2571 * `intrinsics` - Allows use of the "rust-intrinsics" ABI. Compiler intrinsics
2572 are inherently unstable and no promise about them is made.
2574 * `lang_items` - Allows use of the `#[lang]` attribute. Like `intrinsics`,
2575 lang items are inherently unstable and no promise about them
2578 * `link_args` - This attribute is used to specify custom flags to the linker,
2579 but usage is strongly discouraged. The compiler's usage of the
2580 system linker is not guaranteed to continue in the future, and
2581 if the system linker is not used then specifying custom flags
2582 doesn't have much meaning.
2584 * `link_llvm_intrinsics` – Allows linking to LLVM intrinsics via
2585 `#[link_name="llvm.*"]`.
2587 * `linkage` - Allows use of the `linkage` attribute, which is not portable.
2589 * `log_syntax` - Allows use of the `log_syntax` macro attribute, which is a
2590 nasty hack that will certainly be removed.
2592 * `non_ascii_idents` - The compiler supports the use of non-ascii identifiers,
2593 but the implementation is a little rough around the
2594 edges, so this can be seen as an experimental feature
2595 for now until the specification of identifiers is fully
2598 * `once_fns` - Onceness guarantees a closure is only executed once. Defining a
2599 closure as `once` is unlikely to be supported going forward. So
2600 they are hidden behind this feature until they are to be removed.
2602 * `plugin` - Usage of [compiler plugins][plugin] for custom lints or syntax extensions.
2603 These depend on compiler internals and are subject to change.
2605 * `plugin_registrar` - Indicates that a crate provides [compiler plugins][plugin].
2607 * `quote` - Allows use of the `quote_*!` family of macros, which are
2608 implemented very poorly and will likely change significantly
2609 with a proper implementation.
2611 * `rustc_diagnostic_macros`- A mysterious feature, used in the implementation
2612 of rustc, not meant for mortals.
2614 * `simd` - Allows use of the `#[simd]` attribute, which is overly simple and
2615 not the SIMD interface we want to expose in the long term.
2617 * `struct_inherit` - Allows using struct inheritance, which is barely
2618 implemented and will probably be removed. Don't use this.
2620 * `struct_variant` - Structural enum variants (those with named fields). It is
2621 currently unknown whether this style of enum variant is as
2622 fully supported as the tuple-forms, and it's not certain
2623 that this style of variant should remain in the language.
2624 For now this style of variant is hidden behind a feature
2627 * `thread_local` - The usage of the `#[thread_local]` attribute is experimental
2628 and should be seen as unstable. This attribute is used to
2629 declare a `static` as being unique per-thread leveraging
2630 LLVM's implementation which works in concert with the kernel
2631 loader and dynamic linker. This is not necessarily available
2632 on all platforms, and usage of it is discouraged (rust
2633 focuses more on thread-local data instead of thread-local
2636 * `trace_macros` - Allows use of the `trace_macros` macro, which is a nasty
2637 hack that will certainly be removed.
2639 * `unboxed_closures` - Rust's new closure design, which is currently a work in
2640 progress feature with many known bugs.
2642 * `unsafe_destructor` - Allows use of the `#[unsafe_destructor]` attribute,
2643 which is considered wildly unsafe and will be
2644 obsoleted by language improvements.
2646 * `associated_types` - Allows type aliases in traits. Experimental.
2648 If a feature is promoted to a language feature, then all existing programs will
2649 start to receive compilation warnings about #[feature] directives which enabled
2650 the new feature (because the directive is no longer necessary). However, if a
2651 feature is decided to be removed from the language, errors will be issued (if
2652 there isn't a parser error first). The directive in this case is no longer
2653 necessary, and it's likely that existing code will break if the feature isn't
2656 If an unknown feature is found in a directive, it results in a compiler error.
2657 An unknown feature is one which has never been recognized by the compiler.
2659 # Statements and expressions
2661 Rust is _primarily_ an expression language. This means that most forms of
2662 value-producing or effect-causing evaluation are directed by the uniform syntax
2663 category of _expressions_. Each kind of expression can typically _nest_ within
2664 each other kind of expression, and rules for evaluation of expressions involve
2665 specifying both the value produced by the expression and the order in which its
2666 sub-expressions are themselves evaluated.
2668 In contrast, statements in Rust serve _mostly_ to contain and explicitly
2669 sequence expression evaluation.
2673 A _statement_ is a component of a block, which is in turn a component of an
2674 outer [expression](#expressions) or [function](#functions).
2676 Rust has two kinds of statement: [declaration
2677 statements](#declaration-statements) and [expression
2678 statements](#expression-statements).
2680 ### Declaration statements
2682 A _declaration statement_ is one that introduces one or more *names* into the
2683 enclosing statement block. The declared names may denote new slots or new
2686 #### Item declarations
2688 An _item declaration statement_ has a syntactic form identical to an
2689 [item](#items) declaration within a module. Declaring an item — a
2690 function, enumeration, structure, type, static, trait, implementation or module
2691 — locally within a statement block is simply a way of restricting its
2692 scope to a narrow region containing all of its uses; it is otherwise identical
2693 in meaning to declaring the item outside the statement block.
2695 > **Note**: there is no implicit capture of the function's dynamic environment when
2696 > declaring a function-local item.
2698 #### Slot declarations
2701 let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
2702 init : [ '=' ] expr ;
2705 A _slot declaration_ introduces a new set of slots, given by a pattern. The
2706 pattern may be followed by a type annotation, and/or an initializer expression.
2707 When no type annotation is given, the compiler will infer the type, or signal
2708 an error if insufficient type information is available for definite inference.
2709 Any slots introduced by a slot declaration are visible from the point of
2710 declaration until the end of the enclosing block scope.
2712 ### Expression statements
2714 An _expression statement_ is one that evaluates an [expression](#expressions)
2715 and ignores its result. The type of an expression statement `e;` is always
2716 `()`, regardless of the type of `e`. As a rule, an expression statement's
2717 purpose is to trigger the effects of evaluating its expression.
2721 An expression may have two roles: it always produces a *value*, and it may have
2722 *effects* (otherwise known as "side effects"). An expression *evaluates to* a
2723 value, and has effects during *evaluation*. Many expressions contain
2724 sub-expressions (operands). The meaning of each kind of expression dictates
2727 * Whether or not to evaluate the sub-expressions when evaluating the expression
2728 * The order in which to evaluate the sub-expressions
2729 * How to combine the sub-expressions' values to obtain the value of the expression
2731 In this way, the structure of expressions dictates the structure of execution.
2732 Blocks are just another kind of expression, so blocks, statements, expressions,
2733 and blocks again can recursively nest inside each other to an arbitrary depth.
2735 #### Lvalues, rvalues and temporaries
2737 Expressions are divided into two main categories: _lvalues_ and _rvalues_.
2738 Likewise within each expression, sub-expressions may occur in _lvalue context_
2739 or _rvalue context_. The evaluation of an expression depends both on its own
2740 category and the context it occurs within.
2742 An lvalue is an expression that represents a memory location. These expressions
2743 are [paths](#path-expressions) (which refer to local variables, function and
2744 method arguments, or static variables), dereferences (`*expr`), [indexing
2745 expressions](#index-expressions) (`expr[expr]`), and [field
2746 references](#field-expressions) (`expr.f`). All other expressions are rvalues.
2748 The left operand of an [assignment](#assignment-expressions) or
2749 [compound-assignment](#compound-assignment-expressions) expression is an lvalue
2750 context, as is the single operand of a unary
2751 [borrow](#unary-operator-expressions). All other expression contexts are
2754 When an lvalue is evaluated in an _lvalue context_, it denotes a memory
2755 location; when evaluated in an _rvalue context_, it denotes the value held _in_
2756 that memory location.
2758 When an rvalue is used in an lvalue context, a temporary un-named lvalue is
2759 created and used instead. A temporary's lifetime equals the largest lifetime
2760 of any reference that points to it.
2762 #### Moved and copied types
2764 When a [local variable](#memory-slots) is used as an
2765 [rvalue](#lvalues,-rvalues-and-temporaries) the variable will either be moved
2766 or copied, depending on its type. For types that contain [owning
2767 pointers](#pointer-types) or values that implement the special trait `Drop`,
2768 the variable is moved. All other types are copied.
2770 ### Literal expressions
2772 A _literal expression_ consists of one of the [literal](#literals) forms
2773 described earlier. It directly describes a number, character, string, boolean
2774 value, or the unit value.
2778 "hello"; // string type
2779 '5'; // character type
2783 ### Path expressions
2785 A [path](#paths) used as an expression context denotes either a local variable
2786 or an item. Path expressions are [lvalues](#lvalues,-rvalues-and-temporaries).
2788 ### Tuple expressions
2790 Tuples are written by enclosing zero or more comma-separated expressions in
2791 parentheses. They are used to create [tuple-typed](#tuple-types) values.
2799 ### Unit expressions
2801 The expression `()` denotes the _unit value_, the only value of the type with
2804 ### Structure expressions
2807 struct_expr : expr_path '{' ident ':' expr
2808 [ ',' ident ':' expr ] *
2811 [ ',' expr ] * ')' |
2815 There are several forms of structure expressions. A _structure expression_
2816 consists of the [path](#paths) of a [structure item](#structures), followed by
2817 a brace-enclosed list of one or more comma-separated name-value pairs,
2818 providing the field values of a new instance of the structure. A field name
2819 can be any identifier, and is separated from its value expression by a colon.
2820 The location denoted by a structure field is mutable if and only if the
2821 enclosing structure is mutable.
2823 A _tuple structure expression_ consists of the [path](#paths) of a [structure
2824 item](#structures), followed by a parenthesized list of one or more
2825 comma-separated expressions (in other words, the path of a structure item
2826 followed by a tuple expression). The structure item must be a tuple structure
2829 A _unit-like structure expression_ consists only of the [path](#paths) of a
2830 [structure item](#structures).
2832 The following are examples of structure expressions:
2835 # struct Point { x: f64, y: f64 }
2836 # struct TuplePoint(f64, f64);
2837 # mod game { pub struct User<'a> { pub name: &'a str, pub age: uint, pub score: uint } }
2838 # struct Cookie; fn some_fn<T>(t: T) {}
2839 Point {x: 10.0, y: 20.0};
2840 TuplePoint(10.0, 20.0);
2841 let u = game::User {name: "Joe", age: 35, score: 100_000};
2842 some_fn::<Cookie>(Cookie);
2845 A structure expression forms a new value of the named structure type. Note
2846 that for a given *unit-like* structure type, this will always be the same
2849 A structure expression can terminate with the syntax `..` followed by an
2850 expression to denote a functional update. The expression following `..` (the
2851 base) must have the same structure type as the new structure type being formed.
2852 The entire expression denotes the result of constructing a new structure (with
2853 the same type as the base expression) with the given values for the fields that
2854 were explicitly specified and the values in the base expression for all other
2858 # struct Point3d { x: int, y: int, z: int }
2859 let base = Point3d {x: 1, y: 2, z: 3};
2860 Point3d {y: 0, z: 10, .. base};
2863 ### Block expressions
2866 block_expr : '{' [ view_item ] *
2867 [ stmt ';' | item ] *
2871 A _block expression_ is similar to a module in terms of the declarations that
2872 are possible. Each block conceptually introduces a new namespace scope. View
2873 items can bring new names into scopes and declared items are in scope for only
2876 A block will execute each statement sequentially, and then execute the
2877 expression (if given). If the final expression is omitted, the type and return
2878 value of the block are `()`, but if it is provided, the type and return value
2879 of the block are that of the expression itself.
2881 ### Method-call expressions
2884 method_call_expr : expr '.' ident paren_expr_list ;
2887 A _method call_ consists of an expression followed by a single dot, an
2888 identifier, and a parenthesized expression-list. Method calls are resolved to
2889 methods on specific traits, either statically dispatching to a method if the
2890 exact `self`-type of the left-hand-side is known, or dynamically dispatching if
2891 the left-hand-side expression is an indirect [object type](#object-types).
2893 ### Field expressions
2896 field_expr : expr '.' ident ;
2899 A _field expression_ consists of an expression followed by a single dot and an
2900 identifier, when not immediately followed by a parenthesized expression-list
2901 (the latter is a [method call expression](#method-call-expressions)). A field
2902 expression denotes a field of a [structure](#structure-types).
2907 (Struct {a: 10, b: 20}).a;
2910 A field access is an [lvalue](#lvalues,-rvalues-and-temporaries) referring to
2911 the value of that field. When the type providing the field inherits mutability,
2912 it can be [assigned](#assignment-expressions) to.
2914 Also, if the type of the expression to the left of the dot is a pointer, it is
2915 automatically dereferenced to make the field access possible.
2917 ### Array expressions
2920 array_expr : '[' "mut" ? vec_elems? ']' ;
2922 array_elems : [expr [',' expr]*] | [expr ',' ".." expr] ;
2925 An [array](#array,-and-slice-types) _expression_ is written by enclosing zero
2926 or more comma-separated expressions of uniform type in square brackets.
2928 In the `[expr ',' ".." expr]` form, the expression after the `".."` must be a
2929 constant expression that can be evaluated at compile time, such as a
2930 [literal](#literals) or a [static item](#static-items).
2934 ["a", "b", "c", "d"];
2935 [0i; 128]; // array with 128 zeros
2936 [0u8, 0u8, 0u8, 0u8];
2939 ### Index expressions
2942 idx_expr : expr '[' expr ']' ;
2945 [Array](#array,-and-slice-types)-typed expressions can be indexed by
2946 writing a square-bracket-enclosed expression (the index) after them. When the
2947 array is mutable, the resulting [lvalue](#lvalues,-rvalues-and-temporaries) can
2950 Indices are zero-based, and may be of any integral type. Vector access is
2951 bounds-checked at run-time. When the check fails, it will put the thread in a
2956 (["a", "b"])[10]; // panics
2959 ### Unary operator expressions
2961 Rust defines six symbolic unary operators. They are all written as prefix
2962 operators, before the expression they apply to.
2965 : Negation. May only be applied to numeric types.
2967 : Dereference. When applied to a [pointer](#pointer-types) it denotes the
2968 pointed-to location. For pointers to mutable locations, the resulting
2969 [lvalue](#lvalues,-rvalues-and-temporaries) can be assigned to.
2970 On non-pointer types, it calls the `deref` method of the `std::ops::Deref`
2971 trait, or the `deref_mut` method of the `std::ops::DerefMut` trait (if
2972 implemented by the type and required for an outer expression that will or
2973 could mutate the dereference), and produces the result of dereferencing the
2974 `&` or `&mut` borrowed pointer returned from the overload method.
2977 : Logical negation. On the boolean type, this flips between `true` and
2978 `false`. On integer types, this inverts the individual bits in the
2979 two's complement representation of the value.
2981 : [Boxing](#pointer-types) operators. Allocate a box to hold the value they
2982 are applied to, and store the value in it. `box` creates a box.
2984 : Borrow operator. Returns a reference, pointing to its operand. The operand
2985 of a borrow is statically proven to outlive the resulting pointer. If the
2986 borrow-checker cannot prove this, it is a compilation error.
2988 ### Binary operator expressions
2991 binop_expr : expr binop expr ;
2994 Binary operators expressions are given in terms of [operator
2995 precedence](#operator-precedence).
2997 #### Arithmetic operators
2999 Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
3000 defined in the `std::ops` module of the `std` library. This means that
3001 arithmetic operators can be overridden for user-defined types. The default
3002 meaning of the operators on standard types is given here.
3005 : Addition and array/string concatenation.
3006 Calls the `add` method on the `std::ops::Add` trait.
3009 Calls the `sub` method on the `std::ops::Sub` trait.
3012 Calls the `mul` method on the `std::ops::Mul` trait.
3015 Calls the `div` method on the `std::ops::Div` trait.
3018 Calls the `rem` method on the `std::ops::Rem` trait.
3020 #### Bitwise operators
3022 Like the [arithmetic operators](#arithmetic-operators), bitwise operators are
3023 syntactic sugar for calls to methods of built-in traits. This means that
3024 bitwise operators can be overridden for user-defined types. The default
3025 meaning of the operators on standard types is given here.
3029 Calls the `bitand` method of the `std::ops::BitAnd` trait.
3032 Calls the `bitor` method of the `std::ops::BitOr` trait.
3035 Calls the `bitxor` method of the `std::ops::BitXor` trait.
3037 : Logical left shift.
3038 Calls the `shl` method of the `std::ops::Shl` trait.
3040 : Logical right shift.
3041 Calls the `shr` method of the `std::ops::Shr` trait.
3043 #### Lazy boolean operators
3045 The operators `||` and `&&` may be applied to operands of boolean type. The
3046 `||` operator denotes logical 'or', and the `&&` operator denotes logical
3047 'and'. They differ from `|` and `&` in that the right-hand operand is only
3048 evaluated when the left-hand operand does not already determine the result of
3049 the expression. That is, `||` only evaluates its right-hand operand when the
3050 left-hand operand evaluates to `false`, and `&&` only when it evaluates to
3053 #### Comparison operators
3055 Comparison operators are, like the [arithmetic
3056 operators](#arithmetic-operators), and [bitwise operators](#bitwise-operators),
3057 syntactic sugar for calls to built-in traits. This means that comparison
3058 operators can be overridden for user-defined types. The default meaning of the
3059 operators on standard types is given here.
3063 Calls the `eq` method on the `std::cmp::PartialEq` trait.
3066 Calls the `ne` method on the `std::cmp::PartialEq` trait.
3069 Calls the `lt` method on the `std::cmp::PartialOrd` trait.
3072 Calls the `gt` method on the `std::cmp::PartialOrd` trait.
3074 : Less than or equal.
3075 Calls the `le` method on the `std::cmp::PartialOrd` trait.
3077 : Greater than or equal.
3078 Calls the `ge` method on the `std::cmp::PartialOrd` trait.
3080 #### Type cast expressions
3082 A type cast expression is denoted with the binary operator `as`.
3084 Executing an `as` expression casts the value on the left-hand side to the type
3085 on the right-hand side.
3087 A numeric value can be cast to any numeric type. A raw pointer value can be
3088 cast to or from any integral type or raw pointer type. Any other cast is
3089 unsupported and will fail to compile.
3091 An example of an `as` expression:
3094 # fn sum(v: &[f64]) -> f64 { 0.0 }
3095 # fn len(v: &[f64]) -> int { 0 }
3097 fn avg(v: &[f64]) -> f64 {
3098 let sum: f64 = sum(v);
3099 let sz: f64 = len(v) as f64;
3104 #### Assignment expressions
3106 An _assignment expression_ consists of an
3107 [lvalue](#lvalues,-rvalues-and-temporaries) expression followed by an equals
3108 sign (`=`) and an [rvalue](#lvalues,-rvalues-and-temporaries) expression.
3110 Evaluating an assignment expression [either copies or
3111 moves](#moved-and-copied-types) its right-hand operand to its left-hand
3121 #### Compound assignment expressions
3123 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>` operators may be
3124 composed with the `=` operator. The expression `lval OP= val` is equivalent to
3125 `lval = lval OP val`. For example, `x = x + 1` may be written as `x += 1`.
3127 Any such expression always has the [`unit`](#primitive-types) type.
3129 #### Operator precedence
3131 The precedence of Rust binary operators is ordered as follows, going from
3134 ```{.text .precedence}
3149 Operators at the same precedence level are evaluated left-to-right. [Unary
3150 operators](#unary-operator-expressions) have the same precedence level and are
3151 stronger than any of the binary operators.
3153 ### Grouped expressions
3155 An expression enclosed in parentheses evaluates to the result of the enclosed
3156 expression. Parentheses can be used to explicitly specify evaluation order
3157 within an expression.
3160 paren_expr : '(' expr ')' ;
3163 An example of a parenthesized expression:
3166 let x: int = (2 + 3) * 4;
3170 ### Call expressions
3173 expr_list : [ expr [ ',' expr ]* ] ? ;
3174 paren_expr_list : '(' expr_list ')' ;
3175 call_expr : expr paren_expr_list ;
3178 A _call expression_ invokes a function, providing zero or more input slots and
3179 an optional reference slot to serve as the function's output, bound to the
3180 `lval` on the right hand side of the call. If the function eventually returns,
3181 then the expression completes.
3183 Some examples of call expressions:
3186 # fn add(x: int, y: int) -> int { 0 }
3188 let x: int = add(1, 2);
3189 let pi: Option<f32> = "3.14".parse();
3192 ### Lambda expressions
3195 ident_list : [ ident [ ',' ident ]* ] ? ;
3196 lambda_expr : '|' ident_list '|' expr ;
3199 A _lambda expression_ (sometimes called an "anonymous function expression")
3200 defines a function and denotes it as a value, in a single expression. A lambda
3201 expression is a pipe-symbol-delimited (`|`) list of identifiers followed by an
3204 A lambda expression denotes a function that maps a list of parameters
3205 (`ident_list`) onto the expression that follows the `ident_list`. The
3206 identifiers in the `ident_list` are the parameters to the function. These
3207 parameters' types need not be specified, as the compiler infers them from
3210 Lambda expressions are most useful when passing functions as arguments to other
3211 functions, as an abbreviation for defining and capturing a separate function.
3213 Significantly, lambda expressions _capture their environment_, which regular
3214 [function definitions](#functions) do not. The exact type of capture depends
3215 on the [function type](#function-types) inferred for the lambda expression. In
3216 the simplest and least-expensive form (analogous to a ```|| { }``` expression),
3217 the lambda expression captures its environment by reference, effectively
3218 borrowing pointers to all outer variables mentioned inside the function.
3219 Alternately, the compiler may infer that a lambda expression should copy or
3220 move values (depending on their type.) from the environment into the lambda
3221 expression's captured environment.
3223 In this example, we define a function `ten_times` that takes a higher-order
3224 function argument, and call it with a lambda expression as an argument.
3227 fn ten_times<F>(f: F) where F: Fn(int) {
3235 ten_times(|j| println!("hello, {}", j));
3241 while_expr : "while" no_struct_literal_expr '{' block '}' ;
3244 A `while` loop begins by evaluating the boolean loop conditional expression.
3245 If the loop conditional expression evaluates to `true`, the loop body block
3246 executes and control returns to the loop conditional expression. If the loop
3247 conditional expression evaluates to `false`, the `while` expression completes.
3262 A `loop` expression denotes an infinite loop.
3265 loop_expr : [ lifetime ':' ] "loop" '{' block '}';
3268 A `loop` expression may optionally have a _label_. If a label is present, then
3269 labeled `break` and `continue` expressions nested within this loop may exit out
3270 of this loop or return control to its head. See [Break
3271 expressions](#break-expressions) and [Continue
3272 expressions](#continue-expressions).
3274 ### Break expressions
3277 break_expr : "break" [ lifetime ];
3280 A `break` expression has an optional _label_. If the label is absent, then
3281 executing a `break` expression immediately terminates the innermost loop
3282 enclosing it. It is only permitted in the body of a loop. If the label is
3283 present, then `break foo` terminates the loop with label `foo`, which need not
3284 be the innermost label enclosing the `break` expression, but must enclose it.
3286 ### Continue expressions
3289 continue_expr : "continue" [ lifetime ];
3292 A `continue` expression has an optional _label_. If the label is absent, then
3293 executing a `continue` expression immediately terminates the current iteration
3294 of the innermost loop enclosing it, returning control to the loop *head*. In
3295 the case of a `while` loop, the head is the conditional expression controlling
3296 the loop. In the case of a `for` loop, the head is the call-expression
3297 controlling the loop. If the label is present, then `continue foo` returns
3298 control to the head of the loop with label `foo`, which need not be the
3299 innermost label enclosing the `break` expression, but must enclose it.
3301 A `continue` expression is only permitted in the body of a loop.
3306 for_expr : "for" pat "in" no_struct_literal_expr '{' block '}' ;
3309 A `for` expression is a syntactic construct for looping over elements provided
3310 by an implementation of `std::iter::Iterator`.
3312 An example of a for loop over the contents of an array:
3316 # fn bar(f: Foo) { }
3321 let v: &[Foo] = &[a, b, c];
3328 An example of a for loop over a series of integers:
3331 # fn bar(b:uint) { }
3332 for i in range(0u, 256) {
3340 if_expr : "if" no_struct_literal_expr '{' block '}'
3343 else_tail : "else" [ if_expr | if_let_expr
3347 An `if` expression is a conditional branch in program control. The form of an
3348 `if` expression is a condition expression, followed by a consequent block, any
3349 number of `else if` conditions and blocks, and an optional trailing `else`
3350 block. The condition expressions must have type `bool`. If a condition
3351 expression evaluates to `true`, the consequent block is executed and any
3352 subsequent `else if` or `else` block is skipped. If a condition expression
3353 evaluates to `false`, the consequent block is skipped and any subsequent `else
3354 if` condition is evaluated. If all `if` and `else if` conditions evaluate to
3355 `false` then any `else` block is executed.
3357 ### Match expressions
3360 match_expr : "match" no_struct_literal_expr '{' match_arm * '}' ;
3362 match_arm : attribute * match_pat "=>" [ expr "," | '{' block '}' ] ;
3364 match_pat : pat [ '|' pat ] * [ "if" expr ] ? ;
3367 A `match` expression branches on a *pattern*. The exact form of matching that
3368 occurs depends on the pattern. Patterns consist of some combination of
3369 literals, destructured arrays or enum constructors, structures and tuples,
3370 variable binding specifications, wildcards (`..`), and placeholders (`_`). A
3371 `match` expression has a *head expression*, which is the value to compare to
3372 the patterns. The type of the patterns must equal the type of the head
3375 In a pattern whose head expression has an `enum` type, a placeholder (`_`)
3376 stands for a *single* data field, whereas a wildcard `..` stands for *all* the
3377 fields of a particular variant. For example:
3380 enum List<X> { Nil, Cons(X, Box<List<X>>) }
3382 let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil));
3385 List::Cons(_, box List::Nil) => panic!("singleton list"),
3386 List::Cons(..) => return,
3387 List::Nil => panic!("empty list")
3391 The first pattern matches lists constructed by applying `Cons` to any head
3392 value, and a tail value of `box Nil`. The second pattern matches _any_ list
3393 constructed with `Cons`, ignoring the values of its arguments. The difference
3394 between `_` and `..` is that the pattern `C(_)` is only type-correct if `C` has
3395 exactly one argument, while the pattern `C(..)` is type-correct for any enum
3396 variant `C`, regardless of how many arguments `C` has.
3398 Used inside an array pattern, `..` stands for any number of elements, when the
3399 `advanced_slice_patterns` feature gate is turned on. This wildcard can be used
3400 at most once for a given array, which implies that it cannot be used to
3401 specifically match elements that are at an unknown distance from both ends of a
3402 array, like `[.., 42, ..]`. If followed by a variable name, it will bind the
3403 corresponding slice to the variable. Example:
3406 # #![feature(advanced_slice_patterns)]
3407 fn is_symmetric(list: &[uint]) -> bool {
3410 [x, inside.., y] if x == y => is_symmetric(inside),
3416 let sym = &[0, 1, 4, 2, 4, 1, 0];
3417 let not_sym = &[0, 1, 7, 2, 4, 1, 0];
3418 assert!(is_symmetric(sym));
3419 assert!(!is_symmetric(not_sym));
3423 A `match` behaves differently depending on whether or not the head expression
3424 is an [lvalue or an rvalue](#lvalues,-rvalues-and-temporaries). If the head
3425 expression is an rvalue, it is first evaluated into a temporary location, and
3426 the resulting value is sequentially compared to the patterns in the arms until
3427 a match is found. The first arm with a matching pattern is chosen as the branch
3428 target of the `match`, any variables bound by the pattern are assigned to local
3429 variables in the arm's block, and control enters the block.
3431 When the head expression is an lvalue, the match does not allocate a temporary
3432 location (however, a by-value binding may copy or move from the lvalue). When
3433 possible, it is preferable to match on lvalues, as the lifetime of these
3434 matches inherits the lifetime of the lvalue, rather than being restricted to
3435 the inside of the match.
3437 An example of a `match` expression:
3440 # fn process_pair(a: int, b: int) { }
3441 # fn process_ten() { }
3443 enum List<X> { Nil, Cons(X, Box<List<X>>) }
3445 let x: List<int> = List::Cons(10, box List::Cons(11, box List::Nil));
3448 List::Cons(a, box List::Cons(b, _)) => {
3451 List::Cons(10, _) => {
3463 Patterns that bind variables default to binding to a copy or move of the
3464 matched value (depending on the matched value's type). This can be changed to
3465 bind to a reference by using the `ref` keyword, or to a mutable reference using
3468 Subpatterns can also be bound to variables by the use of the syntax `variable @
3469 subpattern`. For example:
3472 enum List { Nil, Cons(uint, Box<List>) }
3474 fn is_sorted(list: &List) -> bool {
3476 List::Nil | List::Cons(_, box List::Nil) => true,
3477 List::Cons(x, ref r @ box List::Cons(_, _)) => {
3479 box List::Cons(y, _) => (x <= y) && is_sorted(&**r),
3487 let a = List::Cons(6, box List::Cons(7, box List::Cons(42, box List::Nil)));
3488 assert!(is_sorted(&a));
3493 Patterns can also dereference pointers by using the `&`, `&mut` and `box`
3494 symbols, as appropriate. For example, these two matches on `x: &int` are
3499 let y = match *x { 0 => "zero", _ => "some" };
3500 let z = match x { &0 => "zero", _ => "some" };
3505 A pattern that's just an identifier, like `Nil` in the previous example, could
3506 either refer to an enum variant that's in scope, or bind a new variable. The
3507 compiler resolves this ambiguity by forbidding variable bindings that occur in
3508 `match` patterns from shadowing names of variants that are in scope. For
3509 example, wherever `List` is in scope, a `match` pattern would not be able to
3510 bind `Nil` as a new name. The compiler interprets a variable pattern `x` as a
3511 binding _only_ if there is no variant named `x` in scope. A convention you can
3512 use to avoid conflicts is simply to name variants with upper-case letters, and
3513 local variables with lower-case letters.
3515 Multiple match patterns may be joined with the `|` operator. A range of values
3516 may be specified with `...`. For example:
3521 let message = match x {
3522 0 | 1 => "not many",
3528 Range patterns only work on scalar types (like integers and characters; not
3529 like arrays and structs, which have sub-components). A range pattern may not
3530 be a sub-range of another range pattern inside the same `match`.
3532 Finally, match patterns can accept *pattern guards* to further refine the
3533 criteria for matching a case. Pattern guards appear after the pattern and
3534 consist of a bool-typed expression following the `if` keyword. A pattern guard
3535 may refer to the variables bound within the pattern they follow.
3538 # let maybe_digit = Some(0);
3539 # fn process_digit(i: int) { }
3540 # fn process_other(i: int) { }
3542 let message = match maybe_digit {
3543 Some(x) if x < 10 => process_digit(x),
3544 Some(x) => process_other(x),
3549 ### If let expressions
3552 if_let_expr : "if" "let" pat '=' expr '{' block '}'
3554 else_tail : "else" [ if_expr | if_let_expr | '{' block '}' ] ;
3557 An `if let` expression is semantically identical to an `if` expression but in place
3558 of a 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 corresponding
3560 block will execute, otherwise flow proceeds to the first `else` block that follows.
3565 while_let_expr : "while" "let" pat '=' expr '{' block '}' ;
3568 A `while let` loop is semantically identical to a `while` loop but in place of a
3569 condition expression it expects a refutable let statement. If the value of the
3570 expression on the right hand side of the let statement matches the pattern, the
3571 loop body block executes and control returns to the pattern matching statement.
3572 Otherwise, the while expression completes.
3574 ### Return expressions
3577 return_expr : "return" expr ? ;
3580 Return expressions are denoted with the keyword `return`. Evaluating a `return`
3581 expression moves its argument into the output slot of the current function,
3582 destroys the current function activation frame, and transfers control to the
3585 An example of a `return` expression:
3588 fn max(a: int, b: int) -> int {
3600 Every slot, item and value in a Rust program has a type. The _type_ of a
3601 *value* defines the interpretation of the memory holding it.
3603 Built-in types and type-constructors are tightly integrated into the language,
3604 in nontrivial ways that are not possible to emulate in user-defined types.
3605 User-defined types have limited capabilities.
3609 The primitive types are the following:
3611 * The "unit" type `()`, having the single "unit" value `()` (occasionally called
3613 * The boolean type `bool` with values `true` and `false`.
3614 * The machine types.
3615 * The machine-dependent integer and floating-point types.
3617 [^unittype]: The "unit" value `()` is *not* a sentinel "null pointer" value for
3618 reference slots; the "unit" type is the implicit return type from functions
3619 otherwise lacking a return type, and can be used in other contexts (such as
3620 message-sending or type-parametric code) as a zero-size type.]
3624 The machine types are the following:
3626 * The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from
3627 the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1] and
3628 [0, 2^64 - 1] respectively.
3630 * The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with
3631 values drawn from the integer intervals [-(2^(7)), 2^7 - 1],
3632 [-(2^(15)), 2^15 - 1], [-(2^(31)), 2^31 - 1], [-(2^(63)), 2^63 - 1]
3635 * The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and
3636 `f64`, respectively.
3638 #### Machine-dependent integer types
3640 The `uint` type is an unsigned integer type with the same number of bits as the
3641 platform's pointer type. It can represent every memory address in the process.
3643 The `int` type is a signed integer type with the same number of bits as the
3644 platform's pointer type. The theoretical upper bound on object and array size
3645 is the maximum `int` value. This ensures that `int` can be used to calculate
3646 differences between pointers into an object or array and can address every byte
3647 within an object along with one byte past the end.
3651 The types `char` and `str` hold textual data.
3653 A value of type `char` is a [Unicode scalar value](
3654 http://www.unicode.org/glossary/#unicode_scalar_value) (ie. a code point that
3655 is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to
3656 0xD7FF or 0xE000 to 0x10FFFF range. A `[char]` array is effectively an UCS-4 /
3659 A value of type `str` is a Unicode string, represented as an array of 8-bit
3660 unsigned bytes holding a sequence of UTF-8 codepoints. Since `str` is of
3661 unknown size, it is not a _first class_ type, but can only be instantiated
3662 through a pointer type, such as `&str` or `String`.
3666 A tuple *type* is a heterogeneous product of other types, called the *elements*
3667 of the tuple. It has no nominal name and is instead structurally typed.
3669 Tuple types and values are denoted by listing the types or values of their
3670 elements, respectively, in a parenthesized, comma-separated list.
3672 Because tuple elements don't have a name, they can only be accessed by
3675 The members of a tuple are laid out in memory contiguously, in order specified
3678 An example of a tuple type and its use:
3681 type Pair<'a> = (int, &'a str);
3682 let p: Pair<'static> = (10, "hello");
3684 assert!(b != "world");
3687 ### Array, and Slice types
3689 Rust has two different types for a list of items:
3691 * `[T ..N]`, an 'array'
3692 * `&[T]`, a 'slice'.
3694 An array has a fixed size, and can be allocated on either the stack or the
3697 A slice is a 'view' into an array. It doesn't own the data it points
3700 An example of each kind:
3703 let vec: Vec<int> = vec![1, 2, 3];
3704 let arr: [int; 3] = [1, 2, 3];
3705 let s: &[int] = vec.as_slice();
3708 As you can see, the `vec!` macro allows you to create a `Vec<T>` easily. The
3709 `vec!` macro is also part of the standard library, rather than the language.
3711 All in-bounds elements of arrays, and slices are always initialized, and access
3712 to an array or slice is always bounds-checked.
3716 A `struct` *type* is a heterogeneous product of other types, called the
3717 *fields* of the type.[^structtype]
3719 [^structtype]: `struct` types are analogous `struct` types in C,
3720 the *record* types of the ML family,
3721 or the *structure* types of the Lisp family.
3723 New instances of a `struct` can be constructed with a [struct
3724 expression](#structure-expressions).
3726 The memory layout of a `struct` is undefined by default to allow for compiler
3727 optimizations like field reordering, but it can be fixed with the
3728 `#[repr(...)]` attribute. In either case, fields may be given in any order in
3729 a corresponding struct *expression*; the resulting `struct` value will always
3730 have the same memory layout.
3732 The fields of a `struct` may be qualified by [visibility
3733 modifiers](#re-exporting-and-visibility), to allow access to data in a
3734 structure outside a module.
3736 A _tuple struct_ type is just like a structure type, except that the fields are
3739 A _unit-like struct_ type is like a structure type, except that it has no
3740 fields. The one value constructed by the associated [structure
3741 expression](#structure-expressions) is the only value that inhabits such a
3744 ### Enumerated types
3746 An *enumerated type* is a nominal, heterogeneous disjoint union type, denoted
3747 by the name of an [`enum` item](#enumerations). [^enumtype]
3749 [^enumtype]: The `enum` type is analogous to a `data` constructor declaration in
3750 ML, or a *pick ADT* in Limbo.
3752 An [`enum` item](#enumerations) declares both the type and a number of *variant
3753 constructors*, each of which is independently named and takes an optional tuple
3756 New instances of an `enum` can be constructed by calling one of the variant
3757 constructors, in a [call expression](#call-expressions).
3759 Any `enum` value consumes as much memory as the largest variant constructor for
3760 its corresponding `enum` type.
3762 Enum types cannot be denoted *structurally* as types, but must be denoted by
3763 named reference to an [`enum` item](#enumerations).
3767 Nominal types — [enumerations](#enumerated-types) and
3768 [structures](#structure-types) — may be recursive. That is, each `enum`
3769 constructor or `struct` field may refer, directly or indirectly, to the
3770 enclosing `enum` or `struct` type itself. Such recursion has restrictions:
3772 * Recursive types must include a nominal type in the recursion
3773 (not mere [type definitions](#type-definitions),
3774 or other structural types such as [arrays](#array,-and-slice-types) or [tuples](#tuple-types)).
3775 * A recursive `enum` item must have at least one non-recursive constructor
3776 (in order to give the recursion a basis case).
3777 * The size of a recursive type must be finite;
3778 in other words the recursive fields of the type must be [pointer types](#pointer-types).
3779 * Recursive type definitions can cross module boundaries, but not module *visibility* boundaries,
3780 or crate boundaries (in order to simplify the module system and type checker).
3782 An example of a *recursive* type and its use:
3787 Cons(T, Box<List<T>>)
3790 let a: List<int> = List::Cons(7, box List::Cons(13, box List::Nil));
3795 All pointers in Rust are explicit first-class values. They can be copied,
3796 stored into data structures, and returned from functions. There are two
3797 varieties of pointer in Rust:
3800 : These point to memory _owned by some other value_.
3801 A reference type is written `&type` for some lifetime-variable `f`,
3802 or just `&'a type` when you need an explicit lifetime.
3803 Copying a reference is a "shallow" operation:
3804 it involves only copying the pointer itself.
3805 Releasing a reference typically has no effect on the value it points to,
3806 with the exception of temporary values, which are released when the last
3807 reference to them is released.
3809 * Raw pointers (`*`)
3810 : Raw pointers are pointers without safety or liveness guarantees.
3811 Raw pointers are written as `*const T` or `*mut T`,
3812 for example `*const int` means a raw pointer to an integer.
3813 Copying or dropping a raw pointer has no effect on the lifecycle of any
3814 other value. Dereferencing a raw pointer or converting it to any other
3815 pointer type is an [`unsafe` operation](#unsafe-functions).
3816 Raw pointers are generally discouraged in Rust code;
3817 they exist to support interoperability with foreign code,
3818 and writing performance-critical or low-level functions.
3820 The standard library contains additional 'smart pointer' types beyond references
3825 The function type constructor `fn` forms new function types. A function type
3826 consists of a possibly-empty set of function-type modifiers (such as `unsafe`
3827 or `extern`), a sequence of input types and an output type.
3829 An example of a `fn` type:
3832 fn add(x: int, y: int) -> int {
3836 let mut x = add(5,7);
3838 type Binop = fn(int, int) -> int;
3839 let bo: Binop = add;
3845 ```{.ebnf .notation}
3846 closure_type := [ 'unsafe' ] [ '<' lifetime-list '>' ] '|' arg-list '|'
3847 [ ':' bound-list ] [ '->' type ]
3848 lifetime-list := lifetime | lifetime ',' lifetime-list
3849 arg-list := ident ':' type | ident ':' type ',' arg-list
3850 bound-list := bound | bound '+' bound-list
3851 bound := path | lifetime
3854 The type of a closure mapping an input of type `A` to an output of type `B` is
3855 `|A| -> B`. A closure with no arguments or return values has type `||`.
3857 An example of creating and calling a closure:
3860 let captured_var = 10i;
3862 let closure_no_args = |&:| println!("captured_var={}", captured_var);
3864 let closure_args = |&: arg: int| -> int {
3865 println!("captured_var={}, arg={}", captured_var, arg);
3866 arg // Note lack of semicolon after 'arg'
3869 fn call_closure<F: Fn(), G: Fn(int) -> int>(c1: F, c2: G) {
3874 call_closure(closure_no_args, closure_args);
3880 Every trait item (see [traits](#traits)) defines a type with the same name as
3881 the trait. This type is called the _object type_ of the trait. Object types
3882 permit "late binding" of methods, dispatched using _virtual method tables_
3883 ("vtables"). Whereas most calls to trait methods are "early bound" (statically
3884 resolved) to specific implementations at compile time, a call to a method on an
3885 object type is only resolved to a vtable entry at compile time. The actual
3886 implementation for each vtable entry can vary on an object-by-object basis.
3888 Given a pointer-typed expression `E` of type `&T` or `Box<T>`, where `T`
3889 implements trait `R`, casting `E` to the corresponding pointer type `&R` or
3890 `Box<R>` results in a value of the _object type_ `R`. This result is
3891 represented as a pair of pointers: the vtable pointer for the `T`
3892 implementation of `R`, and the pointer value of `E`.
3894 An example of an object type:
3898 fn stringify(&self) -> String;
3901 impl Printable for int {
3902 fn stringify(&self) -> String { self.to_string() }
3905 fn print(a: Box<Printable>) {
3906 println!("{}", a.stringify());
3910 print(box 10i as Box<Printable>);
3914 In this example, the trait `Printable` occurs as an object type in both the
3915 type signature of `print`, and the cast expression in `main`.
3919 Within the body of an item that has type parameter declarations, the names of
3920 its type parameters are types:
3923 fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
3927 let first: B = f(xs[0].clone());
3928 let mut rest: Vec<B> = map(f, xs.slice(1, xs.len()));
3929 rest.insert(0, first);
3934 Here, `first` has type `B`, referring to `map`'s `B` type parameter; and `rest`
3935 has type `Vec<B>`, a vector type with element type `B`.
3939 The special type `self` has a meaning within methods inside an impl item. It
3940 refers to the type of the implicit `self` argument. For example, in:
3944 fn make_string(&self) -> String;
3947 impl Printable for String {
3948 fn make_string(&self) -> String {
3954 `self` refers to the value of type `String` that is the receiver for a call to
3955 the method `make_string`.
3959 Types in Rust are categorized into kinds, based on various properties of the
3960 components of the type. The kinds are:
3963 : Types of this kind can be safely sent between threads.
3964 This kind includes scalars, boxes, procs, and
3965 structural types containing only other owned types.
3966 All `Send` types are `'static`.
3968 : Types of this kind consist of "Plain Old Data"
3969 which can be copied by simply moving bits.
3970 All values of this kind can be implicitly copied.
3971 This kind includes scalars and immutable references,
3972 as well as structural types containing other `Copy` types.
3974 : Types of this kind do not contain any references (except for
3975 references with the `static` lifetime, which are allowed).
3976 This can be a useful guarantee for code
3977 that breaks borrowing assumptions
3978 using [`unsafe` operations](#unsafe-functions).
3980 : This is not strictly a kind,
3981 but its presence interacts with kinds:
3982 the `Drop` trait provides a single method `drop`
3983 that takes no parameters,
3984 and is run when values of the type are dropped.
3985 Such a method is called a "destructor",
3986 and are always executed in "top-down" order:
3987 a value is completely destroyed
3988 before any of the values it owns run their destructors.
3989 Only `Send` types can implement `Drop`.
3992 : Types with destructors, closure environments,
3993 and various other _non-first-class_ types,
3994 are not copyable at all.
3995 Such types can usually only be accessed through pointers,
3996 or in some cases, moved between mutable locations.
3998 Kinds can be supplied as _bounds_ on type parameters, like traits, in which
3999 case the parameter is constrained to types satisfying that kind.
4001 By default, type parameters do not carry any assumed kind-bounds at all. When
4002 instantiating a type parameter, the kind bounds on the parameter are checked to
4003 be the same or narrower than the kind of the type that it is instantiated with.
4005 Sending operations are not part of the Rust language, but are implemented in
4006 the library. Generic functions that send values bound the kind of these values
4009 # Memory and concurrency models
4011 Rust has a memory model centered around concurrently-executing _threads_. Thus
4012 its memory model and its concurrency model are best discussed simultaneously,
4013 as parts of each only make sense when considered from the perspective of the
4016 When reading about the memory model, keep in mind that it is partitioned in
4017 order to support threads; and when reading about threads, keep in mind that their
4018 isolation and communication mechanisms are only possible due to the ownership
4019 and lifetime semantics of the memory model.
4023 A Rust program's memory consists of a static set of *items*, a set of
4024 [threads](#threads) each with its own *stack*, and a *heap*. Immutable portions of
4025 the heap may be shared between threads, mutable portions may not.
4027 Allocations in the stack consist of *slots*, and allocations in the heap
4030 ### Memory allocation and lifetime
4032 The _items_ of a program are those functions, modules and types that have their
4033 value calculated at compile-time and stored uniquely in the memory image of the
4034 rust process. Items are neither dynamically allocated nor freed.
4036 A thread's _stack_ consists of activation frames automatically allocated on entry
4037 to each function as the thread executes. A stack allocation is reclaimed when
4038 control leaves the frame containing it.
4040 The _heap_ is a general term that describes boxes. The lifetime of an
4041 allocation in the heap depends on the lifetime of the box values pointing to
4042 it. Since box values may themselves be passed in and out of frames, or stored
4043 in the heap, heap allocations may outlive the frame they are allocated within.
4045 ### Memory ownership
4047 A thread owns all memory it can *safely* reach through local variables, as well
4048 as boxes and references.
4050 When a thread sends a value that has the `Send` trait to another thread, it loses
4051 ownership of the value sent and can no longer refer to it. This is statically
4052 guaranteed by the combined use of "move semantics", and the compiler-checked
4053 _meaning_ of the `Send` trait: it is only instantiated for (transitively)
4054 sendable kinds of data constructor and pointers, never including references.
4056 When a stack frame is exited, its local allocations are all released, and its
4057 references to boxes are dropped.
4059 When a thread finishes, its stack is necessarily empty and it therefore has no
4060 references to any boxes; the remainder of its heap is immediately freed.
4064 A thread's stack contains slots.
4066 A _slot_ is a component of a stack frame, either a function parameter, a
4067 [temporary](#lvalues,-rvalues-and-temporaries), or a local variable.
4069 A _local variable_ (or *stack-local* allocation) holds a value directly,
4070 allocated within the stack's memory. The value is a part of the stack frame.
4072 Local variables are immutable unless declared otherwise like: `let mut x = ...`.
4074 Function parameters are immutable unless declared with `mut`. The `mut` keyword
4075 applies only to the following parameter (so `|mut x, y|` and `fn f(mut x:
4076 Box<int>, y: Box<int>)` declare one mutable variable `x` and one immutable
4079 Methods that take either `self` or `Box<Self>` can optionally place them in a
4080 mutable slot by prefixing them with `mut` (similar to regular arguments):
4084 fn change(mut self) -> Self;
4085 fn modify(mut self: Box<Self>) -> Box<Self>;
4089 Local variables are not initialized when allocated; the entire frame worth of
4090 local variables are allocated at once, on frame-entry, in an uninitialized
4091 state. Subsequent statements within a function may or may not initialize the
4092 local variables. Local variables can be used only after they have been
4093 initialized; this is enforced by the compiler.
4097 A _box_ is a reference to a heap allocation holding another value, which is
4098 constructed by the prefix operator `box`. When the standard library is in use,
4099 the type of a box is `std::owned::Box<T>`.
4101 An example of a box type and value:
4104 let x: Box<int> = box 10;
4107 Box values exist in 1:1 correspondence with their heap allocation, copying a
4108 box value makes a shallow copy of the pointer. Rust will consider a shallow
4109 copy of a box to move ownership of the value. After a value has been moved,
4110 the source location cannot be used unless it is reinitialized.
4113 let x: Box<int> = box 10;
4115 // attempting to use `x` will result in an error here
4120 Rust's primary concurrency mechanism is called a **thread**.
4122 ### Communication between threads
4124 Rust threads are isolated and generally unable to interfere with one another's
4125 memory directly, except through [`unsafe` code](#unsafe-functions). All
4126 contact between threads is mediated by safe forms of ownership transfer, and data
4127 races on memory are prohibited by the type system.
4129 When you wish to send data between threads, the values are restricted to the
4130 [`Send` type-kind](#type-kinds). Restricting communication interfaces to this
4131 kind ensures that no references move between threads. Thus access to an entire
4132 data structure can be mediated through its owning "root" value; no further
4133 locking or copying is required to avoid data races within the substructure of
4138 The _lifecycle_ of a threads consists of a finite set of states and events that
4139 cause transitions between the states. The lifecycle states of a thread are:
4146 A thread begins its lifecycle — once it has been spawned — in the
4147 *running* state. In this state it executes the statements of its entry
4148 function, and any functions called by the entry function.
4150 A thread may transition from the *running* state to the *blocked* state any time
4151 it makes a blocking communication call. When the call can be completed —
4152 when a message arrives at a sender, or a buffer opens to receive a message
4153 — then the blocked thread will unblock and transition back to *running*.
4155 A thread may transition to the *panicked* state at any time, due being killed by
4156 some external event or internally, from the evaluation of a `panic!()` macro.
4157 Once *panicking*, a thread unwinds its stack and transitions to the *dead* state.
4158 Unwinding the stack of a thread is done by the thread itself, on its own control
4159 stack. If a value with a destructor is freed during unwinding, the code for the
4160 destructor is run, also on the thread's control stack. Running the destructor
4161 code causes a temporary transition to a *running* state, and allows the
4162 destructor code to cause any subsequent state transitions. The original thread
4163 of unwinding and panicking thereby may suspend temporarily, and may involve
4164 (recursive) unwinding of the stack of a failed destructor. Nonetheless, the
4165 outermost unwinding activity will continue until the stack is unwound and the
4166 thread transitions to the *dead* state. There is no way to "recover" from thread
4167 panics. Once a thread has temporarily suspended its unwinding in the *panicking*
4168 state, a panic occurring from within this destructor results in *hard* panic.
4169 A hard panic currently results in the process aborting.
4171 A thread in the *dead* state cannot transition to other states; it exists only to
4172 have its termination status inspected by other threads, and/or to await
4173 reclamation when the last reference to it drops.
4175 # Runtime services, linkage and debugging
4177 The Rust _runtime_ is a relatively compact collection of Rust code that
4178 provides fundamental services and datatypes to all Rust threads at run-time. It
4179 is smaller and simpler than many modern language runtimes. It is tightly
4180 integrated into the language's execution model of memory, threads, communication
4183 ### Memory allocation
4185 The runtime memory-management system is based on a _service-provider
4186 interface_, through which the runtime requests blocks of memory from its
4187 environment and releases them back to its environment when they are no longer
4188 needed. The default implementation of the service-provider interface consists
4189 of the C runtime functions `malloc` and `free`.
4191 The runtime memory-management system, in turn, supplies Rust threads with
4192 facilities for allocating releasing stacks, as well as allocating and freeing
4197 The runtime provides C and Rust code to assist with various built-in types,
4198 such as arrays, strings, and the low level communication system (ports,
4201 Support for other built-in types such as simple types, tuples and enums is
4202 open-coded by the Rust compiler.
4204 ### Thread scheduling and communication
4206 The runtime provides code to manage inter-thread communication. This includes
4207 the system of thread-lifecycle state transitions depending on the contents of
4208 queues, as well as code to copy values between queues and their recipients and
4209 to serialize values for transmission over operating-system inter-process
4210 communication facilities.
4214 The Rust compiler supports various methods to link crates together both
4215 statically and dynamically. This section will explore the various methods to
4216 link Rust crates together, and more information about native libraries can be
4217 found in the [ffi guide][ffi].
4219 In one session of compilation, the compiler can generate multiple artifacts
4220 through the usage of either command line flags or the `crate_type` attribute.
4221 If one or more command line flag is specified, all `crate_type` attributes will
4222 be ignored in favor of only building the artifacts specified by command line.
4224 * `--crate-type=bin`, `#[crate_type = "bin"]` - A runnable executable will be
4225 produced. This requires that there is a `main` function in the crate which
4226 will be run when the program begins executing. This will link in all Rust and
4227 native dependencies, producing a distributable binary.
4229 * `--crate-type=lib`, `#[crate_type = "lib"]` - A Rust library will be produced.
4230 This is an ambiguous concept as to what exactly is produced because a library
4231 can manifest itself in several forms. The purpose of this generic `lib` option
4232 is to generate the "compiler recommended" style of library. The output library
4233 will always be usable by rustc, but the actual type of library may change from
4234 time-to-time. The remaining output types are all different flavors of
4235 libraries, and the `lib` type can be seen as an alias for one of them (but the
4236 actual one is compiler-defined).
4238 * `--crate-type=dylib`, `#[crate_type = "dylib"]` - A dynamic Rust library will
4239 be produced. This is different from the `lib` output type in that this forces
4240 dynamic library generation. The resulting dynamic library can be used as a
4241 dependency for other libraries and/or executables. This output type will
4242 create `*.so` files on linux, `*.dylib` files on osx, and `*.dll` files on
4245 * `--crate-type=staticlib`, `#[crate_type = "staticlib"]` - A static system
4246 library will be produced. This is different from other library outputs in that
4247 the Rust compiler will never attempt to link to `staticlib` outputs. The
4248 purpose of this output type is to create a static library containing all of
4249 the local crate's code along with all upstream dependencies. The static
4250 library is actually a `*.a` archive on linux and osx and a `*.lib` file on
4251 windows. This format is recommended for use in situations such as linking
4252 Rust code into an existing non-Rust application because it will not have
4253 dynamic dependencies on other Rust code.
4255 * `--crate-type=rlib`, `#[crate_type = "rlib"]` - A "Rust library" file will be
4256 produced. This is used as an intermediate artifact and can be thought of as a
4257 "static Rust library". These `rlib` files, unlike `staticlib` files, are
4258 interpreted by the Rust compiler in future linkage. This essentially means
4259 that `rustc` will look for metadata in `rlib` files like it looks for metadata
4260 in dynamic libraries. This form of output is used to produce statically linked
4261 executables as well as `staticlib` outputs.
4263 Note that these outputs are stackable in the sense that if multiple are
4264 specified, then the compiler will produce each form of output at once without
4265 having to recompile. However, this only applies for outputs specified by the
4266 same method. If only `crate_type` attributes are specified, then they will all
4267 be built, but if one or more `--crate-type` command line flag is specified,
4268 then only those outputs will be built.
4270 With all these different kinds of outputs, if crate A depends on crate B, then
4271 the compiler could find B in various different forms throughout the system. The
4272 only forms looked for by the compiler, however, are the `rlib` format and the
4273 dynamic library format. With these two options for a dependent library, the
4274 compiler must at some point make a choice between these two formats. With this
4275 in mind, the compiler follows these rules when determining what format of
4276 dependencies will be used:
4278 1. If a static library is being produced, all upstream dependencies are
4279 required to be available in `rlib` formats. This requirement stems from the
4280 reason that a dynamic library cannot be converted into a static format.
4282 Note that it is impossible to link in native dynamic dependencies to a static
4283 library, and in this case warnings will be printed about all unlinked native
4284 dynamic dependencies.
4286 2. If an `rlib` file is being produced, then there are no restrictions on what
4287 format the upstream dependencies are available in. It is simply required that
4288 all upstream dependencies be available for reading metadata from.
4290 The reason for this is that `rlib` files do not contain any of their upstream
4291 dependencies. It wouldn't be very efficient for all `rlib` files to contain a
4292 copy of `libstd.rlib`!
4294 3. If an executable is being produced and the `-C prefer-dynamic` flag is not
4295 specified, then dependencies are first attempted to be found in the `rlib`
4296 format. If some dependencies are not available in an rlib format, then
4297 dynamic linking is attempted (see below).
4299 4. If a dynamic library or an executable that is being dynamically linked is
4300 being produced, then the compiler will attempt to reconcile the available
4301 dependencies in either the rlib or dylib format to create a final product.
4303 A major goal of the compiler is to ensure that a library never appears more
4304 than once in any artifact. For example, if dynamic libraries B and C were
4305 each statically linked to library A, then a crate could not link to B and C
4306 together because there would be two copies of A. The compiler allows mixing
4307 the rlib and dylib formats, but this restriction must be satisfied.
4309 The compiler currently implements no method of hinting what format a library
4310 should be linked with. When dynamically linking, the compiler will attempt to
4311 maximize dynamic dependencies while still allowing some dependencies to be
4312 linked in via an rlib.
4314 For most situations, having all libraries available as a dylib is recommended
4315 if dynamically linking. For other situations, the compiler will emit a
4316 warning if it is unable to determine which formats to link each library with.
4318 In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for
4319 all compilation needs, and the other options are just available if more
4320 fine-grained control is desired over the output format of a Rust crate.
4322 # Appendix: Rationales and design tradeoffs
4326 # Appendix: Influences
4328 Rust is not a particularly original language, with design elements coming from
4329 a wide range of sources. Some of these are listed below (including elements
4330 that have since been removed):
4332 * SML, OCaml: algebraic datatypes, pattern matching, type inference,
4333 semicolon statement separation
4334 * C++: references, RAII, smart pointers, move semantics, monomorphisation,
4336 * ML Kit, Cyclone: region based memory management
4337 * Haskell (GHC): typeclasses, type families
4338 * Newsqueak, Alef, Limbo: channels, concurrency
4339 * Erlang: message passing, task failure, ~~linked task failure~~,
4340 ~~lightweight concurrency~~
4341 * Swift: optional bindings
4342 * Scheme: hygienic macros
4344 * Ruby: ~~block syntax~~
4345 * NIL, Hermes: ~~typestate~~
4346 * [Unicode Annex #31](http://www.unicode.org/reports/tr31/): identifier and
4349 [ffi]: guide-ffi.html
4350 [plugin]: guide-plugin.html