# Notation
-Rust's grammar is defined over Unicode codepoints, each conventionally denoted
+Rust's grammar is defined over Unicode code points, each conventionally denoted
`U+XXXX`, for 4 or more hexadecimal digits `X`. _Most_ of Rust's grammar is
confined to the ASCII range of Unicode, and is described in this document by a
dialect of Extended Backus-Naur Form (EBNF), specifically a dialect of EBNF
- Square brackets are used to group rules.
- `LITERAL` is a single printable ASCII character, or an escaped hexadecimal
ASCII code of the form `\xQQ`, in single quotes, denoting the corresponding
- Unicode codepoint `U+00QQ`.
+ Unicode code point `U+00QQ`.
- `IDENTIFIER` is a nonempty string of ASCII letters and underscores.
- The `repeat` forms apply to the adjacent `element`, and are as follows:
- `?` means zero or one repetition
## Unicode productions
-A few productions in Rust's grammar permit Unicode codepoints outside the ASCII
+A few productions in Rust's grammar permit Unicode code points outside the ASCII
range. We define these productions in terms of character properties specified
-in the Unicode standard, rather than in terms of ASCII-range codepoints. The
+in the Unicode standard, rather than in terms of ASCII-range code points. The
section [Special Unicode Productions](#special-unicode-productions) lists these
productions.
## Input format
-Rust input is interpreted as a sequence of Unicode codepoints encoded in UTF-8.
+Rust input is interpreted as a sequence of Unicode code points encoded in UTF-8.
Most Rust grammar rules are defined in terms of printable ASCII-range
-codepoints, but a small number are defined in terms of Unicode properties or
-explicit codepoint lists. [^inputformat]
+code points, but a small number are defined in terms of Unicode properties or
+explicit code point lists. [^inputformat]
[^inputformat]: Substitute definitions for the special Unicode productions are
provided to the grammar verifier, restricted to ASCII range, when verifying the
sequence (`/**`), are interpreted as a special syntax for `doc`
[attributes](#attributes). That is, they are equivalent to writing
`#[doc="..."]` around the body of the comment (this includes the comment
-characters themselves, ie `/// Foo` turns into `#[doc="/// Foo"]`).
+characters themselves, i.e. `/// Foo` turns into `#[doc="/// Foo"]`).
-`//!` comments apply to the parent of the comment, rather than the item that
-follows. `//!` comments are usually used to display information on the crate
-index page.
+Line comments beginning with `//!` and block comments beginning with `/*!` are
+doc comments that apply to the parent of the comment, rather than the item
+that follows. That is, they are equivalent to writing `#![doc="..."]` around
+the body of the comment. `//!` comments are usually used to display
+information on the crate index page.
Non-doc comments are interpreted as a form of whitespace.
| fn | for | if | impl | in |
| let | loop | macro | match | mod |
| move | mut | offsetof | override | priv |
-| pub | pure | ref | return | sizeof |
-| static | self | struct | super | true |
-| trait | type | typeof | unsafe | unsized |
-| use | virtual | where | while | yield |
+| proc | pub | pure | ref | return |
+| Self | self | sizeof | static | struct |
+| super | trait | true | type | typeof |
+| unsafe | unsized | use | virtual | where |
+| while | yield | | | |
Each of these keywords has special meaning in its grammar, and all of them are
##### Suffixes
| Integer | Floating-point |
|---------|----------------|
-| `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `is` (`isize`), `us` (`usize`) | `f32`, `f64` |
+| `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `isize`, `usize` | `f32`, `f64` |
#### Character and string literals
literals. An escape starts with a `U+005C` (`\`) and continues with one of the
following forms:
-* An _8-bit codepoint escape_ escape starts with `U+0078` (`x`) and is
- followed by exactly two _hex digits_. It denotes the Unicode codepoint
+* An _8-bit code point escape_ starts with `U+0078` (`x`) and is
+ followed by exactly two _hex digits_. It denotes the Unicode code point
equal to the provided hex value.
-* A _24-bit codepoint escape_ starts with `U+0075` (`u`) and is followed
+* A _24-bit code point escape_ starts with `U+0075` (`u`) and is followed
by up to six _hex digits_ surrounded by braces `U+007B` (`{`) and `U+007D`
- (`}`). It denotes the Unicode codepoint equal to the provided hex value.
+ (`}`). It denotes the Unicode code point equal to the provided hex value.
* A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
- (`r`), or `U+0074` (`t`), denoting the unicode values `U+000A` (LF),
+ (`r`), or `U+0074` (`t`), denoting the Unicode values `U+000A` (LF),
`U+000D` (CR) or `U+0009` (HT) respectively.
* The _backslash escape_ is the character `U+005C` (`\`) which must be
escaped in order to denote *itself*.
literals. An escape starts with a `U+005C` (`\`) and continues with one of the
following forms:
-* An _byte escape_ escape starts with `U+0078` (`x`) and is
+* A _byte escape_ escape starts with `U+0078` (`x`) and is
followed by exactly two _hex digits_. It denotes the byte
equal to the provided hex value.
* A _whitespace escape_ is one of the characters `U+006E` (`n`), `U+0072`
A _path_ is a sequence of one or more path components _logically_ separated by
a namespace qualifier (`::`). If a path consists of only one component, it may
-refer to either an [item](#items) or a [slot](#memory-slots) in a local control
+refer to either an [item](#items) or a [variable](#variables) in a local control
scope. If a path has multiple components, it refers to an item.
Every item has a _canonical path_ within its crate, but the path naming an item
only the name of a matched nonterminal comes after the dollar sign.
In both the matcher and transcriber, the Kleene star-like operator indicates
-repetition. The Kleene star operator consists of `$` and parens, optionally
+repetition. The Kleene star operator consists of `$` and parentheses, optionally
followed by a separator token, followed by `*` or `+`. `*` means zero or more
-repetitions, `+` means at least one repetition. The parens are not matched or
+repetitions, `+` means at least one repetition. The parentheses are not matched or
transcribed. On the matcher side, a name is bound to _all_ of the names it
matches, in a structure that mimics the structure of the repetition encountered
on a successful match. The job of the transcriber is to sort that structure
# Crates and source files
-Rust is a *compiled* language. Its semantics obey a *phase distinction* between
-compile-time and run-time. Those semantic rules that have a *static
+Although Rust, like any other language, can be implemented by an interpreter as
+well as a compiler, the only existing implementation is a compiler —
+from now on referred to as *the* Rust compiler — and the language has
+always been designed to be compiled. For these reasons, this section assumes a
+compiler.
+
+Rust's semantics obey a *phase distinction* between compile-time and
+run-time.[^phase-distinction] Those semantic rules that have a *static
interpretation* govern the success or failure of compilation. Those semantics
that have a *dynamic interpretation* govern the behavior of the program at
run-time.
+[^phase-distinction]: This distinction would also exist in an interpreter.
+ Static checks like syntactic analysis, type checking, and lints should
+ happen before the program is executed regardless of when it is executed.
+
The compilation model centers on artifacts called _crates_. 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.[^cratesourcefile]
+crate in binary form: either an executable or some sort of
+library.[^cratesourcefile]
[^cratesourcefile]: A crate is somewhat analogous to an *assembly* in the
ECMA-335 CLI model, a *library* in the SML/NJ Compilation Manager, a *unit*
A Rust source file describes a module, the name and location of which —
in the module tree of the current crate — are defined from outside the
source file: either by an explicit `mod_item` in a referencing source file, or
-by the name of the crate itself.
+by the name of the crate itself. Every source file is a module, but not every
+module needs its own source file: [module definitions](#modules) can be nested
+within one file.
Each source file contains a sequence of zero or more `item` definitions, and
-may optionally begin with any number of `attributes` that apply to the
-containing module. Attributes on the anonymous crate module define important
-metadata that influences the behavior of the compiler.
+may optionally begin with any number of [attributes](#Items and attributes)
+that apply to the containing module, most of which influence the behavior of
+the compiler. The anonymous crate module can have additional attributes that
+apply to the crate as a whole.
```no_run
-// Crate name
+// Specify the crate name.
#![crate_name = "projx"]
-// Specify the output type
+// Specify the type of output artifact.
#![crate_type = "lib"]
-// Turn on a warning
+// Turn on a warning.
+// This can be done in any module, not just the anonymous crate module.
#![warn(non_camel_case_types)]
```
An example of `use` declarations:
-```
-# #![feature(core)]
+```rust
use std::option::Option::{Some, None};
use std::collections::hash_map::{self, HashMap};
An example of what will and will not work for `use` items:
```
-# #![feature(core)]
# #![allow(unused_imports)]
-use foo::core::iter; // good: foo is at the root of the crate
use foo::baz::foobaz; // good: foo is at the root of the crate
mod foo {
- extern crate core;
- use foo::core::iter; // good: foo is at crate root
-// use core::iter; // bad: core is not at the crate root
+ mod example {
+ pub mod iter {}
+ }
+
+ use foo::example::iter; // good: foo is at crate root
+// use example::iter; // bad: core is not at the crate root
use self::baz::foobaz; // good: self refers to module 'foo'
use foo::bar::foobar; // good: foo is at crate root
A _function item_ defines a sequence of [statements](#statements) and an
optional final [expression](#expressions), along with a name and a set of
parameters. Functions are declared with the keyword `fn`. 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.
+set of *input* [*variables*](#variables) as parameters, through which the caller
+passes arguments into the function, and the *output* [*type*](#types)
+of the value the function will return to its caller on completion.
A function may also be copied into a first-class *value*, in which case the
value has the corresponding [*function type*](#function-types), and can be used
angle-bracket-enclosed, comma-separated list following the function name.
```{.ignore}
-fn iter<T>(seq: &[T], f: |T|) {
- for elt in seq.iter() { f(elt); }
+fn iter<T, F>(seq: &[T], f: F) where T: Copy, F: Fn(T) {
+ for elt in seq { f(*elt); }
}
-fn map<T, U>(seq: &[T], f: |T| -> U) -> Vec<U> {
+fn map<T, U, F>(seq: &[T], f: F) -> Vec<U> where T: Copy, U: Copy, F: Fn(T) -> U {
let mut acc = vec![];
- for elt in seq.iter() { acc.push(f(elt)); }
+ for elt in seq { acc.push(f(*elt)); }
acc
}
```
Inside the function signature and body, the name of the type parameter can be
-used as a type name.
+used as a type name. [Trait](#traits) bounds can be specified for type parameters
+to allow methods with that trait to be called on values of that type. This is
+specified using the `where` syntax, as in the above example.
When a generic function is referenced, its type is instantiated based on the
context of the reference. For example, calling the `iter` function defined
above on `[1, 2]` will instantiate type parameter `T` with `i32`, and require
-the closure parameter to have type `fn(i32)`.
+the closure parameter to have type `Fn(i32)`.
The type parameters can also be explicitly supplied in a trailing
[path](#paths) component after the function name. This might be necessary if
there is not sufficient context to determine the type parameters. For example,
`mem::size_of::<u32>() == 4`.
-Since a parameter type is opaque to the generic function, the set of operations
-that can be performed on it is limited. Values of parameter type can only be
-moved, not copied.
-
-```
-fn id<T>(x: T) -> T { x }
-```
-
-Similarly, [trait](#traits) bounds can be specified for type parameters to
-allow methods with that trait to be called on values of that type.
-
#### Unsafety
Unsafe operations are those that potentially violate the memory-safety
[noalias]: http://llvm.org/docs/LangRef.html#noalias
-##### Behaviour not considered unsafe
+##### Behavior not considered unsafe
-This is a list of behaviour not considered *unsafe* in Rust terms, but that may
+This is a list of behavior not considered *unsafe* in Rust terms, but that may
be undesired.
* Deadlocks
#### Diverging functions
A special kind of function can be declared with a `!` character where the
-output slot type would normally be. For example:
+output type would normally be. For example:
```
fn my_err(s: &str) -> ! {
several different type constraints.
For example, the following defines the type `Point` as a synonym for the type
-`(u8, u8)`, the type of pairs of unsigned 8 bit integers.:
+`(u8, u8)`, the type of pairs of unsigned 8 bit integers:
```
type Point = (u8, u8);
Enumeration constructors can have either named or unnamed fields:
-```
-# #![feature(struct_variant)]
-# fn main() {
+```rust
enum Animal {
Dog (String, f64),
Cat { name: String, weight: f64 }
let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
-# }
```
In this example, `Cat` is a _struct-like enum variant_,
}
```
-Traits also define an [object type](#object-types) with the same name as the
+Traits also define an [trait object](#trait-objects) with the same name as the
trait. Values of this type are created by [casting](#type-cast-expressions)
pointer values (pointing to a type for which an implementation of the given
trait is in scope) to pointers to the trait name, used as a type.
functions, with the exception that they may not have a body and are instead
terminated by a semicolon.
-```
-# #![feature(libc)]
-extern crate libc;
-use libc::{c_char, FILE};
-
-extern {
- fn fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE;
-}
-# fn main() {}
-```
-
Functions within external blocks may be called by Rust code, just like
functions defined in Rust. The Rust compiler automatically translates between
the Rust ABI and the foreign ABI.
standard C "cdecl" ABI. Other ABIs may be specified using an `abi` string, as
shown here:
-```{.ignore}
+```ignore
// Interface to the Windows API
extern "stdcall" { }
```
### Crate-only attributes
-- `crate_name` - specify the this crate's crate name.
+- `crate_name` - specify the crate's crate name.
- `crate_type` - see [linkage](#linkage).
- `feature` - see [compiler features](#compiler-features).
- `no_builtins` - disable optimizing certain code patterns to invocations of
`"unix"` or `"windows"`. The value of this configuration option is defined
as a configuration itself, like `unix` or `windows`.
* `target_os = "..."`. Operating system of the target, examples include
- `"win32"`, `"macos"`, `"linux"`, `"android"`, `"freebsd"`, `"dragonfly"`,
+ `"windows"`, `"macos"`, `"ios"`, `"linux"`, `"android"`, `"freebsd"`, `"dragonfly"`,
`"bitrig"` or `"openbsd"`.
* `target_pointer_width = "..."`. Target pointer width in bits. This is set
to `"32"` for targets with 32-bit pointers, and likewise set to `"64"` for
terms of encapsulation).
If a feature is promoted to a language feature, then all existing programs will
-start to receive compilation warnings about #[feature] directives which enabled
+start to receive compilation warnings about `#![feature]` directives which enabled
the new feature (because the directive is no longer necessary). However, if a
feature is decided to be removed from the language, errors will be issued (if
there isn't a parser error first). The directive in this case is no longer
### Declaration statements
A _declaration statement_ is one that introduces one or more *names* into the
-enclosing statement block. The declared names may denote new slots or new
+enclosing statement block. The declared names may denote new variables or new
items.
#### Item declarations
> **Note**: there is no implicit capture of the function's dynamic environment when
> declaring a function-local item.
-#### Slot declarations
+#### Variable declarations
```{.ebnf .gram}
let_decl : "let" pat [':' type ] ? [ init ] ? ';' ;
init : [ '=' ] expr ;
```
-A _slot declaration_ introduces a new set of slots, given by a pattern. The
+A _variable declaration_ introduces a new set of variable, given by a pattern. The
pattern may be followed by a type annotation, and/or an initializer expression.
When no type annotation is given, the compiler will infer the type, or signal
an error if insufficient type information is available for definite inference.
-Any slots introduced by a slot declaration are visible from the point of
+Any variables introduced by a variable declaration are visible from the point of
declaration until the end of the enclosing block scope.
### Expression statements
#### Moved and copied types
-When a [local variable](#memory-slots) is used as an
+When a [local variable](#variables) is used as an
[rvalue](#lvalues,-rvalues-and-temporaries) the variable will either be moved
or copied, depending on its type. All values whose type implements `Copy` are
copied, all others are moved.
identifier, and a parenthesized expression-list. Method calls are resolved to
methods on specific traits, either statically dispatching to a method if the
exact `self`-type of the left-hand-side is known, or dynamically dispatching if
-the left-hand-side expression is an indirect [object type](#object-types).
+the left-hand-side expression is an indirect [trait object](#trait-objects).
### Field expressions
(["a", "b"])[10]; // panics
```
+### Range expressions
+
+```{.ebnf .gram}
+range_expr : expr ".." expr |
+ expr ".." |
+ ".." expr |
+ ".." ;
+```
+
+The `..` operator will construct an object of one of the `std::ops::Range` variants.
+
+```
+1..2; // std::ops::Range
+3..; // std::ops::RangeFrom
+..4; // std::ops::RangeTo
+..; // std::ops::RangeFull
+```
+
+The following expressions are equivalent.
+
+```
+let x = std::ops::Range {start: 0, end: 10};
+let y = 0..10;
+
+assert_eq!(x,y);
+```
+
### Unary operator expressions
Rust defines three unary operators. They are all written as prefix operators,
call_expr : expr paren_expr_list ;
```
-A _call expression_ invokes a function, providing zero or more input slots and
-an optional reference slot to serve as the function's output, bound to the
-`lval` on the right hand side of the call. If the function eventually returns,
-then the expression completes.
+A _call expression_ invokes a function, providing zero or more input variables
+and an optional location to move the function's output into. If the function
+eventually returns, then the expression completes.
Some examples of call expressions:
ten_times(|j| println!("hello, {}", j));
```
-### While loops
-
-```{.ebnf .gram}
-while_expr : [ lifetime ':' ] "while" no_struct_literal_expr '{' block '}' ;
-```
-
-A `while` loop begins by evaluating the boolean loop conditional expression.
-If the loop conditional expression evaluates to `true`, the loop body block
-executes and control returns to the loop conditional expression. If the loop
-conditional expression evaluates to `false`, the `while` expression completes.
-
-An example:
-
-```
-let mut i = 0;
-
-while i < 10 {
- println!("hello");
- i = i + 1;
-}
-```
-
### Infinite loops
A `loop` expression denotes an infinite loop.
loop_expr : [ lifetime ':' ] "loop" '{' block '}';
```
-A `loop` expression may optionally have a _label_. If a label is present, then
-labeled `break` and `continue` expressions nested within this loop may exit out
-of this loop or return control to its head. See [Break
-expressions](#break-expressions) and [Continue
+A `loop` expression may optionally have a _label_. The label is written as
+a lifetime preceding the loop expression, as in `'foo: loop{ }`. If a
+label is present, then labeled `break` and `continue` expressions nested
+within this loop may exit out of this loop or return control to its head.
+See [Break expressions](#break-expressions) and [Continue
expressions](#continue-expressions).
### Break expressions
A `break` expression has an optional _label_. If the label is absent, then
executing a `break` expression immediately terminates the innermost loop
enclosing it. It is only permitted in the body of a loop. If the label is
-present, then `break foo` terminates the loop with label `foo`, which need not
+present, then `break 'foo` terminates the loop with label `'foo`, which need not
be the innermost label enclosing the `break` expression, but must enclose it.
### Continue expressions
of the innermost loop enclosing it, returning control to the loop *head*. In
the case of a `while` loop, the head is the conditional expression controlling
the loop. In the case of a `for` loop, the head is the call-expression
-controlling the loop. If the label is present, then `continue foo` returns
-control to the head of the loop with label `foo`, which need not be the
+controlling the loop. If the label is present, then `continue 'foo` returns
+control to the head of the loop with label `'foo`, which need not be the
innermost label enclosing the `break` expression, but must enclose it.
A `continue` expression is only permitted in the body of a loop.
+### While loops
+
+```{.ebnf .gram}
+while_expr : [ lifetime ':' ] "while" no_struct_literal_expr '{' block '}' ;
+```
+
+A `while` loop begins by evaluating the boolean loop conditional expression.
+If the loop conditional expression evaluates to `true`, the loop body block
+executes and control returns to the loop conditional expression. If the loop
+conditional expression evaluates to `false`, the `while` expression completes.
+
+An example:
+
+```
+let mut i = 0;
+
+while i < 10 {
+ println!("hello");
+ i = i + 1;
+}
+```
+
+Like `loop` expressions, `while` loops can be controlled with `break` or
+`continue`, and may optionally have a _label_. See [infinite
+loops](#infinite-loops), [break expressions](#break-expressions), and
+[continue expressions](#continue-expressions) for more information.
+
### For expressions
```{.ebnf .gram}
}
```
+Like `loop` expressions, `for` loops can be controlled with `break` or
+`continue`, and may optionally have a _label_. See [infinite
+loops](#infinite-loops), [break expressions](#break-expressions), and
+[continue expressions](#continue-expressions) for more information.
+
### If expressions
```{.ebnf .gram}
In a pattern whose head expression has an `enum` type, a placeholder (`_`)
stands for a *single* data field, whereas a wildcard `..` stands for *all* the
-fields of a particular variant. For example:
-
-```
-#![feature(box_patterns)]
-#![feature(box_syntax)]
-enum List<X> { Nil, Cons(X, Box<List<X>>) }
-
-fn main() {
- let x: List<i32> = List::Cons(10, box List::Cons(11, box List::Nil));
-
- match x {
- List::Cons(_, box List::Nil) => panic!("singleton list"),
- List::Cons(..) => return,
- List::Nil => panic!("empty list")
- }
-}
-```
-
-The first pattern matches lists constructed by applying `Cons` to any head
-value, and a tail value of `box Nil`. The second pattern matches _any_ list
-constructed with `Cons`, ignoring the values of its arguments. The difference
-between `_` and `..` is that the pattern `C(_)` is only type-correct if `C` has
-exactly one argument, while the pattern `C(..)` is type-correct for any enum
-variant `C`, regardless of how many arguments `C` has.
-
-Used inside an array pattern, `..` stands for any number of elements, when the
-`advanced_slice_patterns` feature gate is turned on. This wildcard can be used
-at most once for a given array, which implies that it cannot be used to
-specifically match elements that are at an unknown distance from both ends of a
-array, like `[.., 42, ..]`. If preceded by a variable name, it will bind the
-corresponding slice to the variable. Example:
-
-```
-# #![feature(advanced_slice_patterns, slice_patterns)]
-fn is_symmetric(list: &[u32]) -> bool {
- match list {
- [] | [_] => true,
- [x, inside.., y] if x == y => is_symmetric(inside),
- _ => false
- }
-}
-
-fn main() {
- let sym = &[0, 1, 4, 2, 4, 1, 0];
- let not_sym = &[0, 1, 7, 2, 4, 1, 0];
- assert!(is_symmetric(sym));
- assert!(!is_symmetric(not_sym));
-}
-```
+fields of a particular variant.
A `match` behaves differently depending on whether or not the head expression
is an [lvalue or an rvalue](#lvalues,-rvalues-and-temporaries). If the head
An example of a `match` expression:
```
-#![feature(box_patterns)]
-#![feature(box_syntax)]
-# fn process_pair(a: i32, b: i32) { }
-# fn process_ten() { }
+let x = 1;
-enum List<X> { Nil, Cons(X, Box<List<X>>) }
-
-fn main() {
- let x: List<i32> = List::Cons(10, box List::Cons(11, box List::Nil));
-
- match x {
- List::Cons(a, box List::Cons(b, _)) => {
- process_pair(a, b);
- }
- List::Cons(10, _) => {
- process_ten();
- }
- List::Nil => {
- return;
- }
- _ => {
- panic!();
- }
- }
+match x {
+ 1 => println!("one"),
+ 2 => println!("two"),
+ 3 => println!("three"),
+ 4 => println!("four"),
+ 5 => println!("five"),
+ _ => println!("something else"),
}
```
subpattern`. For example:
```
-#![feature(box_patterns)]
-#![feature(box_syntax)]
+let x = 1;
-enum List { Nil, Cons(u32, Box<List>) }
-
-fn is_sorted(list: &List) -> bool {
- match *list {
- List::Nil | List::Cons(_, box List::Nil) => true,
- List::Cons(x, ref r @ box List::Cons(_, _)) => {
- match *r {
- box List::Cons(y, _) => (x <= y) && is_sorted(&**r),
- _ => panic!()
- }
- }
- }
+match x {
+ e @ 1 ... 5 => println!("got a range element {}", e),
+ _ => println!("anything"),
}
-
-fn main() {
- let a = List::Cons(6, box List::Cons(7, box List::Cons(42, box List::Nil)));
- assert!(is_sorted(&a));
-}
-
```
Patterns can also dereference pointers by using the `&`, `&mut` and `box`
```
Return expressions are denoted with the keyword `return`. Evaluating a `return`
-expression moves its argument into the output slot of the current function,
-destroys the current function activation frame, and transfers control to the
-caller frame.
+expression moves its argument into the designated output location for the
+current function call, destroys the current function activation frame, and
+transfers control to the caller frame.
An example of a `return` expression:
## Types
-Every slot, item and value in a Rust program has a type. The _type_ of a
+Every variable, item and value in a Rust program has a type. The _type_ of a
*value* defines the interpretation of the memory holding it.
Built-in types and type-constructors are tightly integrated into the language,
* The machine-dependent integer and floating-point types.
[^unittype]: The "unit" value `()` is *not* a sentinel "null pointer" value for
- reference slots; the "unit" type is the implicit return type from functions
+ reference variables; 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.]
UTF-32 string.
A value of type `str` is a Unicode string, represented as an array of 8-bit
-unsigned bytes holding a sequence of UTF-8 codepoints. Since `str` is of
+unsigned bytes holding a sequence of UTF-8 code points. Since `str` is of
unknown size, it is not a _first-class_ type, but can only be instantiated
through a pointer type, such as `&str` or `String`.
```
-### Object types
+### Trait objects
Every trait item (see [traits](#traits)) defines a type with the same name as
-the trait. This type is called the _object type_ of the trait. Object types
+the trait. This type is called the _trait object_ of the trait. Trait objects
permit "late binding" of methods, dispatched using _virtual method tables_
("vtables"). Whereas most calls to trait methods are "early bound" (statically
resolved) to specific implementations at compile time, a call to a method on an
-object type is only resolved to a vtable entry at compile time. The actual
+trait objects is only resolved to a vtable entry at compile time. The actual
implementation for each vtable entry can vary on an object-by-object basis.
Given a pointer-typed expression `E` of type `&T` or `Box<T>`, where `T`
implements trait `R`, casting `E` to the corresponding pointer type `&R` or
-`Box<R>` results in a value of the _object type_ `R`. This result is
+`Box<R>` results in a value of the _trait object_ `R`. This result is
represented as a pair of pointers: the vtable pointer for the `T`
implementation of `R`, and the pointer value of `E`.
-An example of an object type:
+An example of a trait object:
```
trait Printable {
}
```
-In this example, the trait `Printable` occurs as an object type in both the
+In this example, the trait `Printable` occurs as a trait object in both the
type signature of `print`, and the cast expression in `main`.
### Type parameters
`self` refers to the value of type `String` that is the receiver for a call to
the method `make_string`.
-# The `Copy` trait
+# Special traits
+
+Several traits define special evaluation behavior.
-Rust has a special trait, `Copy`, which when implemented changes the semantics
-of a value. Values whose type implements `Copy` are copied rather than moved
-upon assignment.
+## The `Copy` trait
-# The `Sized` trait
+The `Copy` trait changes the semantics of a type implementing it. Values whose
+type implements `Copy` are copied rather than moved upon assignment.
-`Sized` is a special trait which indicates that the size of this type is known
-at compile-time.
+## The `Sized` trait
-# The `Drop` trait
+The `Sized` trait indicates that the size of this type is known at compile-time.
+
+## The `Drop` trait
The `Drop` trait provides a destructor, to be run whenever a value of this type
is to be destroyed.
# Memory model
A Rust program's memory consists of a static set of *items* and a *heap*.
-Immutable portions of the heap may be shared between threads, mutable portions
-may not.
+Immutable portions of the heap may be safely shared between threads, mutable
+portions may not be safely shared, but several mechanisms for effectively-safe
+sharing of mutable values, built on unsafe code but enforcing a safe locking
+discipline, exist in the standard library.
-Allocations in the stack consist of *slots*, and allocations in the heap
+Allocations in the stack consist of *variables*, and allocations in the heap
consist of *boxes*.
### Memory allocation and lifetime
When a stack frame is exited, its local allocations are all released, and its
references to boxes are dropped.
-### Memory slots
+### Variables
-A _slot_ is a component of a stack frame, either a function parameter, a
-[temporary](#lvalues,-rvalues-and-temporaries), or a local variable.
+A _variable_ is a component of a stack frame, either a named function parameter,
+an anonymous [temporary](#lvalues,-rvalues-and-temporaries), or a named local
+variable.
A _local variable_ (or *stack-local* allocation) holds a value directly,
allocated within the stack's memory. The value is a part of the stack frame.
variable `y`).
Methods that take either `self` or `Box<Self>` can optionally place them in a
-mutable slot by prefixing them with `mut` (similar to regular arguments):
+mutable variable by prefixing them with `mut` (similar to regular arguments):
```
trait Changer {
local variables. Local variables can be used only after they have been
initialized; this is enforced by the compiler.
-# Runtime services, linkage and debugging
-
-The Rust _runtime_ is a relatively compact collection of Rust code that
-provides fundamental services and datatypes to all Rust threads at run-time. It
-is smaller and simpler than many modern language runtimes. It is tightly
-integrated into the language's execution model of memory, threads, communication
-and logging.
-
-### Memory allocation
-
-The runtime memory-management system is based on a _service-provider
-interface_, through which the runtime requests blocks of memory from its
-environment and releases them back to its environment when they are no longer
-needed. The default implementation of the service-provider interface consists
-of the C runtime functions `malloc` and `free`.
-
-The runtime memory-management system, in turn, supplies Rust threads with
-facilities for allocating releasing stacks, as well as allocating and freeing
-heap data.
-
-### Built in types
-
-The runtime provides C and Rust code to assist with various built-in types,
-such as arrays, strings, and the low level communication system (ports,
-channels, threads).
-
-Support for other built-in types such as simple types, tuples and enums is
-open-coded by the Rust compiler.
-
-### Thread scheduling and communication
-
-The runtime provides code to manage inter-thread communication. This includes
-the system of thread-lifecycle state transitions depending on the contents of
-queues, as well as code to copy values between queues and their recipients and
-to serialize values for transmission over operating-system inter-process
-communication facilities.
-
-### Linkage
+# Linkage
The Rust compiler supports various methods to link crates together both
statically and dynamically. This section will explore the various methods to