1 % Rust Reference Manual
5 This document is the reference manual 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 a tutorial introduction to the
17 language. Background familiarity with the language is assumed. A separate
18 [tutorial] document is available to help acquire such background familiarity.
20 This document also does not serve as a reference to the [standard] or [extra]
21 libraries included in the language distribution. Those libraries are
22 documented separately by extracting documentation attributes from their
25 [tutorial]: tutorial.html
26 [standard]: std/index.html
27 [extra]: extra/index.html
31 Rust is a work in progress. The language continues to evolve as the design
32 shifts and is fleshed out in working code. Certain parts work, certain parts
33 do not, certain parts will be removed or changed.
35 This manual is a snapshot written in the present tense. All features described
36 exist in working code unless otherwise noted, but some are quite primitive or
37 remain to be further modified by planned work. Some may be temporary. It is a
38 *draft*, and we ask that you not take anything you read here as final.
40 If you have suggestions to make, please try to focus them on *reductions* to
41 the language: possible features that can be combined or omitted. We aim to
42 keep the size and complexity of the language under control.
44 > **Note:** The grammar for Rust given in this document is rough and
45 > very incomplete; only a modest number of sections have accompanying grammar
46 > rules. Formalizing the grammar accepted by the Rust parser is ongoing work,
47 > but future versions of this document will contain a complete
48 > grammar. Moreover, we hope that this grammar will be extracted and verified
49 > as LL(1) by an automated grammar-analysis tool, and further tested against the
50 > Rust sources. Preliminary versions of this automation exist, but are not yet
55 Rust's grammar is defined over Unicode codepoints, each conventionally
56 denoted `U+XXXX`, for 4 or more hexadecimal digits `X`. _Most_ of Rust's
57 grammar is confined to the ASCII range of Unicode, and is described in this
58 document by a dialect of Extended Backus-Naur Form (EBNF), specifically a
59 dialect of EBNF supported by common automated LL(k) parsing tools such as
60 `llgen`, rather than the dialect given in ISO 14977. The dialect can be
61 defined self-referentially as follows:
63 ~~~~~~~~ {.ebnf .notation}
66 rule : nonterminal ':' productionrule ';' ;
67 productionrule : production [ '|' production ] * ;
69 term : element repeats ;
70 element : LITERAL | IDENTIFIER | '[' productionrule ']' ;
71 repeats : [ '*' | '+' ] NUMBER ? | NUMBER ? | '?' ;
77 - Whitespace in the grammar is ignored.
78 - Square brackets are used to group rules.
79 - `LITERAL` is a single printable ASCII character, or an escaped hexadecimal
80 ASCII code of the form `\xQQ`, in single quotes, denoting the corresponding
81 Unicode codepoint `U+00QQ`.
82 - `IDENTIFIER` is a nonempty string of ASCII letters and underscores.
83 - The `repeat` forms apply to the adjacent `element`, and are as follows:
84 - `?` means zero or one repetition
85 - `*` means zero or more repetitions
86 - `+` means one or more repetitions
87 - NUMBER trailing a repeat symbol gives a maximum repetition count
88 - NUMBER on its own gives an exact repetition count
90 This EBNF dialect should hopefully be familiar to many readers.
92 ## Unicode productions
94 A few productions in Rust's grammar permit Unicode codepoints outside the ASCII range.
95 We define these productions in terms of character properties specified in the Unicode standard,
96 rather than in terms of ASCII-range codepoints.
97 The section [Special Unicode Productions](#special-unicode-productions) lists these productions.
99 ## String table productions
101 Some rules in the grammar -- notably [unary
102 operators](#unary-operator-expressions), [binary
103 operators](#binary-operator-expressions), and [keywords](#keywords) --
104 are given in a simplified form: as a listing of a table of unquoted,
105 printable whitespace-separated strings. These cases form a subset of
106 the rules regarding the [token](#tokens) rule, and are assumed to be
107 the result of a lexical-analysis phase feeding the parser, driven by a
108 DFA, operating over the disjunction of all such string table entries.
110 When such a string enclosed in double-quotes (`"`) occurs inside the
111 grammar, it is an implicit reference to a single member of such a string table
112 production. See [tokens](#tokens) for more information.
119 Rust input is interpreted as a sequence of Unicode codepoints encoded in UTF-8,
120 normalized to Unicode normalization form NFKC.
121 Most Rust grammar rules are defined in terms of printable ASCII-range codepoints,
122 but a small number are defined in terms of Unicode properties or explicit codepoint lists.
123 ^[Substitute definitions for the special Unicode productions are provided to the grammar verifier, restricted to ASCII range, when verifying the grammar in this document.]
125 ## Special Unicode Productions
127 The following productions in the Rust grammar are defined in terms of Unicode properties:
128 `ident`, `non_null`, `non_star`, `non_eol`, `non_slash_or_star`, `non_single_quote` and `non_double_quote`.
132 The `ident` production is any nonempty Unicode string of the following form:
134 - The first character has property `XID_start`
135 - The remaining characters have property `XID_continue`
137 that does _not_ occur in the set of [keywords](#keywords).
139 Note: `XID_start` and `XID_continue` as character properties cover the
140 character ranges used to form the more familiar C and Java language-family
143 ### Delimiter-restricted productions
145 Some productions are defined by exclusion of particular Unicode characters:
147 - `non_null` is any single Unicode character aside from `U+0000` (null)
148 - `non_eol` is `non_null` restricted to exclude `U+000A` (`'\n'`)
149 - `non_star` is `non_null` restricted to exclude `U+002A` (`*`)
150 - `non_slash_or_star` is `non_null` restricted to exclude `U+002F` (`/`) and `U+002A` (`*`)
151 - `non_single_quote` is `non_null` restricted to exclude `U+0027` (`'`)
152 - `non_double_quote` is `non_null` restricted to exclude `U+0022` (`"`)
156 ~~~~~~~~ {.ebnf .gram}
157 comment : block_comment | line_comment ;
158 block_comment : "/*" block_comment_body * '*' + '/' ;
159 block_comment_body : non_star * | '*' + non_slash_or_star ;
160 line_comment : "//" non_eol * ;
163 Comments in Rust code follow the general C++ style of line and block-comment forms,
164 with no nesting of block-comment delimiters.
166 Line comments beginning with _three_ slashes (`///`),
167 and block comments beginning with a repeated asterisk in the block-open sequence (`/**`),
168 are interpreted as a special syntax for `doc` [attributes](#attributes).
169 That is, they are equivalent to writing `#[doc "..."]` around the comment's text.
171 Non-doc comments are interpreted as a form of whitespace.
175 ~~~~~~~~ {.ebnf .gram}
176 whitespace_char : '\x20' | '\x09' | '\x0a' | '\x0d' ;
177 whitespace : [ whitespace_char | comment ] + ;
180 The `whitespace_char` production is any nonempty Unicode string consisting of any
181 of the following Unicode characters: `U+0020` (space, `' '`), `U+0009` (tab,
182 `'\t'`), `U+000A` (LF, `'\n'`), `U+000D` (CR, `'\r'`).
184 Rust is a "free-form" language, meaning that all forms of whitespace serve
185 only to separate _tokens_ in the grammar, and have no semantic significance.
187 A Rust program has identical meaning if each whitespace element is replaced
188 with any other legal whitespace element, such as a single space character.
192 ~~~~~~~~ {.ebnf .gram}
193 simple_token : keyword | unop | binop ;
194 token : simple_token | ident | literal | symbol | whitespace token ;
197 Tokens are primitive productions in the grammar defined by regular
198 (non-recursive) languages. "Simple" tokens are given in [string table
199 production](#string-table-productions) form, and occur in the rest of the
200 grammar as double-quoted strings. Other tokens have exact rules given.
204 The keywords are the following strings:
217 self static struct super
223 Each of these keywords has special meaning in its grammar,
224 and all of them are excluded from the `ident` rule.
228 A literal is an expression consisting of a single token, rather than a
229 sequence of tokens, that immediately and directly denotes the value it
230 evaluates to, rather than referring to it by name or some other evaluation
231 rule. A literal is a form of constant expression, so is evaluated (primarily)
234 ~~~~~~~~ {.ebnf .gram}
235 literal : string_lit | char_lit | num_lit ;
238 #### Character and string literals
240 ~~~~~~~~ {.ebnf .gram}
241 char_lit : '\x27' char_body '\x27' ;
242 string_lit : '"' string_body * '"' ;
244 char_body : non_single_quote
245 | '\x5c' [ '\x27' | common_escape ] ;
247 string_body : non_double_quote
248 | '\x5c' [ '\x22' | common_escape ] ;
250 common_escape : '\x5c'
256 hex_digit : 'a' | 'b' | 'c' | 'd' | 'e' | 'f'
257 | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
259 dec_digit : '0' | nonzero_dec ;
260 nonzero_dec: '1' | '2' | '3' | '4'
261 | '5' | '6' | '7' | '8' | '9' ;
264 A _character literal_ is a single Unicode character enclosed within two
265 `U+0027` (single-quote) characters, with the exception of `U+0027` itself,
266 which must be _escaped_ by a preceding U+005C character (`\`).
268 A _string literal_ is a sequence of any Unicode characters enclosed within
269 two `U+0022` (double-quote) characters, with the exception of `U+0022`
270 itself, which must be _escaped_ by a preceding `U+005C` character (`\`).
272 Some additional _escapes_ are available in either character or string
273 literals. An escape starts with a `U+005C` (`\`) and continues with one of
276 * An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is
277 followed by exactly two _hex digits_. It denotes the Unicode codepoint
278 equal to the provided hex value.
279 * A _16-bit codepoint escape_ starts with `U+0075` (`u`) and is followed
280 by exactly four _hex digits_. It denotes the Unicode codepoint equal to
281 the provided hex value.
282 * A _32-bit codepoint escape_ starts with `U+0055` (`U`) and is followed
283 by exactly eight _hex digits_. It denotes the Unicode codepoint equal to
284 the provided hex value.
285 * A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
286 (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF),
287 `U+000D` (CR) or `U+0009` (HT) respectively.
288 * The _backslash escape_ is the character U+005C (`\`) which must be
289 escaped in order to denote *itself*.
293 ~~~~~~~~ {.ebnf .gram}
295 num_lit : nonzero_dec [ dec_digit | '_' ] * num_suffix ?
296 | '0' [ [ dec_digit | '_' ] + num_suffix ?
297 | 'b' [ '1' | '0' | '_' ] + int_suffix ?
298 | 'x' [ hex_digit | '_' ] + int_suffix ? ] ;
300 num_suffix : int_suffix | float_suffix ;
302 int_suffix : 'u' int_suffix_size ?
303 | 'i' int_suffix_size ? ;
304 int_suffix_size : [ '8' | '1' '6' | '3' '2' | '6' '4' ] ;
306 float_suffix : [ exponent | '.' dec_lit exponent ? ] ? float_suffix_ty ? ;
307 float_suffix_ty : 'f' [ '3' '2' | '6' '4' ] ;
308 exponent : ['E' | 'e'] ['-' | '+' ] ? dec_lit ;
309 dec_lit : [ dec_digit | '_' ] + ;
312 A _number literal_ is either an _integer literal_ or a _floating-point
313 literal_. The grammar for recognizing the two kinds of literals is mixed,
314 as they are differentiated by suffixes.
316 ##### Integer literals
318 An _integer literal_ has one of three forms:
320 * A _decimal literal_ starts with a *decimal digit* and continues with any
321 mixture of *decimal digits* and _underscores_.
322 * A _hex literal_ starts with the character sequence `U+0030` `U+0078`
323 (`0x`) and continues as any mixture hex digits and underscores.
324 * A _binary literal_ starts with the character sequence `U+0030` `U+0062`
325 (`0b`) and continues as any mixture binary digits and underscores.
327 An integer literal may be followed (immediately, without any spaces) by an
328 _integer suffix_, which changes the type of the literal. There are two kinds
329 of integer literal suffix:
331 * The `i` and `u` suffixes give the literal type `int` or `uint`,
333 * Each of the signed and unsigned machine types `u8`, `i8`,
334 `u16`, `i16`, `u32`, `i32`, `u64` and `i64`
335 give the literal the corresponding machine type.
337 The type of an _unsuffixed_ integer literal is determined by type inference.
338 If a integer type can be _uniquely_ determined from the surrounding program
339 context, the unsuffixed integer literal has that type. If the program context
340 underconstrains the type, the unsuffixed integer literal's type is `int`; if
341 the program context overconstrains the type, it is considered a static type
344 Examples of integer literals of various forms:
347 123; 0xff00; // type determined by program context
348 // defaults to int in absence of type
354 0b1111_1111_1001_0000_i32; // type i32
357 ##### Floating-point literals
359 A _floating-point literal_ has one of two forms:
361 * Two _decimal literals_ separated by a period
362 character `U+002E` (`.`), with an optional _exponent_ trailing after the
363 second decimal literal.
364 * A single _decimal literal_ followed by an _exponent_.
366 By default, a floating-point literal is of type `float`. A
367 floating-point literal may be followed (immediately, without any
368 spaces) by a _floating-point suffix_, which changes the type of the
369 literal. There are three floating-point suffixes: `f` (for the base
370 `float` type), `f32`, and `f64` (the 32-bit and 64-bit floating point
373 Examples of floating-point literals of various forms:
380 12E+99_f64; // type f64
383 ##### Unit and boolean literals
385 The _unit value_, the only value of the type that has the same name, is written as `()`.
386 The two values of the boolean type are written `true` and `false`.
390 ~~~~~~~~ {.ebnf .gram}
392 | '#' | '[' | ']' | '(' | ')' | '{' | '}'
396 Symbols are a general class of printable [token](#tokens) that play structural
397 roles in a variety of grammar productions. They are catalogued here for
398 completeness as the set of remaining miscellaneous printable tokens that do not
399 otherwise appear as [unary operators](#unary-operator-expressions), [binary
400 operators](#binary-operator-expressions), or [keywords](#keywords).
405 ~~~~~~~~ {.ebnf .gram}
407 expr_path : ident [ "::" expr_path_tail ] + ;
408 expr_path_tail : '<' type_expr [ ',' type_expr ] + '>'
411 type_path : ident [ type_path_tail ] + ;
412 type_path_tail : '<' type_expr [ ',' type_expr ] + '>'
417 A _path_ is a sequence of one or more path components _logically_ separated by
418 a namespace qualifier (`::`). If a path consists of only one component, it may
419 refer to either an [item](#items) or a [slot](#memory-slots) in a local
420 control scope. If a path has multiple components, it refers to an item.
422 Every item has a _canonical path_ within its crate, but the path naming an
423 item is only meaningful within a given crate. There is no global namespace
424 across crates; an item's canonical path merely identifies it within the crate.
426 Two examples of simple paths consisting of only identifier components:
433 Path components are usually [identifiers](#identifiers), but the trailing
434 component of a path may be an angle-bracket-enclosed list of type
435 arguments. In [expression](#expressions) context, the type argument list is
436 given after a final (`::`) namespace qualifier in order to disambiguate it
437 from a relational expression involving the less-than symbol (`<`). In type
438 expression context, the final namespace qualifier is omitted.
440 Two examples of paths with type arguments:
443 # use std::hashmap::HashMap;
445 # fn id<T>(t: T) -> T { t }
446 type t = HashMap<int,~str>; // Type arguments used in a type expression
447 let x = id::<int>(10); // Type arguments used in a call expression
453 A number of minor features of Rust are not central enough to have their own
454 syntax, and yet are not implementable as functions. Instead, they are given
455 names, and invoked through a consistent syntax: `name!(...)`. Examples
458 * `fmt!` : format data into a string
459 * `env!` : look up an environment variable's value at compile time
460 * `stringify!` : pretty-print the Rust expression given as an argument
461 * `proto!` : define a protocol for inter-task communication
462 * `include!` : include the Rust expression in the given file
463 * `include_str!` : include the contents of the given file as a string
464 * `include_bin!` : include the contents of the given file as a binary blob
465 * `error!`, `warn!`, `info!`, `debug!` : provide diagnostic information.
467 All of the above extensions, with the exception of `proto!`, are expressions
468 with values. `proto!` is an item, defining a new name.
472 ~~~~~~~~ {.ebnf .gram}
474 expr_macro_rules : "macro_rules" '!' ident '(' macro_rule * ')'
475 macro_rule : '(' matcher * ')' "=>" '(' transcriber * ')' ';'
476 matcher : '(' matcher * ')' | '[' matcher * ']'
477 | '{' matcher * '}' | '$' ident ':' ident
478 | '$' '(' matcher * ')' sep_token? [ '*' | '+' ]
480 transcriber : '(' transcriber * ')' | '[' transcriber * ']'
481 | '{' transcriber * '}' | '$' ident
482 | '$' '(' transcriber * ')' sep_token? [ '*' | '+' ]
487 User-defined syntax extensions are called "macros",
488 and the `macro_rules` syntax extension defines them.
489 Currently, user-defined macros can expand to expressions, statements, or items.
491 (A `sep_token` is any token other than `*` and `+`.
492 A `non_special_token` is any token other than a delimiter or `$`.)
494 The macro expander looks up macro invocations by name,
495 and tries each macro rule in turn.
496 It transcribes the first successful match.
497 Matching and transcription are closely related to each other,
498 and we will describe them together.
502 The macro expander matches and transcribes every token that does not begin with a `$` literally, including delimiters.
503 For parsing reasons, delimiters must be balanced, but they are otherwise not special.
505 In the matcher, `$` _name_ `:` _designator_ matches the nonterminal in the
506 Rust syntax named by _designator_. Valid designators are `item`, `block`,
507 `stmt`, `pat`, `expr`, `ty` (type), `ident`, `path`, `matchers` (lhs of the `=>` in macro rules),
508 `tt` (rhs of the `=>` in macro rules). In the transcriber, the designator is already known, and so only
509 the name of a matched nonterminal comes after the dollar sign.
511 In both the matcher and transcriber, the Kleene star-like operator indicates repetition.
512 The Kleene star operator consists of `$` and parens, optionally followed by a separator token, followed by `*` or `+`.
513 `*` means zero or more repetitions, `+` means at least one repetition.
514 The parens are not matched or transcribed.
515 On the matcher side, a name is bound to _all_ of the names it
516 matches, in a structure that mimics the structure of the repetition
517 encountered on a successful match. The job of the transcriber is to sort that
520 The rules for transcription of these repetitions are called "Macro By Example".
521 Essentially, one "layer" of repetition is discharged at a time, and all of
522 them must be discharged by the time a name is transcribed. Therefore,
523 `( $( $i:ident ),* ) => ( $i )` is an invalid macro, but
524 `( $( $i:ident ),* ) => ( $( $i:ident ),* )` is acceptable (if trivial).
526 When Macro By Example encounters a repetition, it examines all of the `$`
527 _name_ s that occur in its body. At the "current layer", they all must repeat
528 the same number of times, so
529 ` ( $( $i:ident ),* ; $( $j:ident ),* ) => ( $( ($i,$j) ),* )` is valid if
530 given the argument `(a,b,c ; d,e,f)`, but not `(a,b,c ; d,e)`. The repetition
531 walks through the choices at that layer in lockstep, so the former input
532 transcribes to `( (a,d), (b,e), (c,f) )`.
534 Nested repetitions are allowed.
536 ### Parsing limitations
538 The parser used by the macro system is reasonably powerful, but the parsing of
539 Rust syntax is restricted in two ways:
541 1. The parser will always parse as much as possible. If it attempts to match
542 `$i:expr [ , ]` against `8 [ , ]`, it will attempt to parse `i` as an array
543 index operation and fail. Adding a separator can solve this problem.
544 2. The parser must have eliminated all ambiguity by the time it reaches a `$` _name_ `:` _designator_.
545 This requirement most often affects name-designator pairs when they occur at the beginning of, or immediately after, a `$(...)*`; requiring a distinctive token in front can solve the problem.
548 ## Syntax extensions useful for the macro author
550 * `log_syntax!` : print out the arguments at compile time
551 * `trace_macros!` : supply `true` or `false` to enable or disable macro expansion logging
552 * `stringify!` : turn the identifier argument into a string literal
553 * `concat_idents!` : create a new identifier by concatenating the arguments
555 # Crates and source files
557 Rust is a *compiled* language.
558 Its semantics obey a *phase distinction* between compile-time and run-time.
559 Those semantic rules that have a *static interpretation* govern the success or failure of compilation.
560 We refer to these rules as "static semantics".
561 Semantic rules called "dynamic semantics" govern the behavior of programs at run-time.
562 A program that fails to compile due to violation of a compile-time rule has no defined dynamic semantics; the compiler should halt with an error report, and produce no executable artifact.
564 The compilation model centres on artifacts called _crates_.
565 Each compilation processes a single crate in source form, and if successful, produces a single crate in binary form: either an executable or a library.^[A crate is somewhat
566 analogous to an *assembly* in the ECMA-335 CLI model, a *library* in the
567 SML/NJ Compilation Manager, a *unit* in the Owens and Flatt module system,
568 or a *configuration* in Mesa.]
570 A _crate_ is a unit of compilation and linking, as well as versioning, distribution and runtime loading.
571 A crate contains a _tree_ of nested [module](#modules) scopes.
572 The top level of this tree is a module that is anonymous (from the point of view of paths within the module) and any item within a crate has a canonical [module path](#paths) denoting its location within the crate's module tree.
574 The Rust compiler is always invoked with a single source file as input, and always produces a single output crate.
575 The processing of that source file may result in other source files being loaded as modules.
576 Source files have the extension `.rs`.
578 A Rust source file describes a module, the name and
579 location of which -- in the module tree of the current crate -- are defined
580 from outside the source file: either by an explicit `mod_item` in
581 a referencing source file, or by the name of the crate itself.
583 Each source file contains a sequence of zero or more `item` definitions,
584 and may optionally begin with any number of `attributes` that apply to the containing module.
585 Attributes on the anonymous crate module define important metadata that influences
586 the behavior of the compiler.
589 // Linkage attributes
590 #[ link(name = "projx",
592 uuid = "9cccc5d5-aceb-4af5-8285-811211826b82") ];
594 // Additional metadata attributes
595 #[ desc = "Project X" ];
596 #[ license = "BSD" ];
597 #[ author = "Jane Doe" ];
599 // Specify the output type
600 #[ crate_type = "lib" ];
603 #[ warn(non_camel_case_types) ];
606 A crate that contains a `main` function can be compiled to an executable.
607 If a `main` function is present, its return type must be [`unit`](#primitive-types) and it must take no arguments.
610 # Items and attributes
612 Crates contain [items](#items),
613 each of which may have some number of [attributes](#attributes) attached to it.
617 ~~~~~~~~ {.ebnf .gram}
618 item : mod_item | fn_item | type_item | struct_item | enum_item
619 | static_item | trait_item | impl_item | extern_block ;
622 An _item_ is a component of a crate; some module items can be defined in crate
623 files, but most are defined in source files. Items are organized within a
624 crate by a nested set of [modules](#modules). Every crate has a single
625 "outermost" anonymous module; all further items within the crate have
626 [paths](#paths) within the module tree of the crate.
628 Items are entirely determined at compile-time, generally remain fixed during
629 execution, and may reside in read-only memory.
631 There are several kinds of item:
633 * [modules](#modules)
634 * [functions](#functions)
635 * [type definitions](#type-definitions)
636 * [structures](#structures)
637 * [enumerations](#enumerations)
638 * [static items](#static-items)
640 * [implementations](#implementations)
642 Some items form an implicit scope for the declaration of sub-items. In other
643 words, within a function or module, declarations of items can (in many cases)
644 be mixed with the statements, control blocks, and similar artifacts that
645 otherwise compose the item body. The meaning of these scoped items is the same
646 as if the item was declared outside the scope -- it is still a static item --
647 except that the item's *path name* within the module namespace is qualified by
648 the name of the enclosing item, or is private to the enclosing item (in the
650 The grammar specifies the exact locations in which sub-item declarations may appear.
654 All items except modules may be *parameterized* by type. Type parameters are
655 given as a comma-separated list of identifiers enclosed in angle brackets
656 (`<...>`), after the name of the item and before its definition.
657 The type parameters of an item are considered "part of the name", not part of the type of the item.
658 A referencing [path](#paths) must (in principle) provide type arguments as a list of comma-separated types enclosed within angle brackets, in order to refer to the type-parameterized item.
659 In practice, the type-inference system can usually infer such argument types from context.
660 There are no general type-parametric types, only type-parametric items.
661 That is, Rust has no notion of type abstraction: there are no first-class "forall" types.
665 ~~~~~~~~ {.ebnf .gram}
666 mod_item : "mod" ident ( ';' | '{' mod '}' );
667 mod : [ view_item | item ] * ;
670 A module is a container for zero or more [view items](#view-items) and zero or
671 more [items](#items). The view items manage the visibility of the items
672 defined within the module, as well as the visibility of names from outside the
673 module when referenced from inside the module.
675 A _module item_ is a module, surrounded in braces, named, and prefixed with
676 the keyword `mod`. A module item introduces a new, named module into the tree
677 of modules making up a crate. Modules can nest arbitrarily.
679 An example of a module:
683 type complex = (f64, f64);
684 fn sin(f: f64) -> f64 {
688 fn cos(f: f64) -> f64 {
692 fn tan(f: f64) -> f64 {
699 Modules and types share the same namespace.
700 Declaring a named type that has the same name as a module in scope is forbidden:
701 that is, a type definition, trait, struct, enumeration, or type parameter
702 can't shadow the name of a module in scope, or vice versa.
704 A module without a body is loaded from an external file, by default with the same
705 name as the module, plus the `.rs` extension.
706 When a nested submodule is loaded from an external file,
707 it is loaded from a subdirectory path that mirrors the module hierarchy.
710 // Load the `vec` module from `vec.rs`
714 // Load the `local_data` module from `task/local_data.rs`
719 The directories and files used for loading external file modules can be influenced
720 with the `path` attribute.
723 #[path = "task_files"]
725 // Load the `local_data` module from `task_files/tls.rs`
733 ~~~~~~~~ {.ebnf .gram}
734 view_item : extern_mod_decl | use_decl ;
737 A view item manages the namespace of a module.
738 View items do not define new items, but rather, simply change other items' visibility.
739 There are several kinds of view item:
741 * [`extern mod` declarations](#extern-mod-declarations)
742 * [`use` declarations](#use-declarations)
744 ##### Extern mod declarations
746 ~~~~~~~~ {.ebnf .gram}
747 extern_mod_decl : "extern" "mod" ident [ '(' link_attrs ')' ] ? [ '=' string_lit ] ? ;
748 link_attrs : link_attr [ ',' link_attrs ] + ;
749 link_attr : ident '=' literal ;
752 An _`extern mod` declaration_ specifies a dependency on an external crate.
753 The external crate is then bound into the declaring scope
754 as the `ident` provided in the `extern_mod_decl`.
756 The external crate is resolved to a specific `soname` at compile time,
757 and a runtime linkage requirement to that `soname` is passed to the linker for
759 The `soname` is resolved at compile time by scanning the compiler's library path
760 and matching the `link_attrs` provided in the `use_decl` against any `#link` attributes that
761 were declared on the external crate when it was compiled.
762 If no `link_attrs` are provided,
763 a default `name` attribute is assumed,
764 equal to the `ident` given in the `use_decl`.
766 Optionally, an identifier in an `extern mod` declaration may be followed by an equals sign,
767 then a string literal denoting a relative path on the filesystem.
768 This path should exist in one of the directories in the Rust path,
769 which by default contains the `.rust` subdirectory of the current directory and each of its parents,
770 as well as any directories in the colon-separated (or semicolon-separated on Windows)
771 list of paths that is the `RUST_PATH` environment variable.
772 The meaning of `extern mod a = "b/c/d";`, supposing that `/a` is in the RUST_PATH,
773 is that the name `a` should be taken as a reference to the crate whose absolute location is
776 Four examples of `extern mod` declarations:
778 ~~~~~~~~{.xfail-test}
779 extern mod pcre (uuid = "54aba0f8-a7b1-4beb-92f1-4cf625264841");
781 extern mod extra; // equivalent to: extern mod extra ( name = "extra" );
783 extern mod rustextra (name = "extra"); // linking to 'extra' under another name
785 extern mod complicated_mod = "some-file/in/the-rust/path";
788 ##### Use declarations
790 ~~~~~~~~ {.ebnf .gram}
791 use_decl : "pub" ? "use" ident [ '=' path
794 path_glob : ident [ "::" path_glob ] ?
796 | '{' ident [ ',' ident ] * '}'
799 A _use declaration_ creates one or more local name bindings synonymous
800 with some other [path](#paths).
801 Usually a `use` declaration is used to shorten the path required to refer to a module item.
803 *Note*: Unlike in many languages,
804 `use` declarations in Rust do *not* declare linkage dependency with external crates.
805 Rather, [`extern mod` declarations](#extern-mod-declarations) declare linkage dependencies.
807 Use declarations support a number of convenient shortcuts:
809 * Rebinding the target name as a new local name, using the syntax `use x = p::q::r;`.
810 * Simultaneously binding a list of paths differing only in their final element,
811 using the glob-like brace syntax `use a::b::{c,d,e,f};`
812 * Binding all paths matching a given prefix, using the asterisk wildcard syntax `use a::b::*;`
814 An example of `use` declarations:
818 use std::option::{Some, None};
821 // Equivalent to 'info!(std::num::sin(1.0));'
824 // Equivalent to 'info!(~[std::option::Some(1.0), std::option::None]);'
825 info!(~[Some(1.0), None]);
829 Like items, `use` declarations are private to the containing module, by default.
830 Also like items, a `use` declaration can be public, if qualified by the `pub` keyword.
831 Such a `use` declaration serves to _re-export_ a name.
832 A public `use` declaration can therefore _redirect_ some public name to a different target definition:
833 even a definition with a private canonical path, inside a different module.
834 If a sequence of such redirections form a cycle or cannot be resolved unambiguously,
835 they represent a compile-time error.
837 An example of re-exporting:
841 pub use quux::foo::*;
850 In this example, the module `quux` re-exports all of the public names defined in `foo`.
852 Also note that the paths contained in `use` items are relative to the crate root.
853 So, in the previous example, the `use` refers to `quux::foo::*`, and not simply to `foo::*`.
857 A _function item_ defines a sequence of [statements](#statements) and an optional final [expression](#expressions), along with a name and a set of parameters.
858 Functions are declared with the keyword `fn`.
859 Functions declare a set of *input* [*slots*](#memory-slots) as parameters, through which the caller passes arguments into the function, and an *output* [*slot*](#memory-slots) through which the function passes results back to the caller.
861 A function may also be copied into a first class *value*, in which case the
862 value has the corresponding [*function type*](#function-types), and can be
863 used otherwise exactly as a function item (with a minor additional cost of
864 calling the function indirectly).
866 Every control path in a function logically ends with a `return` expression or a
867 diverging expression. If the outermost block of a function has a
868 value-producing expression in its final-expression position, that expression
869 is interpreted as an implicit `return` expression applied to the
872 An example of a function:
875 fn add(x: int, y: int) -> int {
880 As with `let` bindings, function arguments are irrefutable patterns,
881 so any pattern that is valid in a let binding is also valid as an argument.
884 fn first((value, _): (int, int)) -> int { value }
888 #### Generic functions
890 A _generic function_ allows one or more _parameterized types_ to
891 appear in its signature. Each type parameter must be explicitly
892 declared, in an angle-bracket-enclosed, comma-separated list following
896 fn iter<T>(seq: &[T], f: &fn(T)) {
897 for elt in seq.iter() { f(elt); }
899 fn map<T, U>(seq: &[T], f: &fn(T) -> U) -> ~[U] {
901 for elt in seq.iter() { acc.push(f(elt)); }
906 Inside the function signature and body, the name of the type parameter
907 can be used as a type name.
909 When a generic function is referenced, its type is instantiated based
910 on the context of the reference. For example, calling the `iter`
911 function defined above on `[1, 2]` will instantiate type parameter `T`
912 with `int`, and require the closure parameter to have type
915 The type parameters can also be explicitly supplied in a trailing
916 [path](#paths) component after the function name. This might be necessary
917 if there is not sufficient context to determine the type parameters. For
918 example, `sys::size_of::<u32>() == 4`.
920 Since a parameter type is opaque to the generic function, the set of
921 operations that can be performed on it is limited. Values of parameter
922 type can only be moved, not copied.
925 fn id<T>(x: T) -> T { x }
928 Similarly, [trait](#traits) bounds can be specified for type
929 parameters to allow methods with that trait to be called on values
933 #### Unsafe functions
935 Unsafe functions are those containing unsafe operations that are not contained in an [`unsafe` block](#unsafe-blocks).
936 Such a function must be prefixed with the keyword `unsafe`.
938 Unsafe operations are those that potentially violate the memory-safety guarantees of Rust's static semantics.
939 Specifically, the following operations are considered unsafe:
941 - Dereferencing a [raw pointer](#pointer-types).
942 - Casting a [raw pointer](#pointer-types) to a safe pointer type.
943 - Calling an unsafe function.
947 A block of code can also be prefixed with the `unsafe` keyword, to permit a sequence of unsafe operations in an otherwise-safe function.
948 This facility exists because the static semantics of Rust are a necessary approximation of the dynamic semantics.
949 When a programmer has sufficient conviction that a sequence of unsafe operations is actually safe, they can encapsulate that sequence (taken as a whole) within an `unsafe` block. The compiler will consider uses of such code "safe", to the surrounding context.
952 #### Diverging functions
954 A special kind of function can be declared with a `!` character where the
955 output slot type would normally be. For example:
958 fn my_err(s: &str) -> ! {
964 We call such functions "diverging" because they never return a value to the
965 caller. Every control path in a diverging function must end with a
966 `fail!()` or a call to another diverging function on every
967 control path. The `!` annotation does *not* denote a type. Rather, the result
968 type of a diverging function is a special type called $\bot$ ("bottom") that
969 unifies with any type. Rust has no syntax for $\bot$.
971 It might be necessary to declare a diverging function because as mentioned
972 previously, the typechecker checks that every control path in a function ends
973 with a [`return`](#return-expressions) or diverging expression. So, if `my_err`
974 were declared without the `!` annotation, the following code would not
978 # fn my_err(s: &str) -> ! { fail!() }
980 fn f(i: int) -> int {
985 my_err("Bad number!");
990 This will not compile without the `!` annotation on `my_err`,
991 since the `else` branch of the conditional in `f` does not return an `int`,
992 as required by the signature of `f`.
993 Adding the `!` annotation to `my_err` informs the typechecker that,
994 should control ever enter `my_err`, no further type judgments about `f` need to hold,
995 since control will never resume in any context that relies on those judgments.
996 Thus the return type on `f` only needs to reflect the `if` branch of the conditional.
999 #### Extern functions
1001 Extern functions are part of Rust's foreign function interface,
1002 providing the opposite functionality to [external blocks](#external-blocks).
1003 Whereas external blocks allow Rust code to call foreign code,
1004 extern functions with bodies defined in Rust code _can be called by foreign
1005 code_. They are defined in the same way as any other Rust function,
1006 except that they have the `extern` modifier.
1009 extern fn new_vec() -> ~[int] { ~[] }
1012 Extern functions may not be called from Rust code,
1013 but Rust code may take their value as a raw `u8` pointer.
1016 # extern fn new_vec() -> ~[int] { ~[] }
1017 let fptr: *u8 = new_vec;
1020 The primary motivation for extern functions is
1021 to create callbacks for foreign functions that expect to receive function
1024 ### Type definitions
1026 A _type definition_ defines a new name for an existing [type](#types). Type
1027 definitions are declared with the keyword `type`. Every value has a single,
1028 specific type; the type-specified aspects of a value include:
1030 * Whether the value is composed of sub-values or is indivisible.
1031 * Whether the value represents textual or numerical information.
1032 * Whether the value represents integral or floating-point information.
1033 * The sequence of memory operations required to access the value.
1034 * The [kind](#type-kinds) of the type.
1036 For example, the type `(u8, u8)` defines the set of immutable values that are composite pairs,
1037 each containing two unsigned 8-bit integers accessed by pattern-matching and laid out in memory with the `x` component preceding the `y` component.
1041 A _structure_ is a nominal [structure type](#structure-types) defined with the keyword `struct`.
1043 An example of a `struct` item and its use:
1046 struct Point {x: int, y: int}
1047 let p = Point {x: 10, y: 11};
1051 A _tuple structure_ is a nominal [tuple type](#tuple-types), also defined with the keyword `struct`.
1055 struct Point(int, int);
1056 let p = Point(10, 11);
1057 let px: int = match p { Point(x, _) => x };
1060 A _unit-like struct_ is a structure without any fields, defined by leaving off the list of fields entirely.
1061 Such types will have a single value, just like the [unit value `()`](#unit-and-boolean-literals) of the unit type.
1066 let c = [Cookie, Cookie, Cookie, Cookie];
1071 An _enumeration_ is a simultaneous definition of a nominal [enumerated type](#enumerated-types) as well as a set of *constructors*,
1072 that can be used to create or pattern-match values of the corresponding enumerated type.
1074 Enumerations are declared with the keyword `enum`.
1076 An example of an `enum` item and its use:
1084 let mut a: Animal = Dog;
1088 Enumeration constructors can have either named or unnamed fields:
1092 Cat { name: ~str, weight: float }
1095 let mut a: Animal = Dog(~"Cocoa", 37.2);
1096 a = Cat{ name: ~"Spotty", weight: 2.7 };
1099 In this example, `Cat` is a _struct-like enum variant_,
1100 whereas `Dog` is simply called an enum variant.
1104 ~~~~~~~~ {.ebnf .gram}
1105 static_item : "static" ident ':' type '=' expr ';' ;
1108 A *static item* is a named _constant value_ stored in the global data section of a crate.
1109 Immutable static items are stored in the read-only data section.
1110 The constant value bound to a static item is, like all constant values, evaluated at compile time.
1111 Static items have the `static` lifetime, which outlives all other lifetimes in a Rust program.
1112 Static items are declared with the `static` keyword.
1113 A static item must have a _constant expression_ giving its definition.
1115 Static items must be explicitly typed.
1116 The type may be ```bool```, ```char```, a number, or a type derived from those primitive types.
1117 The derived types are borrowed pointers with the `'static` lifetime,
1118 fixed-size arrays, tuples, and structs.
1121 static BIT1: uint = 1 << 0;
1122 static BIT2: uint = 1 << 1;
1124 static BITS: [uint, ..2] = [BIT1, BIT2];
1125 static STRING: &'static str = "bitstring";
1127 struct BitsNStrings<'self> {
1128 mybits: [uint, ..2],
1129 mystring: &'self str
1132 static bits_n_strings: BitsNStrings<'static> = BitsNStrings {
1138 #### Mutable statics
1140 If a static item is declared with the ```mut``` keyword, then it is allowed to
1141 be modified by the program. One of Rust's goals is to make concurrency bugs hard
1142 to run into, and this is obviously a very large source of race conditions or
1143 other bugs. For this reason, an ```unsafe``` block is required when either
1144 reading or writing a mutable static variable. Care should be taken to ensure
1145 that modifications to a mutable static are safe with respect to other tasks
1146 running in the same process.
1148 Mutable statics are still very useful, however. They can be used with C
1149 libraries and can also be bound from C libraries (in an ```extern``` block).
1152 # fn atomic_add(_: &mut uint, _: uint) -> uint { 2 }
1154 static mut LEVELS: uint = 0;
1156 // This violates the idea of no shared state, and this doesn't internally
1157 // protect against races, so this function is `unsafe`
1158 unsafe fn bump_levels_unsafe1() -> uint {
1164 // Assuming that we have an atomic_add function which returns the old value,
1165 // this function is "safe" but the meaning of the return value may not be what
1166 // callers expect, so it's still marked as `unsafe`
1167 unsafe fn bump_levels_unsafe2() -> uint {
1168 return atomic_add(&mut LEVELS, 1);
1175 A _trait_ describes a set of method types.
1177 Traits can include default implementations of methods,
1178 written in terms of some unknown [`self` type](#self-types);
1179 the `self` type may either be completely unspecified,
1180 or constrained by some other trait.
1182 Traits are implemented for specific types through separate [implementations](#implementations).
1185 # type Surface = int;
1186 # type BoundingBox = int;
1189 fn draw(&self, Surface);
1190 fn bounding_box(&self) -> BoundingBox;
1194 This defines a trait with two methods.
1195 All values that have [implementations](#implementations) of this trait in scope can have their `draw` and `bounding_box` methods called,
1196 using `value.bounding_box()` [syntax](#method-call-expressions).
1198 Type parameters can be specified for a trait to make it generic.
1199 These appear after the trait name, using the same syntax used in [generic functions](#generic-functions).
1203 fn len(&self) -> uint;
1204 fn elt_at(&self, n: uint) -> T;
1205 fn iter(&self, &fn(T));
1209 Generic functions may use traits as _bounds_ on their type parameters.
1210 This will have two effects: only types that have the trait may instantiate the parameter,
1211 and within the generic function,
1212 the methods of the trait can be called on values that have the parameter's type.
1216 # type Surface = int;
1217 # trait Shape { fn draw(&self, Surface); }
1219 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
1225 Traits also define an [object type](#object-types) with the same name as the trait.
1226 Values of this type are created by [casting](#type-cast-expressions) pointer values
1227 (pointing to a type for which an implementation of the given trait is in scope)
1228 to pointers to the trait name, used as a type.
1232 # impl Shape for int { }
1235 let myshape: @Shape = @mycircle as @Shape;
1238 The resulting value is a managed box containing the value that was cast,
1239 along with information that identifies the methods of the implementation that was used.
1240 Values with a trait type can have [methods called](#method-call-expressions) on them,
1241 for any method in the trait,
1242 and can be used to instantiate type parameters that are bounded by the trait.
1244 Trait methods may be static,
1245 which means that they lack a `self` argument.
1246 This means that they can only be called with function call syntax (`f(x)`)
1247 and not method call syntax (`obj.f()`).
1248 The way to refer to the name of a static method is to qualify it with the trait name,
1249 treating the trait name like a module.
1254 fn from_int(n: int) -> Self;
1256 impl Num for float {
1257 fn from_int(n: int) -> float { n as float }
1259 let x: float = Num::from_int(42);
1262 Traits may inherit from other traits. For example, in
1265 trait Shape { fn area() -> float; }
1266 trait Circle : Shape { fn radius() -> float; }
1269 the syntax `Circle : Shape` means that types that implement `Circle` must also have an implementation for `Shape`.
1270 Multiple supertraits are separated by spaces, `trait Circle : Shape Eq { }`.
1271 In an implementation of `Circle` for a given type `T`, methods can refer to `Shape` methods,
1272 since the typechecker checks that any type with an implementation of `Circle` also has an implementation of `Shape`.
1274 In type-parameterized functions,
1275 methods of the supertrait may be called on values of subtrait-bound type parameters.
1276 Referring to the previous example of `trait Circle : Shape`:
1279 # trait Shape { fn area(&self) -> float; }
1280 # trait Circle : Shape { fn radius(&self) -> float; }
1281 fn radius_times_area<T: Circle>(c: T) -> float {
1282 // `c` is both a Circle and a Shape
1283 c.radius() * c.area()
1287 Likewise, supertrait methods may also be called on trait objects.
1290 # trait Shape { fn area(&self) -> float; }
1291 # trait Circle : Shape { fn radius(&self) -> float; }
1292 # impl Shape for int { fn area(&self) -> float { 0.0 } }
1293 # impl Circle for int { fn radius(&self) -> float { 0.0 } }
1296 let mycircle: Circle = @mycircle as @Circle;
1297 let nonsense = mycircle.radius() * mycircle.area();
1302 An _implementation_ is an item that implements a [trait](#traits) for a specific type.
1304 Implementations are defined with the keyword `impl`.
1307 # struct Point {x: float, y: float};
1308 # type Surface = int;
1309 # struct BoundingBox {x: float, y: float, width: float, height: float};
1310 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
1311 # fn do_draw_circle(s: Surface, c: Circle) { }
1318 impl Shape for Circle {
1319 fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
1320 fn bounding_box(&self) -> BoundingBox {
1321 let r = self.radius;
1322 BoundingBox{x: self.center.x - r, y: self.center.y - r,
1323 width: 2.0 * r, height: 2.0 * r}
1328 It is possible to define an implementation without referring to a trait.
1329 The methods in such an implementation can only be used
1330 as direct calls on the values of the type that the implementation targets.
1331 In such an implementation, the trait type and `for` after `impl` are omitted.
1332 Such implementations are limited to nominal types (enums, structs),
1333 and the implementation must appear in the same module or a sub-module as the `self` type.
1335 When a trait _is_ specified in an `impl`,
1336 all methods declared as part of the trait must be implemented,
1337 with matching types and type parameter counts.
1339 An implementation can take type parameters,
1340 which can be different from the type parameters taken by the trait it implements.
1341 Implementation parameters are written after the `impl` keyword.
1346 impl<T> Seq<T> for ~[T] {
1349 impl Seq<bool> for u32 {
1350 /* Treat the integer as a sequence of bits */
1357 extern_block_item : "extern" '{' extern_block '} ;
1358 extern_block : [ foreign_fn ] * ;
1361 External blocks form the basis for Rust's foreign function interface.
1362 Declarations in an external block describe symbols
1363 in external, non-Rust libraries.
1365 Functions within external blocks
1366 are declared in the same way as other Rust functions,
1367 with the exception that they may not have a body
1368 and are instead terminated by a semicolon.
1371 # use std::libc::{c_char, FILE};
1375 fn fopen(filename: *c_char, mode: *c_char) -> *FILE;
1379 Functions within external blocks may be called by Rust code,
1380 just like functions defined in Rust.
1381 The Rust compiler automatically translates
1382 between the Rust ABI and the foreign ABI.
1384 A number of [attributes](#attributes) control the behavior of external
1387 By default external blocks assume
1388 that the library they are calling uses the standard C "cdecl" ABI.
1389 Other ABIs may be specified using the `abi` attribute as in
1392 // Interface to the Windows API
1397 The `link_name` attribute allows the name of the library to be specified.
1400 #[link_name = "crypto"]
1404 The `nolink` attribute tells the Rust compiler
1405 not to do any linking for the external block.
1406 This is particularly useful for creating external blocks for libc,
1407 which tends to not follow standard library naming conventions
1408 and is linked to all Rust programs anyway.
1412 ~~~~~~~~{.ebnf .gram}
1413 attribute : '#' '[' attr_list ']' ;
1414 attr_list : attr [ ',' attr_list ]*
1415 attr : ident [ '=' literal
1416 | '(' attr_list ')' ] ? ;
1419 Static entities in Rust -- crates, modules and items -- may have _attributes_
1420 applied to them. ^[Attributes in Rust are modeled on Attributes in ECMA-335,
1422 An attribute is a general, free-form metadatum that is interpreted according to name, convention, and language and compiler version.
1423 Attributes may appear as any of
1425 * A single identifier, the attribute name
1426 * An identifier followed by the equals sign '=' and a literal, providing a key/value pair
1427 * An identifier followed by a parenthesized list of sub-attribute arguments
1429 Attributes terminated by a semi-colon apply to the entity that the attribute is declared
1430 within. Attributes that are not terminated by a semi-colon apply to the next entity.
1432 An example of attributes:
1434 ~~~~~~~~{.xfail-test}
1435 // General metadata applied to the enclosing module or crate.
1438 // A function marked as a unit test
1444 // A conditionally-compiled module
1445 #[cfg(target_os="linux")]
1450 // A lint attribute used to suppress a warning/error
1451 #[allow(non_camel_case_types)]
1452 pub type int8_t = i8;
1455 > **Note:** In future versions of Rust, user-provided extensions to the compiler will be able to interpret attributes.
1456 > When this facility is provided, the compiler will distinguish between language-reserved and user-available attributes.
1458 At present, only the Rust compiler interprets attributes, so all attribute
1459 names are effectively reserved. Some significant attributes include:
1461 * The `doc` attribute, for documenting code in-place.
1462 * The `cfg` attribute, for conditional-compilation by build-configuration.
1463 * The `lang` attribute, for custom definitions of traits and functions that are known to the Rust compiler (see [Language items](#language-items)).
1464 * The `link` attribute, for describing linkage metadata for a crate.
1465 * The `test` attribute, for marking functions as unit tests.
1466 * The `allow`, `warn`, `forbid`, and `deny` attributes, for
1467 controlling lint checks (see [Lint check attributes](#lint-check-attributes)).
1468 * The `deriving` attribute, for automatically generating
1469 implementations of certain traits.
1470 * The `static_assert` attribute, for asserting that a static bool is true at compiletime
1472 Other attributes may be added or removed during development of the language.
1474 ### Lint check attributes
1476 A lint check names a potentially undesirable coding pattern, such as
1477 unreachable code or omitted documentation, for the static entity to
1478 which the attribute applies.
1480 For any lint check `C`:
1482 * `warn(C)` warns about violations of `C` but continues compilation,
1483 * `deny(C)` signals an error after encountering a violation of `C`,
1484 * `allow(C)` overrides the check for `C` so that violations will go
1486 * `forbid(C)` is the same as `deny(C)`, but also forbids uses of
1487 `allow(C)` within the entity.
1489 The lint checks supported by the compiler can be found via `rustc -W help`,
1490 along with their default settings.
1494 // Missing documentation is ignored here
1495 #[allow(missing_doc)]
1496 pub fn undocumented_one() -> int { 1 }
1498 // Missing documentation signals a warning here
1499 #[warn(missing_doc)]
1500 pub fn undocumented_too() -> int { 2 }
1502 // Missing documentation signals an error here
1503 #[deny(missing_doc)]
1504 pub fn undocumented_end() -> int { 3 }
1508 This example shows how one can use `allow` and `warn` to toggle
1509 a particular check on and off.
1512 #[warn(missing_doc)]
1514 #[allow(missing_doc)]
1516 // Missing documentation is ignored here
1517 pub fn undocumented_one() -> int { 1 }
1519 // Missing documentation signals a warning here,
1520 // despite the allow above.
1521 #[warn(missing_doc)]
1522 pub fn undocumented_two() -> int { 2 }
1525 // Missing documentation signals a warning here
1526 pub fn undocumented_too() -> int { 3 }
1530 This example shows how one can use `forbid` to disallow uses
1531 of `allow` for that lint check.
1534 #[forbid(missing_doc)]
1536 // Attempting to toggle warning signals an error here
1537 #[allow(missing_doc)]
1539 pub fn undocumented_too() -> int { 2 }
1545 Some primitive Rust operations are defined in Rust code,
1546 rather than being implemented directly in C or assembly language.
1547 The definitions of these operations have to be easy for the compiler to find.
1548 The `lang` attribute makes it possible to declare these operations.
1549 For example, the `str` module in the Rust standard library defines the string equality function:
1553 pub fn eq_slice(a: &str, b: &str) -> bool {
1558 The name `str_eq` has a special meaning to the Rust compiler,
1559 and the presence of this definition means that it will use this definition
1560 when generating calls to the string equality function.
1562 A complete list of the built-in language items follows:
1567 : Cannot be mutated.
1569 : Are uniquely owned.
1571 : Contain borrowed pointers.
1575 : Elements can be added (for example, integers and floats).
1577 : Elements can be subtracted.
1579 : Elements can be multiplied.
1581 : Elements have a division operation.
1583 : Elements have a remainder operation.
1585 : Elements can be negated arithmetically.
1587 : Elements can be negated logically.
1589 : Elements have an exclusive-or operation.
1591 : Elements have a bitwise `and` operation.
1593 : Elements have a bitwise `or` operation.
1595 : Elements have a left shift operation.
1597 : Elements have a right shift operation.
1599 : Elements can be indexed.
1601 : Elements can be compared for equality.
1603 : Elements have a partial ordering.
1608 : Compare two strings for equality.
1610 : Compare two owned strings for equality.
1612 : Destroy a box before freeing it.
1614 : Generically print a string representation of any type.
1616 : Abort the program with an error.
1618 : Abort the program with a bounds check error.
1620 : Allocate memory on the exchange heap.
1622 : Free memory that was allocated on the exchange heap.
1624 : Allocate memory on the managed heap.
1626 : Free memory that was allocated on the managed heap.
1628 : Create an immutable borrowed pointer to a mutable value.
1630 : Release a borrowed pointer created with `return_to_mut`
1631 `check_not_borrowed`
1632 : Fail if a value has existing borrowed pointers to it.
1634 : Return a new unique string
1635 containing a copy of the contents of a unique string.
1637 > **Note:** This list is likely to become out of date. We should auto-generate it
1638 > from `librustc/middle/lang_items.rs`.
1642 The `deriving` attribute allows certain traits to be automatically
1643 implemented for data structures. For example, the following will
1644 create an `impl` for the `Eq` and `Clone` traits for `Foo`, the type
1645 parameter `T` will be given the `Eq` or `Clone` constraints for the
1649 #[deriving(Eq, Clone)]
1656 The generated `impl` for `Eq` is equivalent to
1659 # struct Foo<T> { a: int, b: T }
1660 impl<T: Eq> Eq for Foo<T> {
1661 fn eq(&self, other: &Foo<T>) -> bool {
1662 self.a == other.a && self.b == other.b
1665 fn ne(&self, other: &Foo<T>) -> bool {
1666 self.a != other.a || self.b != other.b
1671 Supported traits for `deriving` are:
1673 * Comparison traits: `Eq`, `TotalEq`, `Ord`, `TotalOrd`.
1674 * Serialization: `Encodable`, `Decodable`. These require `extra`.
1675 * `Clone` and `DeepClone`, to perform (deep) copies.
1676 * `IterBytes`, to iterate over the bytes in a data type.
1677 * `Rand`, to create a random instance of a data type.
1678 * `Zero`, to create an zero (or empty) instance of a data type.
1679 * `ToStr`, to convert to a string. For a type with this instance,
1680 `obj.to_str()` has similar output as `fmt!("%?", obj)`, but it differs in that
1681 each constituent field of the type must also implement `ToStr` and will have
1682 `field.to_str()` invoked to build up the result.
1684 # Statements and expressions
1686 Rust is _primarily_ an expression language. This means that most forms of
1687 value-producing or effect-causing evaluation are directed by the uniform
1688 syntax category of _expressions_. Each kind of expression can typically _nest_
1689 within each other kind of expression, and rules for evaluation of expressions
1690 involve specifying both the value produced by the expression and the order in
1691 which its sub-expressions are themselves evaluated.
1693 In contrast, statements in Rust serve _mostly_ to contain and explicitly
1694 sequence expression evaluation.
1698 A _statement_ is a component of a block, which is in turn a component of an
1699 outer [expression](#expressions) or [function](#functions).
1701 Rust has two kinds of statement:
1702 [declaration statements](#declaration-statements) and
1703 [expression statements](#expression-statements).
1705 ### Declaration statements
1707 A _declaration statement_ is one that introduces one or more *names* into the enclosing statement block.
1708 The declared names may denote new slots or new items.
1710 #### Item declarations
1712 An _item declaration statement_ has a syntactic form identical to an
1713 [item](#items) declaration within a module. Declaring an item -- a function,
1714 enumeration, structure, type, static, trait, implementation or module -- locally
1715 within a statement block is simply a way of restricting its scope to a narrow
1716 region containing all of its uses; it is otherwise identical in meaning to
1717 declaring the item outside the statement block.
1719 Note: there is no implicit capture of the function's dynamic environment when
1720 declaring a function-local item.
1723 #### Slot declarations
1725 ~~~~~~~~{.ebnf .gram}
1726 let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
1727 init : [ '=' ] expr ;
1730 A _slot declaration_ introduces a new set of slots, given by a pattern.
1731 The pattern may be followed by a type annotation, and/or an initializer expression.
1732 When no type annotation is given, the compiler will infer the type,
1733 or signal an error if insufficient type information is available for definite inference.
1734 Any slots introduced by a slot declaration are visible from the point of declaration until the end of the enclosing block scope.
1736 ### Expression statements
1738 An _expression statement_ is one that evaluates an [expression](#expressions)
1739 and ignores its result.
1740 The type of an expression statement `e;` is always `()`, regardless of the type of `e`.
1741 As a rule, an expression statement's purpose is to trigger the effects of evaluating its expression.
1745 An expression may have two roles: it always produces a *value*, and it may have *effects*
1746 (otherwise known as "side effects").
1747 An expression *evaluates to* a value, and has effects during *evaluation*.
1748 Many expressions contain sub-expressions (operands).
1749 The meaning of each kind of expression dictates several things:
1750 * Whether or not to evaluate the sub-expressions when evaluating the expression
1751 * The order in which to evaluate the sub-expressions
1752 * How to combine the sub-expressions' values to obtain the value of the expression.
1754 In this way, the structure of expressions dictates the structure of execution.
1755 Blocks are just another kind of expression,
1756 so blocks, statements, expressions, and blocks again can recursively nest inside each other
1757 to an arbitrary depth.
1759 #### Lvalues, rvalues and temporaries
1761 Expressions are divided into two main categories: _lvalues_ and _rvalues_.
1762 Likewise within each expression, sub-expressions may occur in _lvalue context_ or _rvalue context_.
1763 The evaluation of an expression depends both on its own category and the context it occurs within.
1765 [Path](#path-expressions), [field](#field-expressions) and [index](#index-expressions) expressions are lvalues.
1766 All other expressions are rvalues.
1768 The left operand of an [assignment](#assignment-expressions),
1769 [binary move](#binary-move-expressions) or
1770 [compound-assignment](#compound-assignment-expressions) expression is an lvalue context,
1771 as is the single operand of a unary [borrow](#unary-operator-expressions),
1772 or [move](#unary-move-expressions) expression,
1773 and _both_ operands of a [swap](#swap-expressions) expression.
1774 All other expression contexts are rvalue contexts.
1776 When an lvalue is evaluated in an _lvalue context_, it denotes a memory location;
1777 when evaluated in an _rvalue context_, it denotes the value held _in_ that memory location.
1779 When an rvalue is used in lvalue context, a temporary un-named lvalue is created and used instead.
1780 A temporary's lifetime equals the largest lifetime of any borrowed pointer that points to it.
1782 #### Moved and copied types
1784 When a [local variable](#memory-slots) is used
1785 as an [rvalue](#lvalues-rvalues-and-temporaries)
1786 the variable will either be [moved](#move-expressions) or copied,
1787 depending on its type.
1788 For types that contain [owning pointers](#owning-pointers)
1789 or values that implement the special trait `Drop`,
1790 the variable is moved.
1791 All other types are copied.
1794 ### Literal expressions
1796 A _literal expression_ consists of one of the [literal](#literals)
1797 forms described earlier. It directly describes a number, character,
1798 string, boolean value, or the unit value.
1800 ~~~~~~~~ {.literals}
1802 "hello"; // string type
1803 '5'; // character type
1807 ### Path expressions
1809 A [path](#paths) used as an expression context denotes either a local variable or an item.
1810 Path expressions are [lvalues](#lvalues-rvalues-and-temporaries).
1812 ### Tuple expressions
1814 Tuples are written by enclosing one or more comma-separated
1815 expressions in parentheses. They are used to create [tuple-typed](#tuple-types)
1824 ### Structure expressions
1826 ~~~~~~~~{.ebnf .gram}
1827 struct_expr : expr_path '{' ident ':' expr
1828 [ ',' ident ':' expr ] *
1831 [ ',' expr ] * ')' |
1835 There are several forms of structure expressions.
1836 A _structure expression_ consists of the [path](#paths) of a [structure item](#structures),
1837 followed by a brace-enclosed list of one or more comma-separated name-value pairs,
1838 providing the field values of a new instance of the structure.
1839 A field name can be any identifier, and is separated from its value expression by a colon.
1840 The location denoted by a structure field is mutable if and only if the enclosing structure is mutable.
1842 A _tuple structure expression_ consists of the [path](#paths) of a [structure item](#structures),
1843 followed by a parenthesized list of one or more comma-separated expressions
1844 (in other words, the path of a structure item followed by a tuple expression).
1845 The structure item must be a tuple structure item.
1847 A _unit-like structure expression_ consists only of the [path](#paths) of a [structure item](#structures).
1849 The following are examples of structure expressions:
1852 # struct Point { x: float, y: float }
1853 # struct TuplePoint(float, float);
1854 # mod game { pub struct User<'self> { name: &'self str, age: uint, score: uint } }
1855 # struct Cookie; fn some_fn<T>(t: T) {}
1856 Point {x: 10f, y: 20f};
1857 TuplePoint(10f, 20f);
1858 let u = game::User {name: "Joe", age: 35, score: 100_000};
1859 some_fn::<Cookie>(Cookie);
1862 A structure expression forms a new value of the named structure type.
1863 Note that for a given *unit-like* structure type, this will always be the same value.
1865 A structure expression can terminate with the syntax `..` followed by an expression to denote a functional update.
1866 The expression following `..` (the base) must have the same structure type as the new structure type being formed.
1867 The entire expression denotes the result of allocating a new structure
1868 (with the same type as the base expression)
1869 with the given values for the fields that were explicitly specified
1870 and the values in the base record for all other fields.
1873 # struct Point3d { x: int, y: int, z: int }
1874 let base = Point3d {x: 1, y: 2, z: 3};
1875 Point3d {y: 0, z: 10, .. base};
1878 ### Record expressions
1880 ~~~~~~~~{.ebnf .gram}
1881 rec_expr : '{' ident ':' expr
1882 [ ',' ident ':' expr ] *
1886 ### Method-call expressions
1888 ~~~~~~~~{.ebnf .gram}
1889 method_call_expr : expr '.' ident paren_expr_list ;
1892 A _method call_ consists of an expression followed by a single dot, an identifier, and a parenthesized expression-list.
1893 Method calls are resolved to methods on specific traits,
1894 either statically dispatching to a method if the exact `self`-type of the left-hand-side is known,
1895 or dynamically dispatching if the left-hand-side expression is an indirect [object type](#object-types).
1898 ### Field expressions
1900 ~~~~~~~~{.ebnf .gram}
1901 field_expr : expr '.' ident
1904 A _field expression_ consists of an expression followed by a single dot and an identifier,
1905 when not immediately followed by a parenthesized expression-list (the latter is a [method call expression](#method-call-expressions)).
1906 A field expression denotes a field of a [structure](#structure-types).
1913 A field access on a record is an [lvalue](#lvalues-rvalues-and-temporaries) referring to the value of that field.
1914 When the field is mutable, it can be [assigned](#assignment-expressions) to.
1916 When the type of the expression to the left of the dot is a pointer to a record or structure,
1917 it is automatically dereferenced to make the field access possible.
1920 ### Vector expressions
1922 ~~~~~~~~{.ebnf .gram}
1923 vec_expr : '[' "mut" ? vec_elems? ']'
1925 vec_elems : [expr [',' expr]*] | [expr ',' ".." expr]
1928 A [_vector_](#vector-types) _expression_ is written by enclosing zero or
1929 more comma-separated expressions of uniform type in square brackets.
1931 In the `[expr ',' ".." expr]` form, the expression after the `".."`
1932 must be a constant expression that can be evaluated at compile time, such
1933 as a [literal](#literals) or a [static item](#static-items).
1937 ["a", "b", "c", "d"];
1938 [0, ..128]; // vector with 128 zeros
1939 [0u8, 0u8, 0u8, 0u8];
1942 ### Index expressions
1944 ~~~~~~~~{.ebnf .gram}
1945 idx_expr : expr '[' expr ']'
1949 [Vector](#vector-types)-typed expressions can be indexed by writing a
1950 square-bracket-enclosed expression (the index) after them. When the
1951 vector is mutable, the resulting [lvalue](#lvalues-rvalues-and-temporaries) can be assigned to.
1953 Indices are zero-based, and may be of any integral type. Vector access
1954 is bounds-checked at run-time. When the check fails, it will put the
1955 task in a _failing state_.
1959 # do task::spawn_unlinked {
1962 (["a", "b"])[10]; // fails
1967 ### Unary operator expressions
1969 Rust defines six symbolic unary operators.
1970 They are all written as prefix operators,
1971 before the expression they apply to.
1974 : Negation. May only be applied to numeric types.
1976 : Dereference. When applied to a [pointer](#pointer-types) it denotes the pointed-to location.
1977 For pointers to mutable locations, the resulting [lvalue](#lvalues-rvalues-and-temporaries) can be assigned to.
1978 For [enums](#enumerated-types) that have only a single variant, containing a single parameter,
1979 the dereference operator accesses this parameter.
1981 : Logical negation. On the boolean type, this flips between `true` and
1982 `false`. On integer types, this inverts the individual bits in the
1983 two's complement representation of the value.
1985 : [Boxing](#pointer-types) operators. Allocate a box to hold the value they are applied to,
1986 and store the value in it. `@` creates a managed box, whereas `~` creates an owned box.
1988 : Borrow operator. Returns a borrowed pointer, pointing to its operand.
1989 The operand of a borrowed pointer is statically proven to outlive the resulting pointer.
1990 If the borrow-checker cannot prove this, it is a compilation error.
1992 ### Binary operator expressions
1994 ~~~~~~~~{.ebnf .gram}
1995 binop_expr : expr binop expr ;
1998 Binary operators expressions are given in terms of
1999 [operator precedence](#operator-precedence).
2001 #### Arithmetic operators
2003 Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
2004 defined in the `std::ops` module of the `std` library.
2005 This means that arithmetic operators can be overridden for user-defined types.
2006 The default meaning of the operators on standard types is given here.
2009 : Addition and vector/string concatenation.
2010 Calls the `add` method on the `std::ops::Add` trait.
2013 Calls the `sub` method on the `std::ops::Sub` trait.
2016 Calls the `mul` method on the `std::ops::Mul` trait.
2019 Calls the `div` method on the `std::ops::Div` trait.
2022 Calls the `rem` method on the `std::ops::Rem` trait.
2024 #### Bitwise operators
2026 Like the [arithmetic operators](#arithmetic-operators), bitwise operators
2027 are syntactic sugar for calls to methods of built-in traits.
2028 This means that bitwise operators can be overridden for user-defined types.
2029 The default meaning of the operators on standard types is given here.
2033 Calls the `bitand` method of the `std::ops::BitAnd` trait.
2036 Calls the `bitor` method of the `std::ops::BitOr` trait.
2039 Calls the `bitxor` method of the `std::ops::BitXor` trait.
2041 : Logical left shift.
2042 Calls the `shl` method of the `std::ops::Shl` trait.
2044 : Logical right shift.
2045 Calls the `shr` method of the `std::ops::Shr` trait.
2047 #### Lazy boolean operators
2049 The operators `||` and `&&` may be applied to operands of boolean type.
2050 The `||` operator denotes logical 'or', and the `&&` operator denotes logical 'and'.
2051 They differ from `|` and `&` in that the right-hand operand is only evaluated
2052 when the left-hand operand does not already determine the result of the expression.
2053 That is, `||` only evaluates its right-hand operand
2054 when the left-hand operand evaluates to `false`, and `&&` only when it evaluates to `true`.
2056 #### Comparison operators
2058 Comparison operators are, like the [arithmetic operators](#arithmetic-operators),
2059 and [bitwise operators](#bitwise-operators),
2060 syntactic sugar for calls to built-in traits.
2061 This means that comparison operators can be overridden for user-defined types.
2062 The default meaning of the operators on standard types is given here.
2066 Calls the `eq` method on the `std::cmp::Eq` trait.
2069 Calls the `ne` method on the `std::cmp::Eq` trait.
2072 Calls the `lt` method on the `std::cmp::Ord` trait.
2075 Calls the `gt` method on the `std::cmp::Ord` trait.
2077 : Less than or equal.
2078 Calls the `le` method on the `std::cmp::Ord` trait.
2080 : Greater than or equal.
2081 Calls the `ge` method on the `std::cmp::Ord` trait.
2084 #### Type cast expressions
2086 A type cast expression is denoted with the binary operator `as`.
2088 Executing an `as` expression casts the value on the left-hand side to the type
2089 on the right-hand side.
2091 A numeric value can be cast to any numeric type.
2092 A raw pointer value can be cast to or from any integral type or raw pointer type.
2093 Any other cast is unsupported and will fail to compile.
2095 An example of an `as` expression:
2098 # fn sum(v: &[float]) -> float { 0.0 }
2099 # fn len(v: &[float]) -> int { 0 }
2101 fn avg(v: &[float]) -> float {
2102 let sum: float = sum(v);
2103 let sz: float = len(v) as float;
2108 #### Assignment expressions
2110 An _assignment expression_ consists of an [lvalue](#lvalues-rvalues-and-temporaries) expression followed by an
2111 equals sign (`=`) and an [rvalue](#lvalues-rvalues-and-temporaries) expression.
2113 Evaluating an assignment expression [either copies or moves](#moved-and-copied-types) its right-hand operand to its left-hand operand.
2122 #### Compound assignment expressions
2124 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>`
2125 operators may be composed with the `=` operator. The expression `lval
2126 OP= val` is equivalent to `lval = lval OP val`. For example, `x = x +
2127 1` may be written as `x += 1`.
2129 Any such expression always has the [`unit`](#primitive-types) type.
2131 #### Operator precedence
2133 The precedence of Rust binary operators is ordered as follows, going
2134 from strong to weak:
2151 Operators at the same precedence level are evaluated left-to-right. [Unary operators](#unary-operator-expressions)
2152 have the same precedence level and it is stronger than any of the binary operators'.
2154 ### Grouped expressions
2156 An expression enclosed in parentheses evaluates to the result of the enclosed
2157 expression. Parentheses can be used to explicitly specify evaluation order
2158 within an expression.
2160 ~~~~~~~~{.ebnf .gram}
2161 paren_expr : '(' expr ')' ;
2164 An example of a parenthesized expression:
2167 let x = (2 + 3) * 4;
2171 ### Call expressions
2173 ~~~~~~~~ {.abnf .gram}
2174 expr_list : [ expr [ ',' expr ]* ] ? ;
2175 paren_expr_list : '(' expr_list ')' ;
2176 call_expr : expr paren_expr_list ;
2179 A _call expression_ invokes a function, providing zero or more input slots and
2180 an optional reference slot to serve as the function's output, bound to the
2181 `lval` on the right hand side of the call. If the function eventually returns,
2182 then the expression completes.
2184 Some examples of call expressions:
2187 # use std::from_str::FromStr;
2188 # fn add(x: int, y: int) -> int { 0 }
2190 let x: int = add(1, 2);
2191 let pi = FromStr::from_str::<f32>("3.14");
2194 ### Lambda expressions
2196 ~~~~~~~~ {.abnf .gram}
2197 ident_list : [ ident [ ',' ident ]* ] ? ;
2198 lambda_expr : '|' ident_list '|' expr ;
2201 A _lambda expression_ (sometimes called an "anonymous function expression") defines a function and denotes it as a value,
2202 in a single expression.
2203 A lambda expression is a pipe-symbol-delimited (`|`) list of identifiers followed by an expression.
2205 A lambda expression denotes a function that maps a list of parameters (`ident_list`)
2206 onto the expression that follows the `ident_list`.
2207 The identifiers in the `ident_list` are the parameters to the function.
2208 These parameters' types need not be specified, as the compiler infers them from context.
2210 Lambda expressions are most useful when passing functions as arguments to other functions,
2211 as an abbreviation for defining and capturing a separate function.
2213 Significantly, lambda expressions _capture their environment_,
2214 which regular [function definitions](#functions) do not.
2215 The exact type of capture depends on the [function type](#function-types) inferred for the lambda expression.
2216 In the simplest and least-expensive form (analogous to a ```&fn() { }``` expression),
2217 the lambda expression captures its environment by reference,
2218 effectively borrowing pointers to all outer variables mentioned inside the function.
2219 Alternately, the compiler may infer that a lambda expression should copy or move values (depending on their type.)
2220 from the environment into the lambda expression's captured environment.
2222 In this example, we define a function `ten_times` that takes a higher-order function argument,
2223 and call it with a lambda expression as an argument.
2226 fn ten_times(f: &fn(int)) {
2234 ten_times(|j| println(fmt!("hello, %d", j)));
2240 ~~~~~~~~{.ebnf .gram}
2241 while_expr : "while" expr '{' block '}' ;
2244 A `while` loop begins by evaluating the boolean loop conditional expression.
2245 If the loop conditional expression evaluates to `true`, the loop body block
2246 executes and control returns to the loop conditional expression. If the loop
2247 conditional expression evaluates to `false`, the `while` expression completes.
2262 The keyword `loop` in Rust appears both in _loop expressions_ and in _continue expressions_.
2263 A loop expression denotes an infinite loop;
2264 see [Continue expressions](#continue-expressions) for continue expressions.
2266 ~~~~~~~~{.ebnf .gram}
2267 loop_expr : [ lifetime ':' ] "loop" '{' block '}';
2270 A `loop` expression may optionally have a _label_.
2271 If a label is present,
2272 then labeled `break` and `loop` expressions nested within this loop may exit out of this loop or return control to its head.
2273 See [Break expressions](#break-expressions).
2275 ### Break expressions
2277 ~~~~~~~~{.ebnf .gram}
2278 break_expr : "break" [ lifetime ];
2281 A `break` expression has an optional `label`.
2282 If the label is absent, then executing a `break` expression immediately terminates the innermost loop enclosing it.
2283 It is only permitted in the body of a loop.
2284 If the label is present, then `break foo` terminates the loop with label `foo`,
2285 which need not be the innermost label enclosing the `break` expression,
2286 but must enclose it.
2288 ### Continue expressions
2290 ~~~~~~~~{.ebnf .gram}
2291 continue_expr : "loop" [ lifetime ];
2294 A continue expression, written `loop`, also has an optional `label`.
2295 If the label is absent,
2296 then executing a `loop` expression immediately terminates the current iteration of the innermost loop enclosing it,
2297 returning control to the loop *head*.
2298 In the case of a `while` loop,
2299 the head is the conditional expression controlling the loop.
2300 In the case of a `for` loop, the head is the call-expression controlling the loop.
2301 If the label is present, then `loop foo` returns control to the head of the loop with label `foo`,
2302 which need not be the innermost label enclosing the `break` expression,
2303 but must enclose it.
2305 A `loop` expression is only permitted in the body of a loop.
2310 ~~~~~~~~{.ebnf .gram}
2311 do_expr : "do" expr [ '|' ident_list '|' ] ? '{' block '}' ;
2314 A _do expression_ provides a more-familiar block-syntax for a [lambda expression](#lambda-expressions),
2315 including a special translation of [return expressions](#return-expressions) inside the supplied block.
2317 Any occurrence of a [return expression](#return-expressions)
2318 inside this `block` expression is rewritten
2319 as a reference to an (anonymous) flag set in the caller's environment,
2320 which is checked on return from the `expr` and, if set,
2321 causes a corresponding return from the caller.
2322 In this way, the meaning of `return` statements in language built-in control blocks is preserved,
2323 if they are rewritten using lambda functions and `do` expressions as abstractions.
2325 The optional `ident_list` and `block` provided in a `do` expression are parsed as though they constitute a lambda expression;
2326 if the `ident_list` is missing, an empty `ident_list` is implied.
2328 The lambda expression is then provided as a _trailing argument_
2329 to the outermost [call](#call-expressions) or [method call](#method-call-expressions) expression
2330 in the `expr` following `do`.
2331 If the `expr` is a [path expression](#path-expressions), it is parsed as though it is a call expression.
2332 If the `expr` is a [field expression](#field-expressions), it is parsed as though it is a method call expression.
2334 In this example, both calls to `f` are equivalent:
2337 # fn f(f: &fn(int)) { }
2347 In this example, both calls to the (binary) function `k` are equivalent:
2350 # fn k(x:int, f: &fn(int)) { }
2363 ~~~~~~~~{.ebnf .gram}
2364 for_expr : "for" expr [ '|' ident_list '|' ] ? '{' block '}' ;
2367 A _for expression_ is similar to a [`do` expression](#do-expressions),
2368 in that it provides a special block-form of lambda expression,
2369 suited to passing the `block` function to a higher-order function implementing a loop.
2371 In contrast to a `do` expression, a `for` expression is designed to work
2372 with methods such as `each` and `times`, that require the body block to
2373 return a boolean. The `for` expression accommodates this by implicitly
2374 returning `true` at the end of each block, unless a `break` expression
2377 In addition, [`break`](#break-expressions) and [`loop`](#loop-expressions) expressions
2378 are rewritten inside `for` expressions in the same way that `return` expressions are,
2379 with a combination of local flag variables,
2380 and early boolean-valued returns from the `block` function,
2381 such that the meaning of `break` and `loop` is preserved in a primitive loop
2382 when rewritten as a `for` loop controlled by a higher order function.
2384 An example of a for loop over the contents of a vector:
2388 # fn bar(f: foo) { }
2393 let v: &[foo] = &[a, b, c];
2400 An example of a for loop over a series of integers:
2403 # fn bar(b:uint) { }
2404 for i in range(0u, 256) {
2411 ~~~~~~~~{.ebnf .gram}
2412 if_expr : "if" expr '{' block '}'
2415 else_tail : "else" [ if_expr
2419 An `if` expression is a conditional branch in program control. The form of
2420 an `if` expression is a condition expression, followed by a consequent
2421 block, any number of `else if` conditions and blocks, and an optional
2422 trailing `else` block. The condition expressions must have type
2423 `bool`. If a condition expression evaluates to `true`, the
2424 consequent block is executed and any subsequent `else if` or `else`
2425 block is skipped. If a condition expression evaluates to `false`, the
2426 consequent block is skipped and any subsequent `else if` condition is
2427 evaluated. If all `if` and `else if` conditions evaluate to `false`
2428 then any `else` block is executed.
2431 ### Match expressions
2433 ~~~~~~~~{.ebnf .gram}
2434 match_expr : "match" expr '{' match_arm [ '|' match_arm ] * '}' ;
2436 match_arm : match_pat '=>' [ expr "," | '{' block '}' ] ;
2438 match_pat : pat [ ".." pat ] ? [ "if" expr ] ;
2442 A `match` expression branches on a *pattern*. The exact form of matching that
2443 occurs depends on the pattern. Patterns consist of some combination of
2444 literals, destructured enum constructors, structures, records and tuples, variable binding
2445 specifications, wildcards (`*`), and placeholders (`_`). A `match` expression has a *head
2446 expression*, which is the value to compare to the patterns. The type of the
2447 patterns must equal the type of the head expression.
2449 In a pattern whose head expression has an `enum` type, a placeholder (`_`) stands for a
2450 *single* data field, whereas a wildcard `*` stands for *all* the fields of a particular
2451 variant. For example:
2454 enum List<X> { Nil, Cons(X, @List<X>) }
2456 let x: List<int> = Cons(10, @Cons(11, @Nil));
2459 Cons(_, @Nil) => fail!("singleton list"),
2461 Nil => fail!("empty list")
2465 The first pattern matches lists constructed by applying `Cons` to any head value, and a
2466 tail value of `@Nil`. The second pattern matches _any_ list constructed with `Cons`,
2467 ignoring the values of its arguments. The difference between `_` and `*` is that the pattern `C(_)` is only type-correct if
2468 `C` has exactly one argument, while the pattern `C(*)` is type-correct for any enum variant `C`, regardless of how many arguments `C` has.
2470 To execute an `match` expression, first the head expression is evaluated, then
2471 its value is sequentially compared to the patterns in the arms until a match
2472 is found. The first arm with a matching pattern is chosen as the branch target
2473 of the `match`, any variables bound by the pattern are assigned to local
2474 variables in the arm's block, and control enters the block.
2476 An example of an `match` expression:
2480 # fn process_pair(a: int, b: int) { }
2481 # fn process_ten() { }
2483 enum List<X> { Nil, Cons(X, @List<X>) }
2485 let x: List<int> = Cons(10, @Cons(11, @Nil));
2488 Cons(a, @Cons(b, _)) => {
2503 Patterns that bind variables
2504 default to binding to a copy or move of the matched value
2505 (depending on the matched value's type).
2506 This can be changed to bind to a borrowed pointer by
2507 using the ```ref``` keyword,
2508 or to a mutable borrowed pointer using ```ref mut```.
2510 A pattern that's just an identifier,
2511 like `Nil` in the previous answer,
2512 could either refer to an enum variant that's in scope,
2513 or bind a new variable.
2514 The compiler resolves this ambiguity by forbidding variable bindings that occur in ```match``` patterns from shadowing names of variants that are in scope.
2515 For example, wherever ```List``` is in scope,
2516 a ```match``` pattern would not be able to bind ```Nil``` as a new name.
2517 The compiler interprets a variable pattern `x` as a binding _only_ if there is no variant named `x` in scope.
2518 A convention you can use to avoid conflicts is simply to name variants with upper-case letters,
2519 and local variables with lower-case letters.
2521 Multiple match patterns may be joined with the `|` operator.
2522 A range of values may be specified with `..`.
2528 let message = match x {
2529 0 | 1 => "not many",
2535 Range patterns only work on scalar types
2536 (like integers and characters; not like vectors and structs, which have sub-components).
2537 A range pattern may not be a sub-range of another range pattern inside the same `match`.
2539 Finally, match patterns can accept *pattern guards* to further refine the
2540 criteria for matching a case. Pattern guards appear after the pattern and
2541 consist of a bool-typed expression following the `if` keyword. A pattern
2542 guard may refer to the variables bound within the pattern they follow.
2545 # let maybe_digit = Some(0);
2546 # fn process_digit(i: int) { }
2547 # fn process_other(i: int) { }
2549 let message = match maybe_digit {
2550 Some(x) if x < 10 => process_digit(x),
2551 Some(x) => process_other(x),
2556 ### Return expressions
2558 ~~~~~~~~{.ebnf .gram}
2559 return_expr : "return" expr ? ;
2562 Return expressions are denoted with the keyword `return`. Evaluating a `return`
2563 expression moves its argument into the output slot of the current
2564 function, destroys the current function activation frame, and transfers
2565 control to the caller frame.
2567 An example of a `return` expression:
2570 fn max(a: int, b: int) -> int {
2583 Every slot, item and value in a Rust program has a type. The _type_ of a *value*
2584 defines the interpretation of the memory holding it.
2586 Built-in types and type-constructors are tightly integrated into the language,
2587 in nontrivial ways that are not possible to emulate in user-defined
2588 types. User-defined types have limited capabilities.
2592 The primitive types are the following:
2594 * The "unit" type `()`, having the single "unit" value `()` (occasionally called "nil").
2595 ^[The "unit" value `()` is *not* a sentinel "null pointer" value for reference slots; the "unit" type is the implicit return type from functions otherwise lacking a return type, and can be used in other contexts (such as message-sending or type-parametric code) as a zero-size type.]
2596 * The boolean type `bool` with values `true` and `false`.
2597 * The machine types.
2598 * The machine-dependent integer and floating-point types.
2602 The machine types are the following:
2605 * The unsigned word types `u8`, `u16`, `u32` and `u64`, with values drawn from
2606 the integer intervals $[0, 2^8 - 1]$, $[0, 2^{16} - 1]$, $[0, 2^{32} - 1]$ and
2607 $[0, 2^{64} - 1]$ respectively.
2609 * The signed two's complement word types `i8`, `i16`, `i32` and `i64`, with
2610 values drawn from the integer intervals $[-(2^7), 2^7 - 1]$,
2611 $[-(2^{15}), 2^{15} - 1]$, $[-(2^{31}), 2^{31} - 1]$, $[-(2^{63}), 2^{63} - 1]$
2614 * The IEEE 754-2008 `binary32` and `binary64` floating-point types: `f32` and
2615 `f64`, respectively.
2617 #### Machine-dependent integer types
2619 The Rust type `uint`^[A Rust `uint` is analogous to a C99 `uintptr_t`.] is an
2620 unsigned integer type with target-machine-dependent size. Its size, in
2621 bits, is equal to the number of bits required to hold any memory address on
2624 The Rust type `int`^[A Rust `int` is analogous to a C99 `intptr_t`.] is a
2625 two's complement signed integer type with target-machine-dependent size. Its
2626 size, in bits, is equal to the size of the rust type `uint` on the same target
2630 #### Machine-dependent floating point type
2632 The Rust type `float` is a machine-specific type equal to one of the supported
2633 Rust floating-point machine types (`f32` or `f64`). It is the largest
2634 floating-point type that is directly supported by hardware on the target
2635 machine, or if the target machine has no floating-point hardware support, the
2636 largest floating-point type supported by the software floating-point library
2637 used to support the other floating-point machine types.
2639 Note that due to the preference for hardware-supported floating-point, the
2640 type `float` may not be equal to the largest *supported* floating-point type.
2645 The types `char` and `str` hold textual data.
2647 A value of type `char` is a Unicode character,
2648 represented as a 32-bit unsigned word holding a UCS-4 codepoint.
2650 A value of type `str` is a Unicode string,
2651 represented as a vector of 8-bit unsigned bytes holding a sequence of UTF-8 codepoints.
2652 Since `str` is of unknown size, it is not a _first class_ type,
2653 but can only be instantiated through a pointer type,
2654 such as `&str`, `@str` or `~str`.
2659 The tuple type-constructor forms a new heterogeneous product of values similar
2660 to the record type-constructor. The differences are as follows:
2662 * tuple elements cannot be mutable, unlike record fields
2663 * tuple elements are not named and can be accessed only by pattern-matching
2665 Tuple types and values are denoted by listing the types or values of their
2666 elements, respectively, in a parenthesized, comma-separated
2669 The members of a tuple are laid out in memory contiguously, like a record, in
2670 order specified by the tuple type.
2672 An example of a tuple type and its use:
2675 type Pair<'self> = (int,&'self str);
2676 let p: Pair<'static> = (10,"hello");
2678 assert!(b != "world");
2684 The vector type constructor represents a homogeneous array of values of a given type.
2685 A vector has a fixed size.
2686 (Operations like `vec.push` operate solely on owned vectors.)
2687 A vector type can be annotated with a _definite_ size,
2688 written with a trailing asterisk and integer literal, such as `[int * 10]`.
2689 Such a definite-sized vector type is a first-class type, since its size is known statically.
2690 A vector without such a size is said to be of _indefinite_ size,
2691 and is therefore not a _first-class_ type.
2692 An indefinite-size vector can only be instantiated through a pointer type,
2693 such as `&[T]`, `@[T]` or `~[T]`.
2694 The kind of a vector type depends on the kind of its element type,
2695 as with other simple structural types.
2697 Expressions producing vectors of definite size cannot be evaluated in a
2698 context expecting a vector of indefinite size; one must copy the
2699 definite-sized vector contents into a distinct vector of indefinite size.
2701 An example of a vector type and its use:
2704 let v: &[int] = &[7, 5, 3];
2709 All in-bounds elements of a vector are always initialized,
2710 and access to a vector is always bounds-checked.
2715 A `struct` *type* is a heterogeneous product of other types, called the *fields* of the type.
2716 ^[`struct` types are analogous `struct` types in C,
2717 the *record* types of the ML family,
2718 or the *structure* types of the Lisp family.]
2720 New instances of a `struct` can be constructed with a [struct expression](#struct-expressions).
2722 The memory order of fields in a `struct` is given by the item defining it.
2723 Fields may be given in any order in a corresponding struct *expression*;
2724 the resulting `struct` value will always be laid out in memory in the order specified by the corresponding *item*.
2726 The fields of a `struct` may be qualified by [visibility modifiers](#visibility-modifiers),
2727 to restrict access to implementation-private data in a structure.
2729 A _tuple struct_ type is just like a structure type, except that the fields are anonymous.
2731 A _unit-like struct_ type is like a structure type, except that it has no fields.
2732 The one value constructed by the associated [structure expression](#structure-expression) is the only value that inhabits such a type.
2734 ### Enumerated types
2736 An *enumerated type* is a nominal, heterogeneous disjoint union type,
2737 denoted by the name of an [`enum` item](#enumerations).
2738 ^[The `enum` type is analogous to a `data` constructor declaration in ML,
2739 or a *pick ADT* in Limbo.]
2741 An [`enum` item](#enumerations) declares both the type and a number of *variant constructors*,
2742 each of which is independently named and takes an optional tuple of arguments.
2744 New instances of an `enum` can be constructed by calling one of the variant constructors,
2745 in a [call expression](#call-expressions).
2747 Any `enum` value consumes as much memory as the largest variant constructor for its corresponding `enum` type.
2749 Enum types cannot be denoted *structurally* as types,
2750 but must be denoted by named reference to an [`enum` item](#enumerations).
2755 Nominal types -- [enumerations](#enumerated-types) and [structures](#structure-types) -- may be recursive.
2756 That is, each `enum` constructor or `struct` field may refer, directly or indirectly, to the enclosing `enum` or `struct` type itself.
2757 Such recursion has restrictions:
2759 * Recursive types must include a nominal type in the recursion
2760 (not mere [type definitions](#type-definitions),
2761 or other structural types such as [vectors](#vector-types) or [tuples](#tuple-types)).
2762 * A recursive `enum` item must have at least one non-recursive constructor
2763 (in order to give the recursion a basis case).
2764 * The size of a recursive type must be finite;
2765 in other words the recursive fields of the type must be [pointer types](#pointer-types).
2766 * Recursive type definitions can cross module boundaries, but not module *visibility* boundaries,
2767 or crate boundaries (in order to simplify the module system and type checker).
2769 An example of a *recursive* type and its use:
2777 let a: List<int> = Cons(7, @Cons(13, @Nil));
2783 All pointers in Rust are explicit first-class values.
2784 They can be copied, stored into data structures, and returned from functions.
2785 There are four varieties of pointer in Rust:
2787 Managed pointers (`@`)
2788 : These point to managed heap allocations (or "boxes") in the task-local, managed heap.
2789 Managed pointers are written `@content`,
2790 for example `@int` means a managed pointer to a managed box containing an integer.
2791 Copying a managed pointer is a "shallow" operation:
2792 it involves only copying the pointer itself
2793 (as well as any reference-count or GC-barriers required by the managed heap).
2794 Dropping a managed pointer does not necessarily release the box it points to;
2795 the lifecycles of managed boxes are subject to an unspecified garbage collection algorithm.
2797 Owning pointers (`~`)
2798 : These point to owned heap allocations (or "boxes") in the shared, inter-task heap.
2799 Each owned box has a single owning pointer; pointer and pointee retain a 1:1 relationship at all times.
2800 Owning pointers are written `~content`,
2801 for example `~int` means an owning pointer to an owned box containing an integer.
2802 Copying an owned box is a "deep" operation:
2803 it involves allocating a new owned box and copying the contents of the old box into the new box.
2804 Releasing an owning pointer immediately releases its corresponding owned box.
2806 Borrowed pointers (`&`)
2807 : These point to memory _owned by some other value_.
2808 Borrowed pointers arise by (automatic) conversion from owning pointers, managed pointers,
2809 or by applying the borrowing operator `&` to some other value,
2810 including [lvalues, rvalues or temporaries](#lvalues-rvalues-and-temporaries).
2811 Borrowed pointers are written `&content`, or in some cases `&f/content` for some lifetime-variable `f`,
2812 for example `&int` means a borrowed pointer to an integer.
2813 Copying a borrowed pointer is a "shallow" operation:
2814 it involves only copying the pointer itself.
2815 Releasing a borrowed pointer typically has no effect on the value it points to,
2816 with the exception of temporary values,
2817 which are released when the last borrowed pointer to them is released.
2820 : Raw pointers are pointers without safety or liveness guarantees.
2821 Raw pointers are written `*content`,
2822 for example `*int` means a raw pointer to an integer.
2823 Copying or dropping a raw pointer is has no effect on the lifecycle of any other value.
2824 Dereferencing a raw pointer or converting it to any other pointer type is an [`unsafe` operation](#unsafe-functions).
2825 Raw pointers are generally discouraged in Rust code;
2826 they exist to support interoperability with foreign code,
2827 and writing performance-critical or low-level functions.
2832 The function type constructor `fn` forms new function types.
2833 A function type consists of a possibly-empty set of function-type modifiers
2834 (such as `unsafe` or `extern`), a sequence of input types and an output type.
2836 An example of a `fn` type:
2839 fn add(x: int, y: int) -> int {
2843 let mut x = add(5,7);
2845 type Binop<'self> = &'self fn(int,int) -> int;
2846 let bo: Binop = add;
2852 Every trait item (see [traits](#traits)) defines a type with the same name as the trait.
2853 This type is called the _object type_ of the trait.
2854 Object types permit "late binding" of methods, dispatched using _virtual method tables_ ("vtables").
2855 Whereas most calls to trait methods are "early bound" (statically resolved) to specific implementations at compile time,
2856 a call to a method on an object type is only resolved to a vtable entry at compile time.
2857 The actual implementation for each vtable entry can vary on an object-by-object basis.
2859 Given a pointer-typed expression `E` of type `&T`, `~T` or `@T`, where `T` implements trait `R`,
2860 casting `E` to the corresponding pointer type `&R`, `~R` or `@R` results in a value of the _object type_ `R`.
2861 This result is represented as a pair of pointers:
2862 the vtable pointer for the `T` implementation of `R`, and the pointer value of `E`.
2864 An example of an object type:
2868 fn to_string(&self) -> ~str;
2871 impl Printable for int {
2872 fn to_string(&self) -> ~str { self.to_str() }
2875 fn print(a: @Printable) {
2876 println(a.to_string());
2880 print(@10 as @Printable);
2884 In this example, the trait `Printable` occurs as an object type in both the type signature of `print`,
2885 and the cast expression in `main`.
2889 Within the body of an item that has type parameter declarations, the names of its type parameters are types:
2892 fn map<A: Clone, B: Clone>(f: &fn(A) -> B, xs: &[A]) -> ~[B] {
2896 let first: B = f(xs[0].clone());
2897 let rest: ~[B] = map(f, xs.slice(1, xs.len()));
2898 return ~[first] + rest;
2902 Here, `first` has type `B`, referring to `map`'s `B` type parameter;
2903 and `rest` has type `~[B]`, a vector type with element type `B`.
2907 The special type `self` has a meaning within methods inside an
2908 impl item. It refers to the type of the implicit `self` argument. For
2913 fn make_string(&self) -> ~str;
2916 impl Printable for ~str {
2917 fn make_string(&self) -> ~str {
2923 `self` refers to the value of type `~str` that is the receiver for a
2924 call to the method `make_string`.
2928 Types in Rust are categorized into kinds, based on various properties of the components of the type.
2932 : Types of this kind are deeply immutable;
2933 they contain no mutable memory locations
2934 directly or indirectly via pointers.
2936 : Types of this kind can be safely sent between tasks.
2937 This kind includes scalars, owning pointers, owned closures, and
2938 structural types containing only other owned types.
2939 All `Send` types are `'static`.
2941 : Types of this kind do not contain any borrowed pointers;
2942 this can be a useful guarantee for code
2943 that breaks borrowing assumptions
2944 using [`unsafe` operations](#unsafe-functions).
2946 : This is not strictly a kind,
2947 but its presence interacts with kinds:
2948 the `Drop` trait provides a single method `drop`
2949 that takes no parameters,
2950 and is run when values of the type are dropped.
2951 Such a method is called a "destructor",
2952 and are always executed in "top-down" order:
2953 a value is completely destroyed
2954 before any of the values it owns run their destructors.
2955 Only `Send` types can implement `Drop`.
2958 : Types with destructors, closure environments,
2959 and various other _non-first-class_ types,
2960 are not copyable at all.
2961 Such types can usually only be accessed through pointers,
2962 or in some cases, moved between mutable locations.
2964 Kinds can be supplied as _bounds_ on type parameters, like traits,
2965 in which case the parameter is constrained to types satisfying that kind.
2967 By default, type parameters do not carry any assumed kind-bounds at all.
2968 When instantiating a type parameter,
2969 the kind bounds on the parameter are checked
2970 to be the same or narrower than the kind
2971 of the type that it is instantiated with.
2973 Sending operations are not part of the Rust language,
2974 but are implemented in the library.
2975 Generic functions that send values
2976 bound the kind of these values to sendable.
2978 # Memory and concurrency models
2980 Rust has a memory model centered around concurrently-executing _tasks_. Thus
2981 its memory model and its concurrency model are best discussed simultaneously,
2982 as parts of each only make sense when considered from the perspective of the
2985 When reading about the memory model, keep in mind that it is partitioned in
2986 order to support tasks; and when reading about tasks, keep in mind that their
2987 isolation and communication mechanisms are only possible due to the ownership
2988 and lifetime semantics of the memory model.
2992 A Rust program's memory consists of a static set of *items*, a set of
2993 [tasks](#tasks) each with its own *stack*, and a *heap*. Immutable portions of
2994 the heap may be shared between tasks, mutable portions may not.
2996 Allocations in the stack consist of *slots*, and allocations in the heap
3000 ### Memory allocation and lifetime
3002 The _items_ of a program are those functions, modules and types
3003 that have their value calculated at compile-time and stored uniquely in the
3004 memory image of the rust process. Items are neither dynamically allocated nor
3007 A task's _stack_ consists of activation frames automatically allocated on
3008 entry to each function as the task executes. A stack allocation is reclaimed
3009 when control leaves the frame containing it.
3011 The _heap_ is a general term that describes two separate sets of boxes:
3012 managed boxes -- which may be subject to garbage collection -- and owned
3013 boxes. The lifetime of an allocation in the heap depends on the lifetime of
3014 the box values pointing to it. Since box values may themselves be passed in
3015 and out of frames, or stored in the heap, heap allocations may outlive the
3016 frame they are allocated within.
3018 ### Memory ownership
3020 A task owns all memory it can *safely* reach through local variables,
3021 as well as managed, owning and borrowed pointers.
3023 When a task sends a value that has the `Send` trait to another task,
3024 it loses ownership of the value sent and can no longer refer to it.
3025 This is statically guaranteed by the combined use of "move semantics",
3026 and the compiler-checked _meaning_ of the `Send` trait:
3027 it is only instantiated for (transitively) sendable kinds of data constructor and pointers,
3028 never including managed or borrowed pointers.
3030 When a stack frame is exited, its local allocations are all released, and its
3031 references to boxes (both managed and owned) are dropped.
3033 A managed box may (in the case of a recursive, mutable managed type) be cyclic;
3034 in this case the release of memory inside the managed structure may be deferred
3035 until task-local garbage collection can reclaim it. Code can ensure no such
3036 delayed deallocation occurs by restricting itself to owned boxes and similar
3037 unmanaged kinds of data.
3039 When a task finishes, its stack is necessarily empty and it therefore has no
3040 references to any boxes; the remainder of its heap is immediately freed.
3045 A task's stack contains slots.
3047 A _slot_ is a component of a stack frame, either a function parameter,
3048 a [temporary](#lvalues-rvalues-and-temporaries), or a local variable.
3050 A _local variable_ (or *stack-local* allocation) holds a value directly,
3051 allocated within the stack's memory. The value is a part of the stack frame.
3053 Local variables are immutable unless declared with `let mut`. The
3054 `mut` keyword applies to all local variables declared within that
3055 declaration (so `let mut (x, y) = ...` declares two mutable variables, `x` and
3058 Function parameters are immutable unless declared with `mut`. The
3059 `mut` keyword applies only to the following parameter (so `|mut x, y|`
3060 and `fn f(mut x: ~int, y: ~int)` declare one mutable variable `x` and
3061 one immutable variable `y`).
3063 Local variables are not initialized when allocated; the entire frame worth of
3064 local variables are allocated at once, on frame-entry, in an uninitialized
3065 state. Subsequent statements within a function may or may not initialize the
3066 local variables. Local variables can be used only after they have been
3067 initialized; this is enforced by the compiler.
3072 A _box_ is a reference to a heap allocation holding another value. There
3073 are two kinds of boxes: *managed boxes* and *owned boxes*.
3075 A _managed box_ type or value is constructed by the prefix *at* sigil `@`.
3077 An _owned box_ type or value is constructed by the prefix *tilde* sigil `~`.
3079 Multiple managed box values can point to the same heap allocation; copying a
3080 managed box value makes a shallow copy of the pointer (optionally incrementing
3081 a reference count, if the managed box is implemented through
3082 reference-counting).
3084 Owned box values exist in 1:1 correspondence with their heap allocation.
3086 An example of constructing one managed box type and value, and one owned box
3094 Some operations (such as field selection) implicitly dereference boxes. An
3095 example of an _implicit dereference_ operation performed on box values:
3098 struct Foo { y: int }
3099 let x = @Foo{y: 10};
3103 Other operations act on box values as single-word-sized address values. For
3104 these operations, to access the value held in the box requires an explicit
3105 dereference of the box value. Explicitly dereferencing a box is indicated with
3106 the unary *star* operator `*`. Examples of such _explicit dereference_
3109 * copying box values (`x = y`)
3110 * passing box values to functions (`f(x,y)`)
3113 An example of an explicit-dereference operation performed on box values:
3116 fn takes_boxed(b: @int) {
3119 fn takes_unboxed(b: int) {
3131 An executing Rust program consists of a tree of tasks.
3132 A Rust _task_ consists of an entry function, a stack,
3133 a set of outgoing communication channels and incoming communication ports,
3134 and ownership of some portion of the heap of a single operating-system process.
3135 (We expect that many programs will not use channels and ports directly,
3136 but will instead use higher-level abstractions provided in standard libraries,
3139 Multiple Rust tasks may coexist in a single operating-system process.
3140 The runtime scheduler maps tasks to a certain number of operating-system threads.
3141 By default, the scheduler chooses the number of threads based on
3142 the number of concurrent physical CPUs detected at startup.
3143 It's also possible to override this choice at runtime.
3144 When the number of tasks exceeds the number of threads -- which is likely --
3145 the scheduler multiplexes the tasks onto threads.^[
3146 This is an M:N scheduler,
3147 which is known to give suboptimal results for CPU-bound concurrency problems.
3148 In such cases, running with the same number of threads and tasks can yield better results.
3149 Rust has M:N scheduling in order to support very large numbers of tasks
3150 in contexts where threads are too resource-intensive to use in large number.
3151 The cost of threads varies substantially per operating system, and is sometimes quite low,
3152 so this flexibility is not always worth exploiting.]
3155 ### Communication between tasks
3157 Rust tasks are isolated and generally unable to interfere with one another's memory directly,
3158 except through [`unsafe` code](#unsafe-functions).
3159 All contact between tasks is mediated by safe forms of ownership transfer,
3160 and data races on memory are prohibited by the type system.
3162 Inter-task communication and co-ordination facilities are provided in the standard library.
3165 - synchronous and asynchronous communication channels with various communication topologies
3166 - read-only and read-write shared variables with various safe mutual exclusion patterns
3167 - simple locks and semaphores
3169 When such facilities carry values, the values are restricted to the [`Send` type-kind](#type-kinds).
3170 Restricting communication interfaces to this kind ensures that no borrowed or managed pointers move between tasks.
3171 Thus access to an entire data structure can be mediated through its owning "root" value;
3172 no further locking or copying is required to avoid data races within the substructure of such a value.
3177 The _lifecycle_ of a task consists of a finite set of states and events
3178 that cause transitions between the states. The lifecycle states of a task are:
3185 A task begins its lifecycle -- once it has been spawned -- in the *running*
3186 state. In this state it executes the statements of its entry function, and any
3187 functions called by the entry function.
3189 A task may transition from the *running* state to the *blocked*
3190 state any time it makes a blocking communication call. When the
3191 call can be completed -- when a message arrives at a sender, or a
3192 buffer opens to receive a message -- then the blocked task will
3193 unblock and transition back to *running*.
3195 A task may transition to the *failing* state at any time, due being
3196 killed by some external event or internally, from the evaluation of a
3197 `fail!()` macro. Once *failing*, a task unwinds its stack and
3198 transitions to the *dead* state. Unwinding the stack of a task is done by
3199 the task itself, on its own control stack. If a value with a destructor is
3200 freed during unwinding, the code for the destructor is run, also on the task's
3201 control stack. Running the destructor code causes a temporary transition to a
3202 *running* state, and allows the destructor code to cause any subsequent
3203 state transitions. The original task of unwinding and failing thereby may
3204 suspend temporarily, and may involve (recursive) unwinding of the stack of a
3205 failed destructor. Nonetheless, the outermost unwinding activity will continue
3206 until the stack is unwound and the task transitions to the *dead*
3207 state. There is no way to "recover" from task failure. Once a task has
3208 temporarily suspended its unwinding in the *failing* state, failure
3209 occurring from within this destructor results in *hard* failure. The
3210 unwinding procedure of hard failure frees resources but does not execute
3211 destructors. The original (soft) failure is still resumed at the point where
3212 it was temporarily suspended.
3214 A task in the *dead* state cannot transition to other states; it exists
3215 only to have its termination status inspected by other tasks, and/or to await
3216 reclamation when the last reference to it drops.
3221 The currently scheduled task is given a finite *time slice* in which to
3222 execute, after which it is *descheduled* at a loop-edge or similar
3223 preemption point, and another task within is scheduled, pseudo-randomly.
3225 An executing task can yield control at any time, by making a library call to
3226 `std::task::yield`, which deschedules it immediately. Entering any other
3227 non-executing state (blocked, dead) similarly deschedules the task.
3230 # Runtime services, linkage and debugging
3233 The Rust _runtime_ is a relatively compact collection of C++ and Rust code
3234 that provides fundamental services and datatypes to all Rust tasks at
3235 run-time. It is smaller and simpler than many modern language runtimes. It is
3236 tightly integrated into the language's execution model of memory, tasks,
3237 communication and logging.
3239 > **Note:** The runtime library will merge with the `std` library in future versions of Rust.
3241 ### Memory allocation
3243 The runtime memory-management system is based on a _service-provider interface_,
3244 through which the runtime requests blocks of memory from its environment
3245 and releases them back to its environment when they are no longer needed.
3246 The default implementation of the service-provider interface
3247 consists of the C runtime functions `malloc` and `free`.
3249 The runtime memory-management system, in turn, supplies Rust tasks
3250 with facilities for allocating, extending and releasing stacks,
3251 as well as allocating and freeing heap data.
3255 The runtime provides C and Rust code to assist with various built-in types,
3256 such as vectors, strings, and the low level communication system (ports,
3259 Support for other built-in types such as simple types, tuples, records, and
3260 enums is open-coded by the Rust compiler.
3264 ### Task scheduling and communication
3266 The runtime provides code to manage inter-task communication. This includes
3267 the system of task-lifecycle state transitions depending on the contents of
3268 queues, as well as code to copy values between queues and their recipients and
3269 to serialize values for transmission over operating-system inter-process
3270 communication facilities.
3275 The runtime contains a system for directing [logging
3276 expressions](#log-expressions) to a logging console and/or internal logging
3277 buffers. Logging can be enabled per module.
3279 Logging output is enabled by setting the `RUST_LOG` environment
3280 variable. `RUST_LOG` accepts a logging specification made up of a
3281 comma-separated list of paths, with optional log levels. For each
3282 module containing log expressions, if `RUST_LOG` contains the path to
3283 that module or a parent of that module, then logs of the appropriate
3284 level will be output to the console.
3286 The path to a module consists of the crate name, any parent modules,
3287 then the module itself, all separated by double colons (`::`). The
3288 optional log level can be appended to the module path with an equals
3289 sign (`=`) followed by the log level, from 1 to 4, inclusive. Level 1
3290 is the error level, 2 is warning, 3 info, and 4 debug. Any logs
3291 less than or equal to the specified level will be output. If not
3292 specified then log level 4 is assumed.
3294 As an example, to see all the logs generated by the compiler, you would set
3295 `RUST_LOG` to `rustc`, which is the crate name (as specified in its `link`
3296 [attribute](#attributes)). To narrow down the logs to just crate resolution,
3297 you would set it to `rustc::metadata::creader`. To see just error logging
3300 Note that when compiling source files that don't specify a
3301 crate name the crate is given a default name that matches the source file,
3302 with the extension removed. In that case, to turn on logging for a program
3303 compiled from, e.g. `helloworld.rs`, `RUST_LOG` should be set to `helloworld`.
3305 As a convenience, the logging spec can also be set to a special pseudo-crate,
3306 `::help`. In this case, when the application starts, the runtime will
3307 simply output a list of loaded modules containing log expressions, then exit.
3309 The Rust runtime itself generates logging information. The runtime's logs are
3310 generated for a number of artificial modules in the `::rt` pseudo-crate,
3311 and can be enabled just like the logs for any standard module. The full list
3312 of runtime logging modules follows.
3314 * `::rt::mem` Memory management
3315 * `::rt::comm` Messaging and task communication
3316 * `::rt::task` Task management
3317 * `::rt::dom` Task scheduling
3318 * `::rt::trace` Unused
3319 * `::rt::cache` Type descriptor cache
3320 * `::rt::upcall` Compiler-generated runtime calls
3321 * `::rt::timer` The scheduler timer
3322 * `::rt::gc` Garbage collection
3323 * `::rt::stdlib` Functions used directly by the standard library
3324 * `::rt::kern` The runtime kernel
3325 * `::rt::backtrace` Log a backtrace on task failure
3326 * `::rt::callback` Unused
3328 #### Logging Expressions
3330 Rust provides several macros to log information. Here's a simple Rust program
3331 that demonstrates all four of them:
3335 error!("This is an error log")
3336 warn!("This is a warn log")
3337 info!("this is an info log")
3338 debug!("This is a debug log")
3342 These four log levels correspond to levels 1-4, as controlled by `RUST_LOG`:
3345 $ RUST_LOG=rust=3 ./rust
3346 rust: ~"\"This is an error log\""
3347 rust: ~"\"This is a warn log\""
3348 rust: ~"\"this is an info log\""
3351 # Appendix: Rationales and design tradeoffs
3355 # Appendix: Influences and further references
3360 > The essential problem that must be solved in making a fault-tolerant
3361 > software system is therefore that of fault-isolation. Different programmers
3362 > will write different modules, some modules will be correct, others will have
3363 > errors. We do not want the errors in one module to adversely affect the
3364 > behaviour of a module which does not have any errors.
3366 > — Joe Armstrong
3369 > In our approach, all data is private to some process, and processes can
3370 > only communicate through communications channels. *Security*, as used
3371 > in this paper, is the property which guarantees that processes in a system
3372 > cannot affect each other except by explicit communication.
3374 > When security is absent, nothing which can be proven about a single module
3375 > in isolation can be guaranteed to hold when that module is embedded in a
3378 > — Robert Strom and Shaula Yemini
3381 > Concurrent and applicative programming complement each other. The
3382 > ability to send messages on channels provides I/O without side effects,
3383 > while the avoidance of shared data helps keep concurrent processes from
3389 Rust is not a particularly original language. It may however appear unusual
3390 by contemporary standards, as its design elements are drawn from a number of
3391 "historical" languages that have, with a few exceptions, fallen out of
3392 favour. Five prominent lineages contribute the most, though their influences
3393 have come and gone during the course of Rust's development:
3395 * The NIL (1981) and Hermes (1990) family. These languages were developed by
3396 Robert Strom, Shaula Yemini, David Bacon and others in their group at IBM
3397 Watson Research Center (Yorktown Heights, NY, USA).
3399 * The Erlang (1987) language, developed by Joe Armstrong, Robert Virding, Claes
3400 Wikström, Mike Williams and others in their group at the Ericsson Computer
3401 Science Laboratory (Älvsjö, Stockholm, Sweden) .
3403 * The Sather (1990) language, developed by Stephen Omohundro, Chu-Cheow Lim,
3404 Heinz Schmidt and others in their group at The International Computer
3405 Science Institute of the University of California, Berkeley (Berkeley, CA,
3408 * The Newsqueak (1988), Alef (1995), and Limbo (1996) family. These
3409 languages were developed by Rob Pike, Phil Winterbottom, Sean Dorward and
3410 others in their group at Bell Labs Computing Sciences Research Center
3411 (Murray Hill, NJ, USA).
3413 * The Napier (1985) and Napier88 (1988) family. These languages were
3414 developed by Malcolm Atkinson, Ron Morrison and others in their group at
3415 the University of St. Andrews (St. Andrews, Fife, UK).
3417 Additional specific influences can be seen from the following languages:
3419 * The stack-growth implementation of Go.
3420 * The structural algebraic types and compilation manager of SML.
3421 * The attribute and assembly systems of C#.
3422 * The references and deterministic destructor system of C++.
3423 * The memory region systems of the ML Kit and Cyclone.
3424 * The typeclass system of Haskell.
3425 * The lexical identifier rule of Python.
3426 * The block syntax of Ruby.