Introduction
This document is the primary reference for the Rust programming language. It provides three kinds of material:
- Chapters that informally describe each language construct and their use.
- Chapters that informally describe the memory model, concurrency model, runtime services, linkage model and debugging facilities.
- Appendix chapters providing rationale and references to languages that influenced the design.
This document does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate book is available to help acquire such background familiarity.
This document also does not serve as a reference to the standard library included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you're looking for may be there, not here.
Finally, this document is not normative. It may include details that are
specific to rustc
itself, and should not be taken as a specification for
the Rust language. We intend to produce such a document someday, but this
is what we have for now.
You may also be interested in the grammar.
N. B. This document may be incomplete. Documenting everything might take a while. We have a big issue to track documentation for every Rust feature, so check that out if you can't find something here.
Notation
Unicode productions
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 code points. The grammar has a Special Unicode Productions section that lists these productions.
String table productions
Some rules in the grammar — notably unary operators, binary operators, and keywords — are given in a simplified form: as a listing of a table of unquoted, printable whitespace-separated strings. These cases form a subset of the rules regarding the token rule, and are assumed to be the result of a lexical-analysis phase feeding the parser, driven by a DFA, operating over the disjunction of all such string table entries.
When such a string enclosed in double-quotes ("
) occurs inside the grammar,
it is an implicit reference to a single member of such a string table
production. See tokens for more information.
Lexical structure
Input format
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 code points, but a small number are defined in terms of Unicode properties or explicit code point lists. 1
Substitute definitions for the special Unicode productions are provided to the grammar verifier, restricted to ASCII range, when verifying the grammar in this document.
Keywords
Rust divides keywords in three categories:
Strict keywords
These keywords can only be used in their correct contexts. For example, it is
not allowed to declare a variable with name struct
.
Lexer:
KW_AS :as
KW_BOX :box
KW_BREAK :break
KW_CONST :const
KW_CONTINUE :continue
KW_CRATE :crate
KW_ELSE :else
KW_ENUM :enum
KW_EXTERN :extern
KW_FALSE :false
KW_FN :fn
KW_FOR :for
KW_IF :if
KW_IMPL :impl
KW_IN :in
KW_LET :let
KW_LOOP :loop
KW_MATCH :match
KW_MOD :mod
KW_MOVE :move
KW_MUT :mut
KW_PUB :pub
KW_REF :ref
KW_RETURN :return
KW_SELFVALUE :self
KW_SELFTYPE :Self
KW_STATIC :static
KW_STRUCT :struct
KW_SUPER :super
KW_TRAIT :trait
KW_TRUE :true
KW_TYPE :type
KW_UNSAFE :unsafe
KW_USE :use
KW_WHERE :wher
KW_WHILE :while
Weak keywords
These keywords have special meaning only in certain contexts. For example,
it is possible to declare a variable or method with the name union
.
Lexer
KW_CATCH :catch
KW_DEFAULT :default
KW_UNION :union
KW_STATICLIFETIME :'static
Reserved keywords
These keywords aren't used yet, but they are reserved for future use. The reasoning behind this is to make current programs forward compatible with future versions of rust by forbiding them to use these keywords.
Lexer
KW_ABSTRACT :abstract
KW_ALIGNOF :alignof
KW_BECOME :become
KW_DO :do
KW_FINAL :final
KW_MACRO :macro
KW_OFFSETOF :offsetof
KW_OVERRIDE :override
KW_PRIV :priv
KW_PROC :proc
KW_PURE :pure
KW_SIZEOF :sizeof
KW_TYPEOF :typeof
KW_UNSIZED :unsized
KW_VIRTUAL :virtual
KW_YIELD :yield
Identifiers
Lexer:
IDENTIFIER :
XID_start XID_continue*
|_
XID_continue+
An identifier is any nonempty Unicode1 string of the following form:
Either
- The first character has property
XID_start
- The remaining characters have property
XID_continue
Or
- The first character is
_
- The identifier is more than one character,
_
alone is not an identifier - The remaining characters have property
XID_continue
that does not occur in the set of keywords.
Note:
XID_start
andXID_continue
as character properties cover the character ranges used to form the more familiar C and Java language-family identifiers.
Non-ASCII characters in identifiers are currently feature gated. This is expected to improve soon.
Comments
Lexer
LINE_COMMENT :
//
(~[/
!
] |//
) ~\n
*
|//
BLOCK_COMMENT :
/*
(~[*
!
] |**
| BlockCommentOrDoc) (BlockCommentOrDoc | ~*/
)**/
|/**/
|/***/
OUTER_LINE_DOC :
//!
~[\n
IsolatedCR]*OUTER_BLOCK_DOC :
/*!
( BlockCommentOrDoc | ~[*/
IsolatedCR] )**/
INNER_LINE_DOC :
///
(~/
~[\n
IsolatedCR]*)?INNER_BLOCK_DOC :
/**
(~*
| BlockCommentOrDoc ) (BlockCommentOrDoc | ~[*/
IsolatedCR])**/
BlockCommentOrDoc :
BLOCK_COMMENT
| OUTER_BLOCK_DOC
| INNER_BLOCK_DOCIsolatedCR :
A\r
not followed by a\n
Non-doc comments
Comments in Rust code follow the general C++ style of line (//
) and
block (/* ... */
) comment forms. Nested block comments are supported.
Non-doc comments are interpreted as a form of whitespace.
Doc comments
Line doc comments beginning with exactly three slashes (///
), and block
doc comments (/** ... */
), both inner doc comments, are interpreted as a
special syntax for doc
attributes. That is, they are equivalent to writing
#[doc="..."]
around the body of the comment, i.e., /// Foo
turns into
#[doc="Foo"]
and /** Bar */
turns into #[doc="Bar"]
.
Line comments beginning with //!
and block comments /*! ... */
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 document
modules that occupy a source file.
Isolated CRs (\r
), i.e. not followed by LF (\n
), are not allowed in doc
comments.
Examples
# #![allow(unused_variables)] #fn main() { //! A doc comment that applies to the implicit anonymous module of this crate pub mod outer_module { //! - Inner line doc //!! - Still an inner line doc (but with a bang at the beginning) /*! - Inner block doc */ /*!! - Still an inner block doc (but with a bang at the beginning) */ // - Only a comment /// - Outer line doc (exactly 3 slashes) //// - Only a comment /* - Only a comment */ /** - Outer block doc (exactly) 2 asterisks */ /*** - Only a comment */ pub mod inner_module {} pub mod nested_comments { /* In Rust /* we can /* nest comments */ */ */ // All three types of block comments can contain or be nested inside // any other type: /* /* */ /** */ /*! */ */ /*! /* */ /** */ /*! */ */ /** /* */ /** */ /*! */ */ pub mod dummy_item {} } pub mod degenerate_cases { // empty inner line doc //! // empty inner block doc /*!*/ // empty line comment // // empty outer line doc /// // empty block comment /**/ pub mod dummy_item {} // empty 2-asterisk block isn't a doc block, it is a block comment /***/ } /* The next one isn't allowed because outer doc comments require an item that will receive the doc */ /// Where is my item? # mod boo {} } #}
Whitespace
Whitespace is any non-empty string containing only characters that have the
Pattern_White_Space
Unicode property, namely:
U+0009
(horizontal tab,'\t'
)U+000A
(line feed,'\n'
)U+000B
(vertical tab)U+000C
(form feed)U+000D
(carriage return,'\r'
)U+0020
(space,' '
)U+0085
(next line)U+200E
(left-to-right mark)U+200F
(right-to-left mark)U+2028
(line separator)U+2029
(paragraph separator)
Rust is a "free-form" language, meaning that all forms of whitespace serve only to separate tokens in the grammar, and have no semantic significance.
A Rust program has identical meaning if each whitespace element is replaced with any other legal whitespace element, such as a single space character.
Tokens
Tokens are primitive productions in the grammar defined by regular (non-recursive) languages. "Simple" tokens are given in string table production form, and occur in the rest of the grammar as double-quoted strings. Other tokens have exact rules given.
Literals
A literal is an expression consisting of a single token, rather than a sequence of tokens, that immediately and directly denotes the value it evaluates to, rather than referring to it by name or some other evaluation rule. A literal is a form of constant expression, so is evaluated (primarily) at compile time.
Examples
Characters and strings
Example | # sets | Characters | Escapes | |
---|---|---|---|---|
Character | 'H' | N/A | All Unicode | Quote & Byte & Unicode |
String | "hello" | N/A | All Unicode | Quote & Byte & Unicode |
Raw | r#"hello"# | 0... | All Unicode | N/A |
Byte | b'H' | N/A | All ASCII | Quote & Byte |
Byte string | b"hello" | N/A | All ASCII | Quote & Byte |
Raw byte string | br#"hello"# | 0... | All ASCII | N/A |
Byte escapes
Name | |
---|---|
\x7F | 8-bit character code (exactly 2 digits) |
\n | Newline |
\r | Carriage return |
\t | Tab |
\\ | Backslash |
\0 | Null |
Unicode escapes
Name | |
---|---|
\u{7FFF} | 24-bit Unicode character code (up to 6 digits) |
Quote escapes
Name | |
---|---|
\' | Single quote |
\" | Double quote |
Numbers
Number literals* | Example | Exponentiation | Suffixes |
---|---|---|---|
Decimal integer | 98_222 | N/A | Integer suffixes |
Hex integer | 0xff | N/A | Integer suffixes |
Octal integer | 0o77 | N/A | Integer suffixes |
Binary integer | 0b1111_0000 | N/A | Integer suffixes |
Floating-point | 123.0E+77 | Optional | Floating-point suffixes |
*
All number literals allow _
as a visual separator: 1_234.0E+18f64
Suffixes
Integer | Floating-point |
---|---|
u8 , i8 , u16 , i16 , u32 , i32 , u64 , i64 , isize , usize | f32 , f64 |
Character and string literals
Character literals
A character literal is a single Unicode character enclosed within two
U+0027
(single-quote) characters, with the exception of U+0027
itself,
which must be escaped by a preceding U+005C
character (\
).
String literals
A string literal is a sequence of any Unicode characters enclosed within two
U+0022
(double-quote) characters, with the exception of U+0022
itself,
which must be escaped by a preceding U+005C
character (\
).
Line-break characters are allowed in string literals. Normally they represent
themselves (i.e. no translation), but as a special exception, when an unescaped
U+005C
character (\
) occurs immediately before the newline (U+000A
), the
U+005C
character, the newline, and all whitespace at the beginning of the
next line are ignored. Thus a
and b
are equal:
# #![allow(unused_variables)] #fn main() { let a = "foobar"; let b = "foo\ bar"; assert_eq!(a,b); #}
Character escapes
Some additional escapes are available in either character or non-raw string
literals. An escape starts with a U+005C
(\
) and continues with one of the
following forms:
- 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 code point escape starts with
U+0075
(u
) and is followed by up to six hex digits surrounded by bracesU+007B
({
) andU+007D
(}
). 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
), orU+0074
(t
), denoting the Unicode valuesU+000A
(LF),U+000D
(CR) orU+0009
(HT) respectively. - The null escape is the character
U+0030
(0
) and denotes the Unicode valueU+0000
(NUL). - The backslash escape is the character
U+005C
(\
) which must be escaped in order to denote itself.
Raw string literals
Raw string literals do not process any escapes. They start with the character
U+0072
(r
), followed by zero or more of the character U+0023
(#
) and a
U+0022
(double-quote) character. The raw string body can contain any sequence
of Unicode characters and is terminated only by another U+0022
(double-quote)
character, followed by the same number of U+0023
(#
) characters that preceded
the opening U+0022
(double-quote) character.
All Unicode characters contained in the raw string body represent themselves,
the characters U+0022
(double-quote) (except when followed by at least as
many U+0023
(#
) characters as were used to start the raw string literal) or
U+005C
(\
) do not have any special meaning.
Examples for string literals:
# #![allow(unused_variables)] #fn main() { "foo"; r"foo"; // foo "\"foo\""; r#""foo""#; // "foo" "foo #\"# bar"; r##"foo #"# bar"##; // foo #"# bar "\x52"; "R"; r"R"; // R "\\x52"; r"\x52"; // \x52 #}
Byte and byte string literals
Byte literals
A byte literal is a single ASCII character (in the U+0000
to U+007F
range) or a single escape preceded by the characters U+0062
(b
) and
U+0027
(single-quote), and followed by the character U+0027
. If the character
U+0027
is present within the literal, it must be escaped by a preceding
U+005C
(\
) character. It is equivalent to a u8
unsigned 8-bit integer
number literal.
Byte string literals
A non-raw byte string literal is a sequence of ASCII characters and escapes,
preceded by the characters U+0062
(b
) and U+0022
(double-quote), and
followed by the character U+0022
. If the character U+0022
is present within
the literal, it must be escaped by a preceding U+005C
(\
) character.
Alternatively, a byte string literal can be a raw byte string literal, defined
below. A byte string literal of length n
is equivalent to a &'static [u8; n]
borrowed fixed-sized array
of unsigned 8-bit integers.
Some additional escapes are available in either byte or non-raw byte string
literals. An escape starts with a U+005C
(\
) and continues with one of the
following forms:
- 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
(r
), orU+0074
(t
), denoting the bytes values0x0A
(ASCII LF),0x0D
(ASCII CR) or0x09
(ASCII HT) respectively. - The null escape is the character
U+0030
(0
) and denotes the byte value0x00
(ASCII NUL). - The backslash escape is the character
U+005C
(\
) which must be escaped in order to denote its ASCII encoding0x5C
.
Raw byte string literals
Raw byte string literals do not process any escapes. They start with the
character U+0062
(b
), followed by U+0072
(r
), followed by zero or more
of the character U+0023
(#
), and a U+0022
(double-quote) character. The
raw string body can contain any sequence of ASCII characters and is terminated
only by another U+0022
(double-quote) character, followed by the same number of
U+0023
(#
) characters that preceded the opening U+0022
(double-quote)
character. A raw byte string literal can not contain any non-ASCII byte.
All characters contained in the raw string body represent their ASCII encoding,
the characters U+0022
(double-quote) (except when followed by at least as
many U+0023
(#
) characters as were used to start the raw string literal) or
U+005C
(\
) do not have any special meaning.
Examples for byte string literals:
# #![allow(unused_variables)] #fn main() { b"foo"; br"foo"; // foo b"\"foo\""; br#""foo""#; // "foo" b"foo #\"# bar"; br##"foo #"# bar"##; // foo #"# bar b"\x52"; b"R"; br"R"; // R b"\\x52"; br"\x52"; // \x52 #}
Number literals
A number literal is either an integer literal or a floating-point literal. The grammar for recognizing the two kinds of literals is mixed.
Integer literals
An integer literal has one of four forms:
- A decimal literal starts with a decimal digit and continues with any mixture of decimal digits and underscores.
- A hex literal starts with the character sequence
U+0030
U+0078
(0x
) and continues as any mixture of hex digits and underscores. - An octal literal starts with the character sequence
U+0030
U+006F
(0o
) and continues as any mixture of octal digits and underscores. - A binary literal starts with the character sequence
U+0030
U+0062
(0b
) and continues as any mixture of binary digits and underscores.
Like any literal, an integer literal may be followed (immediately,
without any spaces) by an integer suffix, which forcibly sets the
type of the literal. The integer suffix must be the name of one of the
integral types: u8
, i8
, u16
, i16
, u32
, i32
, u64
, i64
,
isize
, or usize
.
The type of an unsuffixed integer literal is determined by type inference:
-
If an integer type can be uniquely determined from the surrounding program context, the unsuffixed integer literal has that type.
-
If the program context under-constrains the type, it defaults to the signed 32-bit integer
i32
. -
If the program context over-constrains the type, it is considered a static type error.
Examples of integer literals of various forms:
# #![allow(unused_variables)] #fn main() { 123i32; // type i32 123u32; // type u32 123_u32; // type u32 0xff_u8; // type u8 0o70_i16; // type i16 0b1111_1111_1001_0000_i32; // type i32 0usize; // type usize #}
Note that the Rust syntax considers -1i8
as an application of the unary minus
operator to an integer literal 1i8
, rather than
a single integer literal.
Floating-point literals
A floating-point literal has one of two forms:
- A decimal literal followed by a period character
U+002E
(.
). This is optionally followed by another decimal literal, with an optional exponent. - A single decimal literal followed by an exponent.
Like integer literals, a floating-point literal may be followed by a
suffix, so long as the pre-suffix part does not end with U+002E
(.
).
The suffix forcibly sets the type of the literal. There are two valid
floating-point suffixes, f32
and f64
(the 32-bit and 64-bit floating point
types), which explicitly determine the type of the literal.
The type of an unsuffixed floating-point literal is determined by type inference:
-
If a floating-point type can be uniquely determined from the surrounding program context, the unsuffixed floating-point literal has that type.
-
If the program context under-constrains the type, it defaults to
f64
. -
If the program context over-constrains the type, it is considered a static type error.
Examples of floating-point literals of various forms:
# #![allow(unused_variables)] #fn main() { 123.0f64; // type f64 0.1f64; // type f64 0.1f32; // type f32 12E+99_f64; // type f64 let x: f64 = 2.; // type f64 #}
This last example is different because it is not possible to use the suffix
syntax with a floating point literal ending in a period. 2.f64
would attempt
to call a method named f64
on 2
.
The representation semantics of floating-point numbers are described in "Machine Types".
Boolean literals
The two values of the boolean type are written true
and false
.
Symbols
Symbols are a general class of printable tokens that play structural roles in a variety of grammar productions. They are a set of remaining miscellaneous printable tokens that do not otherwise appear as unary operators, binary operators, or keywords. They are catalogued in the Symbols section of the Grammar document.
Paths
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 or a variable 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 is only meaningful within a given crate. There is no global namespace across crates; an item's canonical path merely identifies it within the crate.
Two examples of simple paths consisting of only identifier components:
x;
x::y::z;
Path components are usually identifiers, but they may
also include angle-bracket-enclosed lists of type arguments. In
expression context, the type argument list is given
after a ::
namespace qualifier in order to disambiguate it from a
relational expression involving the less-than symbol (<
). In type
expression context, the final namespace qualifier is omitted.
Two examples of paths with type arguments:
# #![allow(unused_variables)] #fn main() { # struct HashMap<K, V>(K,V); # fn f() { # fn id<T>(t: T) -> T { t } type T = HashMap<i32,String>; // Type arguments used in a type expression let x = id::<i32>(10); // Type arguments used in a call expression # } #}
Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved:
- Paths starting with
::
are considered to be global paths where the components of the path start being resolved from the crate root. Each identifier in the path must resolve to an item.
mod a { pub fn foo() {} } mod b { pub fn foo() { ::a::foo(); // call a's foo function } } # fn main() {}
- Paths starting with the keyword
super
begin resolution relative to the parent module. Each further identifier must resolve to an item.
mod a { pub fn foo() {} } mod b { pub fn foo() { super::a::foo(); // call a's foo function } } # fn main() {}
- Paths starting with the keyword
self
begin resolution relative to the current module. Each further identifier must resolve to an item.
fn foo() {} fn bar() { self::foo(); } # fn main() {}
Additionally keyword super
may be repeated several times after the first
super
or self
to refer to ancestor modules.
mod a { fn foo() {} mod b { mod c { fn foo() { super::super::foo(); // call a's foo function self::super::super::foo(); // call a's foo function } } } } # fn main() {}
Macros
A number of minor features of Rust are not central enough to have their own
syntax, and yet are not implementable as functions. Instead, they are given
names, and invoked through a consistent syntax: some_extension!(...)
.
Users of rustc
can define new macros in two ways:
- Macros define new syntax in a higher-level, declarative way.
- Procedural Macros can be used to implement custom derive.
And one unstable way: compiler plugins.
Macros By Example
macro_rules
allows users to define syntax extension in a declarative way. We
call such extensions "macros by example" or simply "macros".
Currently, macros can expand to expressions, statements, items, or patterns.
(A sep_token
is any token other than *
and +
. A non_special_token
is
any token other than a delimiter or $
.)
The macro expander looks up macro invocations by name, and tries each macro rule in turn. It transcribes the first successful match. Matching and transcription are closely related to each other, and we will describe them together.
The macro expander matches and transcribes every token that does not begin with
a $
literally, including delimiters. For parsing reasons, delimiters must be
balanced, but they are otherwise not special.
In the matcher, $
name :
designator matches the nonterminal in the Rust
syntax named by designator. Valid designators are:
item
: an itemblock
: a blockstmt
: a statementpat
: a patternexpr
: an expressionty
: a typeident
: an identifierpath
: a pathtt
: a token tree (a single token by matching()
,[]
, or{}
)meta
: the contents of an attribute
In the transcriber, the designator is already known, and so 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 parentheses, optionally
followed by a separator token, followed by *
or +
. *
means zero or more
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
out.
The rules for transcription of these repetitions are called "Macro By Example".
Essentially, one "layer" of repetition is discharged at a time, and all of them
must be discharged by the time a name is transcribed. Therefore, ( $( $i:ident ),* ) => ( $i )
is an invalid macro, but ( $( $i:ident ),* ) => ( $( $i:ident ),* )
is acceptable (if trivial).
When Macro By Example encounters a repetition, it examines all of the $
name s that occur in its body. At the "current layer", they all must repeat
the same number of times, so ( $( $i:ident ),* ; $( $j:ident ),* ) => ( $( ($i,$j) ),* )
is valid if given the argument (a,b,c ; d,e,f)
, but not
(a,b,c ; d,e)
. The repetition walks through the choices at that layer in
lockstep, so the former input transcribes to (a,d), (b,e), (c,f)
.
Nested repetitions are allowed.
Parsing limitations
The parser used by the macro system is reasonably powerful, but the parsing of Rust syntax is restricted in two ways:
- Macro definitions are required to include suitable separators after parsing
expressions and other bits of the Rust grammar. This implies that
a macro definition like
$i:expr [ , ]
is not legal, because[
could be part of an expression. A macro definition like$i:expr,
or$i:expr;
would be legal, however, because,
and;
are legal separators. See RFC 550 for more information. - The parser must have eliminated all ambiguity by the time it reaches a
$
name:
designator. 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.
Procedural Macros
"Procedural macros" are the second way to implement a macro. For now, the only thing they can be used for is to implement derive on your own types. See the book for a tutorial.
Procedural macros involve a few different parts of the language and its
standard libraries. First is the proc_macro
crate, included with Rust,
that defines an interface for building a procedural macro. The
#[proc_macro_derive(Foo)]
attribute is used to mark the deriving
function. This function must have the type signature:
use proc_macro::TokenStream;
#[proc_macro_derive(Hello)]
pub fn hello_world(input: TokenStream) -> TokenStream
Finally, procedural macros must be in their own crate, with the proc-macro
crate type.
Crates and source files
Syntax
Crate :
UTF8BOM?
SHEBANG?
InnerAttribute*
Item*
Lexer
UTF8BOM :\uFEFF
SHEBANG :#!
~[[
\n
] ~\n
*
Although Rust, like any other language, can be implemented by an interpreter as well as a compiler, the only existing implementation is a 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.1 Semantic rules that have a static interpretation govern the success or failure of compilation, while semantic rules that have a dynamic interpretation govern the behavior of the program at run-time.
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 some sort of library.2
A crate is a unit of compilation and linking, as well as versioning, distribution and runtime loading. A crate contains a tree of nested module scopes. 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 denoting its location within the crate's module tree.
The Rust compiler is always invoked with a single source file as input, and
always produces a single output crate. The processing of that source file may
result in other source files being loaded as modules. Source files have the
extension .rs
.
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. Every source file is a module, but not every
module needs its own source file: module definitions 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, 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.
# #![allow(unused_variables)] #fn main() { // Specify the crate name. #![crate_name = "projx"] // Specify the type of output artifact. #![crate_type = "lib"] // Turn on a warning. // This can be done in any module, not just the anonymous crate module. #![warn(non_camel_case_types)] #}
A crate that contains a main
function can be compiled to an executable. If a
main
function is present, its return type must be ()
("unit") and it must take no arguments.
The optional UTF8 byte order mark (UTF8BOM production) indicates that the file is encoded in UTF8. It can only occur at the beginning of the file and is ignored by the compiler.
A source file can have a shebang (SHEBANG production), which indicates to the operating system what program to use to execute this file. It serves essentially to treat the source file as an executable script. The shebang can only occur at the beginning of the file (but after the optional UTF8BOM). It is ignored by the compiler. For example:
#!/usr/bin/env rustx
fn main() {
println!("Hello!");
}
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.
A crate is somewhat analogous to an assembly in the ECMA-335 CLI model, a library in the SML/NJ Compilation Manager, a unit in the Owens and Flatt module system, or a configuration in Mesa.
Items and attributes
Crates contain items, each of which may have some number of attributes attached to it.
Items
An item is a component of a crate. Items are organized within a crate by a nested set of modules. Every crate has a single "outermost" anonymous module; all further items within the crate have paths within the module tree of the crate.
Items are entirely determined at compile-time, generally remain fixed during execution, and may reside in read-only memory.
There are several kinds of item:
- modules
extern crate
declarationsuse
declarations- function definitions
- type definitions
- struct definitions
- enumeration definitions
- union definitions
- constant items
- static items
- trait definitions
- implementations
extern
blocks
Some items form an implicit scope for the declaration of sub-items. In other words, within a function or module, declarations of items can (in many cases) be mixed with the statements, control blocks, and similar artifacts that otherwise compose the item body. The meaning of these scoped items is the same as if the item was declared outside the scope — it is still a static item — except that the item's path name within the module namespace is qualified by the name of the enclosing item, or is private to the enclosing item (in the case of functions). The grammar specifies the exact locations in which sub-item declarations may appear.
Type Parameters
Functions, type aliases, structs, enumerations, unions, traits and
implementations may be parameterized by type. Type parameters are given as a
comma-separated list of identifiers enclosed in angle brackets (<...>
), after
the name of the item (except for implementations, where they come directly
after impl
) and before its definition.
The type parameters of an item are considered "part of the name", not part of the type of the item. A referencing path 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. In practice, the type-inference system can usually infer such argument types from context. There are no general type-parametric types, only type-parametric items. That is, Rust has no notion of type abstraction: there are no higher-ranked (or "forall") types abstracted over other types, though higher-ranked types do exist for lifetimes.
Modules
A module is a container for zero or more items.
A module item is a module, surrounded in braces, named, and prefixed with the
keyword mod
. A module item introduces a new, named module into the tree of
modules making up a crate. Modules can nest arbitrarily.
An example of a module:
# #![allow(unused_variables)] #fn main() { mod math { type Complex = (f64, f64); fn sin(f: f64) -> f64 { /* ... */ # panic!(); } fn cos(f: f64) -> f64 { /* ... */ # panic!(); } fn tan(f: f64) -> f64 { /* ... */ # panic!(); } } #}
Modules and types share the same namespace. Declaring a named type with the
same name as a module in scope is forbidden: that is, a type definition, trait,
struct, enumeration, union, type parameter or crate can't shadow the name of a
module in scope, or vice versa. Items brought into scope with use
also have
this restriction.
A module without a body is loaded from an external file, by default with the
same name as the module, plus the .rs
extension. When a nested submodule is
loaded from an external file, it is loaded from a subdirectory path that
mirrors the module hierarchy.
// Load the `vec` module from `vec.rs`
mod vec;
mod thread {
// Load the `local_data` module from `thread/local_data.rs`
// or `thread/local_data/mod.rs`.
mod local_data;
}
The directories and files used for loading external file modules can be
influenced with the path
attribute.
#[path = "thread_files"]
mod thread {
// Load the `local_data` module from `thread_files/tls.rs`
#[path = "tls.rs"]
mod local_data;
}
Extern crate declarations
An extern crate
declaration specifies a dependency on an external crate.
The external crate is then bound into the declaring scope as the ident
provided in the extern_crate_decl
.
The external crate is resolved to a specific soname
at compile time, and a
runtime linkage requirement to that soname
is passed to the linker for
loading at runtime. The soname
is resolved at compile time by scanning the
compiler's library path and matching the optional crateid
provided against
the crateid
attributes that were declared on the external crate when it was
compiled. If no crateid
is provided, a default name
attribute is assumed,
equal to the ident
given in the extern_crate_decl
.
Three examples of extern crate
declarations:
extern crate pcre;
extern crate std; // equivalent to: extern crate std as std;
extern crate std as ruststd; // linking to 'std' under another name
When naming Rust crates, hyphens are disallowed. However, Cargo packages may
make use of them. In such case, when Cargo.toml
doesn't specify a crate name,
Cargo will transparently replace -
with _
(Refer to RFC 940 for more
details).
Here is an example:
// Importing the Cargo package hello-world
extern crate hello_world; // hyphen replaced with an underscore
Use declarations
A use declaration creates one or more local name bindings synonymous with
some other path. Usually a use
declaration is used to shorten the path
required to refer to a module item. These declarations may appear in modules
and blocks, usually at the top.
Note: Unlike in many languages,
use
declarations in Rust do not declare linkage dependency with external crates. Rather,extern crate
declarations declare linkage dependencies.
Use declarations support a number of convenient shortcuts:
- Simultaneously binding a list of paths differing only in their final element,
using the glob-like brace syntax
use a::b::{c,d,e,f};
- Simultaneously binding a list of paths differing only in their final element
and their immediate parent module, using the
self
keyword, such asuse a::b::{self, c, d};
- Rebinding the target name as a new local name, using the syntax
use p::q::r as x;
. This can also be used with the last two features:use a::b::{self as ab, c as abc}
. - Binding all paths matching a given prefix, using the asterisk wildcard syntax
use a::b::*;
An example of use
declarations:
use std::option::Option::{Some, None}; use std::collections::hash_map::{self, HashMap}; fn foo<T>(_: T){} fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){} fn main() { // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64), // std::option::Option::None]);' foo(vec![Some(1.0f64), None]); // Both `hash_map` and `HashMap` are in scope. let map1 = HashMap::new(); let map2 = hash_map::HashMap::new(); bar(map1, map2); }
Like items, use
declarations are private to the containing module, by
default. Also like items, a use
declaration can be public, if qualified by
the pub
keyword. Such a use
declaration serves to re-export a name. A
public use
declaration can therefore redirect some public name to a
different target definition: even a definition with a private canonical path,
inside a different module. If a sequence of such redirections form a cycle or
cannot be resolved unambiguously, they represent a compile-time error.
An example of re-exporting:
# fn main() { } mod quux { pub use quux::foo::{bar, baz}; pub mod foo { pub fn bar() { } pub fn baz() { } } }
In this example, the module quux
re-exports two public names defined in
foo
.
Also note that the paths contained in use
items are relative to the crate
root. So, in the previous example, the use
refers to quux::foo::{bar, baz}
,
and not simply to foo::{bar, baz}
. This also means that top-level module
declarations should be at the crate root if direct usage of the declared
modules within use
items is desired. It is also possible to use self
and
super
at the beginning of a use
item to refer to the current and direct
parent modules respectively. All rules regarding accessing declared modules in
use
declarations apply to both module declarations and extern crate
declarations.
An example of what will and will not work for use
items:
# #![allow(unused_imports)] use foo::baz::foobaz; // good: foo is at the root of the crate mod foo { mod example { pub mod iter {} } use foo::example::iter; // good: foo is at crate root // use example::iter; // bad: example 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 pub mod bar { pub fn foobar() { } } pub mod baz { use super::bar::foobar; // good: super refers to module 'foo' pub fn foobaz() { } } } fn main() {}
Functions
A function consists of a block, along with a name and a set of parameters.
Other than a name, all these are optional. Functions are declared with the
keyword fn
. Functions may declare a set of input variables
as parameters, through which the caller passes arguments into the function, and
the output type of the value the function will return to its caller
on completion.
When referred to, a function yields a first-class value of the corresponding zero-sized function item type, which when called evaluates to a direct call to the function.
For example, this is a simple function:
# #![allow(unused_variables)] #fn main() { fn answer_to_life_the_universe_and_everything() -> i32 { return 42; } #}
As with let
bindings, function arguments are irrefutable patterns, so any
pattern that is valid in a let binding is also valid as an argument:
# #![allow(unused_variables)] #fn main() { fn first((value, _): (i32, i32)) -> i32 { value } #}
The block of a function is conceptually wrapped in a block that binds the
argument patterns and then return
s the value of the function's block. This
means that the tail expression of the block, if evaluated, ends up being
returned to the caller. As usual, an explicit return expression within
the body of the function will short-cut that implicit return, if reached.
For example, the function above behaves as if it was written as:
// argument_0 is the actual first argument passed from the caller
let (value, _) = argument_0;
return {
value
};
Generic functions
A generic function allows one or more parameterized types to appear in its signature. Each type parameter must be explicitly declared in an angle-bracket-enclosed and comma-separated list, following the function name.
# #![allow(unused_variables)] #fn main() { // foo is generic over A and B fn foo<A, B>(x: A, y: B) { # } #}
Inside the function signature and body, the name of the type parameter can be
used as a type name. Trait 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:
# #![allow(unused_variables)] #fn main() { # use std::fmt::Debug; fn foo<T>(x: T) where T: Debug { # } #}
When a generic function is referenced, its type is instantiated based on the
context of the reference. For example, calling the foo
function here:
# #![allow(unused_variables)] #fn main() { use std::fmt::Debug; fn foo<T>(x: &[T]) where T: Debug { // details elided } foo(&[1, 2]); #}
will instantiate type parameter T
with i32
.
The type parameters can also be explicitly supplied in a trailing path
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
.
Diverging functions
A special kind of function can be declared with a !
character where the
output type would normally be. For example:
# #![allow(unused_variables)] #fn main() { fn my_err(s: &str) -> ! { println!("{}", s); panic!(); } #}
We call such functions "diverging" because they never return a value to the
caller. Every control path in a diverging function must end with a panic!()
,
a loop expression without an associated break expression, or a call to another
diverging function on every control path. The !
annotation does not denote
a type.
It might be necessary to declare a diverging function because as mentioned
previously, the typechecker checks that every control path in a function ends
with a return
or diverging expression. So, if my_err
were declared
without the !
annotation, the following code would not typecheck:
# #![allow(unused_variables)] #fn main() { # fn my_err(s: &str) -> ! { panic!() } fn f(i: i32) -> i32 { if i == 42 { return 42; } else { my_err("Bad number!"); } } #}
This will not compile without the !
annotation on my_err
, since the else
branch of the conditional in f
does not return an i32
, as required by the
signature of f
. Adding the !
annotation to my_err
informs the typechecker
that, should control ever enter my_err
, no further type judgments about f
need to hold, since control will never resume in any context that relies on
those judgments. Thus the return type on f
only needs to reflect the if
branch of the conditional.
Extern functions
Extern functions are part of Rust's foreign function interface, providing the
opposite functionality to external blocks. Whereas external
blocks allow Rust code to call foreign code, extern functions with bodies
defined in Rust code can be called by foreign code. They are defined in the
same way as any other Rust function, except that they have the extern
modifier.
# #![allow(unused_variables)] #fn main() { // Declares an extern fn, the ABI defaults to "C" extern fn new_i32() -> i32 { 0 } // Declares an extern fn with "stdcall" ABI # #[cfg(target_arch = "x86_64")] extern "stdcall" fn new_i32_stdcall() -> i32 { 0 } #}
Unlike normal functions, extern fns have type extern "ABI" fn()
. This is the
same type as the functions declared in an extern block.
# #![allow(unused_variables)] #fn main() { # extern fn new_i32() -> i32 { 0 } let fptr: extern "C" fn() -> i32 = new_i32; #}
Type aliases
A type alias defines a new name for an existing type. Type aliases are
declared with the keyword type
. Every value has a single, specific type, but
may implement several different traits, or be compatible with 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:
# #![allow(unused_variables)] #fn main() { type Point = (u8, u8); let p: Point = (41, 68); #}
A type alias to an enum type cannot be used to qualify the constructors:
# #![allow(unused_variables)] #fn main() { enum E { A } type F = E; let _: F = E::A; // OK // let _: F = F::A; // Doesn't work #}
Structs
A struct is a nominal struct type defined with the keyword struct
.
An example of a struct
item and its use:
# #![allow(unused_variables)] #fn main() { struct Point {x: i32, y: i32} let p = Point {x: 10, y: 11}; let px: i32 = p.x; #}
A tuple struct is a nominal tuple type, also defined with the keyword
struct
. For example:
# #![allow(unused_variables)] #fn main() { struct Point(i32, i32); let p = Point(10, 11); let px: i32 = match p { Point(x, _) => x }; #}
A unit-like struct is a struct without any fields, defined by leaving off the list of fields entirely. Such a struct implicitly defines a constant of its type with the same name. For example:
# #![allow(unused_variables)] #fn main() { struct Cookie; let c = [Cookie, Cookie {}, Cookie, Cookie {}]; #}
is equivalent to
# #![allow(unused_variables)] #fn main() { struct Cookie {} const Cookie: Cookie = Cookie {}; let c = [Cookie, Cookie {}, Cookie, Cookie {}]; #}
The precise memory layout of a struct is not specified. One can specify a
particular layout using the repr
attribute.
Enumerations
An enumeration is a simultaneous definition of a nominal enumerated type as well as a set of constructors, that can be used to create or pattern-match values of the corresponding enumerated type.
Enumerations are declared with the keyword enum
.
An example of an enum
item and its use:
# #![allow(unused_variables)] #fn main() { enum Animal { Dog, Cat, } let mut a: Animal = Animal::Dog; a = Animal::Cat; #}
Enumeration constructors can have either named or unnamed fields:
# #![allow(unused_variables)] #fn main() { 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, whereas Dog
is simply
called an enum variant. Each enum instance has a discriminant which is an
integer associated to it that is used to determine which variant it holds.
C-like Enumerations
If there is no data attached to any of the variants of an enumeration it is called a c-like enumeration. If a discriminant isn't specified, they start at zero, and add one for each variant, in order. Each enum value is just its discriminant which you can specify explicitly:
# #![allow(unused_variables)] #fn main() { enum Foo { Bar, // 0 Baz = 123, Quux, // 124 } #}
The right hand side of the specification is interpreted as an isize
value,
but the compiler is allowed to use a smaller type in the actual memory layout.
The repr
attribute can be added in order to change the type of the right
hand side and specify the memory layout.
You can also cast a c-like enum to get its discriminant:
# #![allow(unused_variables)] #fn main() { # enum Foo { Baz = 123 } let x = Foo::Baz as u32; // x is now 123u32 #}
This only works as long as none of the variants have data attached. If it were
Baz(i32)
, this is disallowed.
Unions
A union declaration uses the same syntax as a struct declaration, except with
union
in place of struct
.
# #![allow(unused_variables)] #fn main() { #[repr(C)] union MyUnion { f1: u32, f2: f32, } #}
The key property of unions is that all fields of a union share common storage. As a result writes to one field of a union can overwrite its other fields, and size of a union is determined by the size of its largest field.
A value of a union type can be created using the same syntax that is used for struct types, except that it must specify exactly one field:
# #![allow(unused_variables)] #fn main() { # union MyUnion { f1: u32, f2: f32 } # let u = MyUnion { f1: 1 }; #}
The expression above creates a value of type MyUnion
with active field f1
.
Active field of a union can be accessed using the same syntax as struct fields:
let f = u.f1;
Inactive fields can be accessed as well (using the same syntax) if they are
sufficiently layout compatible with the current value kept by the union.
Reading incompatible fields results in undefined behavior. However, the active
field is not generally known statically, so all reads of union fields have to
be placed in unsafe
blocks.
# #![allow(unused_variables)] #fn main() { # union MyUnion { f1: u32, f2: f32 } # let u = MyUnion { f1: 1 }; # unsafe { let f = u.f1; } #}
Writes to Copy
union fields do not require reads for running destructors, so
these writes don't have to be placed in unsafe
blocks
# #![allow(unused_variables)] #fn main() { # union MyUnion { f1: u32, f2: f32 } # let mut u = MyUnion { f1: 1 }; # u.f1 = 2; #}
Commonly, code using unions will provide safe wrappers around unsafe union field accesses.
Another way to access union fields is to use pattern matching. Pattern matching
on union fields uses the same syntax as struct patterns, except that the
pattern must specify exactly one field. Since pattern matching accesses
potentially inactive fields it has to be placed in unsafe
blocks as well.
# #![allow(unused_variables)] #fn main() { # union MyUnion { f1: u32, f2: f32 } # fn f(u: MyUnion) { unsafe { match u { MyUnion { f1: 10 } => { println!("ten"); } MyUnion { f2 } => { println!("{}", f2); } } } } #}
Pattern matching may match a union as a field of a larger structure. In particular, when using a Rust union to implement a C tagged union via FFI, this allows matching on the tag and the corresponding field simultaneously:
# #![allow(unused_variables)] #fn main() { #[repr(u32)] enum Tag { I, F } #[repr(C)] union U { i: i32, f: f32, } #[repr(C)] struct Value { tag: Tag, u: U, } fn is_zero(v: Value) -> bool { unsafe { match v { Value { tag: I, u: U { i: 0 } } => true, Value { tag: F, u: U { f: 0.0 } } => true, _ => false, } } } #}
Since union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields. Borrow checking rules have to be adjusted to account for this fact. As a result, if one field of a union is borrowed, all its remaining fields are borrowed as well for the same lifetime.
// ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time
fn test() {
let mut u = MyUnion { f1: 1 };
unsafe {
let b1 = &mut u.f1;
---- first mutable borrow occurs here (via `u.f1`)
let b2 = &mut u.f2;
^^^^ second mutable borrow occurs here (via `u.f2`)
*b1 = 5;
}
- first borrow ends here
assert_eq!(unsafe { u.f1 }, 5);
}
As you could see, in many aspects (except for layouts, safety and ownership) unions behave exactly like structs, largely as a consequence of inheriting their syntactic shape from structs. This is also true for many unmentioned aspects of Rust language (such as privacy, name resolution, type inference, generics, trait implementations, inherent implementations, coherence, pattern checking, etc etc etc).
More detailed specification for unions, including unstable bits, can be found in RFC 1897 "Unions v1.2".
Constant items
A constant item is a named constant value which is not associated with a specific memory location in the program. Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. References to the same constant are not necessarily guaranteed to refer to the same memory address.
Constant values must not have destructors, and otherwise permit most forms of
data. Constants may refer to the address of other constants, in which case the
address will have elided lifetimes where applicable, otherwise – in most cases
– defaulting to the static
lifetime. (See below on static lifetime
elision.) The compiler is, however, still at liberty to translate the constant
many times, so the address referred to may not be stable.
Constants must be explicitly typed. The type may be any type that doesn't
implement Drop
and has a 'static
lifetime: any references it contains
must have 'static
lifetimes.
# #![allow(unused_variables)] #fn main() { const BIT1: u32 = 1 << 0; const BIT2: u32 = 1 << 1; const BITS: [u32; 2] = [BIT1, BIT2]; const STRING: &'static str = "bitstring"; struct BitsNStrings<'a> { mybits: [u32; 2], mystring: &'a str, } const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings { mybits: BITS, mystring: STRING, }; #}
Static items
A static item is similar to a constant, except that it represents a precise
memory location in the program. A static is never "inlined" at the usage site,
and all references to it refer to the same memory location. Static items have
the static
lifetime, which outlives all other lifetimes in a Rust program.
Static items may be placed in read-only memory if they do not contain any
interior mutability.
Statics may contain interior mutability through the UnsafeCell
language item.
All access to a static is safe, but there are a number of restrictions on
statics:
- Statics may not contain any destructors.
- The types of static values must ascribe to
Sync
to allow thread-safe access. - Statics may not refer to other statics by value, only by reference.
- Constants cannot refer to statics.
Constants should in general be preferred over statics, unless large amounts of data are being stored, or single-address and mutability properties are required.
Mutable statics
If a static item is declared with the mut
keyword, then it is allowed to be
modified by the program. One of Rust's goals is to make concurrency bugs hard
to run into, and this is obviously a very large source of race conditions or
other bugs. For this reason, an unsafe
block is required when either reading
or writing a mutable static variable. Care should be taken to ensure that
modifications to a mutable static are safe with respect to other threads
running in the same process.
Mutable statics are still very useful, however. They can be used with C
libraries and can also be bound from C libraries (in an extern
block).
# #![allow(unused_variables)] #fn main() { # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 } static mut LEVELS: u32 = 0; // This violates the idea of no shared state, and this doesn't internally // protect against races, so this function is `unsafe` unsafe fn bump_levels_unsafe1() -> u32 { let ret = LEVELS; LEVELS += 1; return ret; } // Assuming that we have an atomic_add function which returns the old value, // this function is "safe" but the meaning of the return value may not be what // callers expect, so it's still marked as `unsafe` unsafe fn bump_levels_unsafe2() -> u32 { return atomic_add(&mut LEVELS, 1); } #}
Mutable statics have the same restrictions as normal statics, except that the
type of the value is not required to ascribe to Sync
.
'static
lifetime elision
Both constant and static declarations of reference types have implicit
'static
lifetimes unless an explicit lifetime is specified. As such, the
constant declarations involving 'static
above may be written without the
lifetimes. Returning to our previous example:
# #![allow(unused_variables)] #fn main() { const BIT1: u32 = 1 << 0; const BIT2: u32 = 1 << 1; const BITS: [u32; 2] = [BIT1, BIT2]; const STRING: &str = "bitstring"; struct BitsNStrings<'a> { mybits: [u32; 2], mystring: &'a str, } const BITS_N_STRINGS: BitsNStrings = BitsNStrings { mybits: BITS, mystring: STRING, }; #}
Note that if the static
or const
items include function or closure
references, which themselves include references, the compiler will first try
the standard elision rules (see discussion in the nomicon).
If it is unable to resolve the lifetimes by its usual rules, it will default to
using the 'static
lifetime. By way of example:
// Resolved as `fn<'a>(&'a str) -> &'a str`.
const RESOLVED_SINGLE: fn(&str) -> &str = ..
// Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
const RESOLVED_MULTIPLE: Fn(&Foo, &Bar, &Baz) -> usize = ..
// There is insufficient information to bound the return reference lifetime
// relative to the argument lifetimes, so the signature is resolved as
// `Fn(&'static Foo, &'static Bar) -> &'static Baz`.
const RESOLVED_STATIC: Fn(&Foo, &Bar) -> &Baz = ..
Traits
A trait describes an abstract interface that types can implement. This interface consists of associated items, which come in three varieties:
All traits define an implicit type parameter Self
that refers to "the type
that is implementing this interface". Traits may also contain additional type
parameters. These type parameters (including Self
) may be constrained by
other traits and so forth as usual.
Traits are implemented for specific types through separate implementations.
Associated functions and methods
Associated functions whose first parameter is named self
are called methods
and may be invoked using .
notation (e.g., x.foo()
) as well as the usual
function call notation (foo(x)
).
Consider the following trait:
# #![allow(unused_variables)] #fn main() { # type Surface = i32; # type BoundingBox = i32; trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; } #}
This defines a trait with two methods. All values that have implementations
of this trait in scope can have their draw
and bounding_box
methods called,
using value.bounding_box()
syntax. Note that &self
is short for self: &Self
, and similarly, self
is short for self: Self
and &mut self
is
short for self: &mut Self
.
Traits can include default implementations of methods, as in:
# #![allow(unused_variables)] #fn main() { trait Foo { fn bar(&self); fn baz(&self) { println!("We called baz."); } } #}
Here the baz
method has a default implementation, so types that implement
Foo
need only implement bar
. It is also possible for implementing types to
override a method that has a default implementation.
Type parameters can be specified for a trait to make it generic. These appear after the trait name, using the same syntax used in generic functions.
# #![allow(unused_variables)] #fn main() { trait Seq<T> { fn len(&self) -> u32; fn elt_at(&self, n: u32) -> T; fn iter<F>(&self, F) where F: Fn(T); } #}
Associated functions may lack a self
argument, sometimes called 'static
methods'. This means that they can only be called with function call syntax
(f(x)
) and not method call syntax (obj.f()
). The way to refer to the name
of a static method is to qualify it with the trait name or type name, treating
the trait name like a module. For example:
# #![allow(unused_variables)] #fn main() { trait Num { fn from_i32(n: i32) -> Self; } impl Num for f64 { fn from_i32(n: i32) -> f64 { n as f64 } } let x: f64 = Num::from_i32(42); let x: f64 = f64::from_i32(42); #}
Associated Types
It is also possible to define associated types for a trait. Consider the
following example of a Container
trait. Notice how the type is available for
use in the method signatures:
# #![allow(unused_variables)] #fn main() { trait Container { type E; fn empty() -> Self; fn insert(&mut self, Self::E); } #}
In order for a type to implement this trait, it must not only provide
implementations for every method, but it must specify the type E
. Here's an
implementation of Container
for the standard library type Vec
:
# #![allow(unused_variables)] #fn main() { # trait Container { # type E; # fn empty() -> Self; # fn insert(&mut self, Self::E); # } impl<T> Container for Vec<T> { type E = T; fn empty() -> Vec<T> { Vec::new() } fn insert(&mut self, x: T) { self.push(x); } } #}
Associated Constants
A trait can define constants like this:
trait Foo { const ID: i32; } impl Foo for i32 { const ID: i32 = 1; } fn main() { assert_eq!(1, i32::ID); }
Any implementor of Foo
will have to define ID
. Without the definition:
# #![allow(unused_variables)] #fn main() { trait Foo { const ID: i32; } impl Foo for i32 { } #}
gives
error: not all trait items implemented, missing: `ID` [E0046]
impl Foo for i32 {
}
A default value can be implemented as well:
trait Foo { const ID: i32 = 1; } impl Foo for i32 { } impl Foo for i64 { const ID: i32 = 5; } fn main() { assert_eq!(1, i32::ID); assert_eq!(5, i64::ID); }
As you can see, when implementing Foo
, you can leave it unimplemented, as
with i32
. It will then use the default value. But, as in i64
, we can also
add our own definition.
Associated constants don’t have to be associated with a trait. An impl
block
for a struct
or an enum
works fine too:
# #![allow(unused_variables)] #fn main() { struct Foo; impl Foo { const FOO: u32 = 3; } #}
Trait bounds
Generic functions may use traits as bounds on their type parameters. This will have three effects:
- Only types that have the trait may instantiate the parameter.
- Within the generic function, the methods of the trait can be called on values that have the parameter's type. Associated types can be used in the function's signature, and associated constants can be used in expressions within the function body.
- Generic functions and types with the same or weaker bounds can use the generic type in the function body or signature.
For example:
# #![allow(unused_variables)] #fn main() { # type Surface = i32; # trait Shape { fn draw(&self, Surface); } struct Figure<S: Shape>(S, S); fn draw_twice<T: Shape>(surface: Surface, sh: T) { sh.draw(surface); sh.draw(surface); } fn draw_figure<U: Shape>(surface: Surface, Figure(sh1, sh2): Figure<U>) { sh1.draw(surface); draw_twice(surface, sh2); // Can call this since U: Shape } #}
Trait objects
Traits also define a trait object with the same name as the trait. Values of
this type are created by coercing from a pointer of some specific type to a
pointer of trait type. For example, &T
could be coerced to &Shape
if T: Shape
holds (and similarly for Box<T>
). This coercion can either be implicit
or explicit. Here is an example of an explicit coercion:
# #![allow(unused_variables)] #fn main() { trait Shape { } impl Shape for i32 { } let mycircle = 0i32; let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>; #}
The resulting value is a box containing the value that was cast, along with information that identifies the methods of the implementation that was used. Values with a trait type can have methods called on them, for any method in the trait, and can be used to instantiate type parameters that are bounded by the trait.
Supertraits
Trait bounds on Self
are considered "supertraits". These are required to be
acyclic. Supertraits are somewhat different from other constraints in that
they affect what methods are available in the vtable when the trait is used as
a trait object. Consider the following example:
# #![allow(unused_variables)] #fn main() { trait Shape { fn area(&self) -> f64; } trait Circle : Shape { fn radius(&self) -> f64; } #}
The syntax Circle : Shape
means that types that implement Circle
must also
have an implementation for Shape
. Multiple supertraits are separated by +
,
trait Circle : Shape + PartialEq { }
. In an implementation of Circle
for a
given type T
, methods can refer to Shape
methods, since the typechecker
checks that any type with an implementation of Circle
also has an
implementation of Shape
:
# #![allow(unused_variables)] #fn main() { struct Foo; trait Shape { fn area(&self) -> f64; } trait Circle : Shape { fn radius(&self) -> f64; } impl Shape for Foo { fn area(&self) -> f64 { 0.0 } } impl Circle for Foo { fn radius(&self) -> f64 { println!("calling area: {}", self.area()); 0.0 } } let c = Foo; c.radius(); #}
In type-parameterized functions, methods of the supertrait may be called on
values of subtrait-bound type parameters. Referring to the previous example of
trait Circle : Shape
:
# #![allow(unused_variables)] #fn main() { # trait Shape { fn area(&self) -> f64; } # trait Circle : Shape { fn radius(&self) -> f64; } fn radius_times_area<T: Circle>(c: T) -> f64 { // `c` is both a Circle and a Shape c.radius() * c.area() } #}
Likewise, supertrait methods may also be called on trait objects.
# #![allow(unused_variables)] #fn main() { # trait Shape { fn area(&self) -> f64; } # trait Circle : Shape { fn radius(&self) -> f64; } # impl Shape for i32 { fn area(&self) -> f64 { 0.0 } } # impl Circle for i32 { fn radius(&self) -> f64 { 0.0 } } # let mycircle = 0i32; let mycircle = Box::new(mycircle) as Box<Circle>; let nonsense = mycircle.radius() * mycircle.area(); #}
Implementations
An implementation is an item that can implement a trait for a specific type.
Implementations are defined with the keyword impl
.
# #![allow(unused_variables)] #fn main() { # #[derive(Copy, Clone)] # struct Point {x: f64, y: f64}; # type Surface = i32; # struct BoundingBox {x: f64, y: f64, width: f64, height: f64}; # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; } # fn do_draw_circle(s: Surface, c: Circle) { } struct Circle { radius: f64, center: Point, } impl Copy for Circle {} impl Clone for Circle { fn clone(&self) -> Circle { *self } } impl Shape for Circle { fn draw(&self, s: Surface) { do_draw_circle(s, *self); } fn bounding_box(&self) -> BoundingBox { let r = self.radius; BoundingBox { x: self.center.x - r, y: self.center.y - r, width: 2.0 * r, height: 2.0 * r, } } } #}
It is possible to define an implementation without referring to a trait. The
methods in such an implementation can only be used as direct calls on the
values of the type that the implementation targets. In such an implementation,
the trait type and for
after impl
are omitted. Such implementations are
limited to nominal types (enums, structs, unions, trait objects), and the
implementation must appear in the same crate as the Self
type:
# #![allow(unused_variables)] #fn main() { struct Point {x: i32, y: i32} impl Point { fn log(&self) { println!("Point is at ({}, {})", self.x, self.y); } } let my_point = Point {x: 10, y:11}; my_point.log(); #}
When a trait is specified in an impl
, all methods declared as part of the
trait must be implemented, with matching types and type parameter counts.
An implementation can take type and lifetime parameters, which can be used in
the rest of the implementation. Type parameters declared for an implementation
must be used at least once in either the trait or the type of an
implementation. Implementation parameters are written after the impl
keyword.
# #![allow(unused_variables)] #fn main() { # trait Seq<T> { fn dummy(&self, _: T) { } } impl<T> Seq<T> for Vec<T> { /* ... */ } impl Seq<bool> for u32 { /* Treat the integer as a sequence of bits */ } #}
External blocks
External blocks form the basis for Rust's foreign function interface. Declarations in an external block describe symbols in external, non-Rust libraries.
Functions within external blocks are declared in the same way as other Rust functions, with the exception that they may not have a body and are instead terminated by a semicolon.
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.
Functions within external blocks may be variadic by specifying ...
after one
or more named arguments in the argument list:
extern {
fn foo(x: i32, ...);
}
A number of attributes control the behavior of external blocks.
By default external blocks assume that the library they are calling uses the
standard C ABI on the specific platform. Other ABIs may be specified using an
abi
string, as shown here:
// Interface to the Windows API
extern "stdcall" { }
There are three ABI strings which are cross-platform, and which all compilers are guaranteed to support:
extern "Rust"
-- The default ABI when you write a normalfn foo()
in any Rust code.extern "C"
-- This is the same asextern fn foo()
; whatever the default your C compiler supports.extern "system"
-- Usually the same asextern "C"
, except on Win32, in which case it's"stdcall"
, or what you should use to link to the Windows API itself
There are also some platform-specific ABI strings:
extern "cdecl"
-- The default for x86_32 C code.extern "stdcall"
-- The default for the Win32 API on x86_32.extern "win64"
-- The default for C code on x86_64 Windows.extern "sysv64"
-- The default for C code on non-Windows x86_64.extern "aapcs"
-- The default for ARM.extern "fastcall"
-- Thefastcall
ABI -- corresponds to MSVC's__fastcall
and GCC and clang's__attribute__((fastcall))
extern "vectorcall"
-- Thevectorcall
ABI -- corresponds to MSVC's__vectorcall
and clang's__attribute__((vectorcall))
Finally, there are some rustc-specific ABI strings:
extern "rust-intrinsic"
-- The ABI of rustc intrinsics.extern "rust-call"
-- The ABI of the Fn::call trait functions.extern "platform-intrinsic"
-- Specific platform intrinsics -- like, for example,sqrt
-- have this ABI. You should never have to deal with it.
The link
attribute allows the name of the library to be specified. When
specified the compiler will attempt to link against the native library of the
specified name.
#[link(name = "crypto")]
extern { }
The type of a function declared in an extern block is extern "abi" fn(A1, ..., An) -> R
, where A1...An
are the declared types of its arguments and R
is
the declared return type.
It is valid to add the link
attribute on an empty extern block. You can use
this to satisfy the linking requirements of extern blocks elsewhere in your
code (including upstream crates) instead of adding the attribute to each extern
block.
Visibility and Privacy
Syntax
Visibility :
EMPTY
|pub
|pub
(
crate
)
|pub
(
in
ModulePath)
|pub
(
in
?self
)
|pub
(
in
?super
)
These two terms are often used interchangeably, and what they are attempting to convey is the answer to the question "Can this item be used at this location?"
Rust's name resolution operates on a global hierarchy of namespaces. Each level in the hierarchy can be thought of as some item. The items are one of those mentioned above, but also include external crates. Declaring or defining a new module can be thought of as inserting a new tree into the hierarchy at the location of the definition.
To control whether interfaces can be used across modules, Rust checks each use of an item to see whether it should be allowed or not. This is where privacy warnings are generated, or otherwise "you used a private item of another module and weren't allowed to."
By default, everything in Rust is private, with two exceptions: Associated
items in a pub
Trait are public by default; Enum variants
in a pub
enum are also public by default. When an item is declared as pub
,
it can be thought of as being accessible to the outside world. For example:
# fn main() {} // Declare a private struct struct Foo; // Declare a public struct with a private field pub struct Bar { field: i32, } // Declare a public enum with two public variants pub enum State { PubliclyAccessibleState, PubliclyAccessibleState2, }
With the notion of an item being either public or private, Rust allows item accesses in two cases:
- If an item is public, then it can be accessed externally from some module
m
if you can access all the item's parent modules fromm
. You can also potentially be able to name the item through re-exports. See below. - If an item is private, it may be accessed by the current module and its descendants.
These two cases are surprisingly powerful for creating module hierarchies exposing public APIs while hiding internal implementation details. To help explain, here's a few use cases and what they would entail:
-
A library developer needs to expose functionality to crates which link against their library. As a consequence of the first case, this means that anything which is usable externally must be
pub
from the root down to the destination item. Any private item in the chain will disallow external accesses. -
A crate needs a global available "helper module" to itself, but it doesn't want to expose the helper module as a public API. To accomplish this, the root of the crate's hierarchy would have a private module which then internally has a "public API". Because the entire crate is a descendant of the root, then the entire local crate can access this private module through the second case.
-
When writing unit tests for a module, it's often a common idiom to have an immediate child of the module to-be-tested named
mod test
. This module could access any items of the parent module through the second case, meaning that internal implementation details could also be seamlessly tested from the child module.
In the second case, it mentions that a private item "can be accessed" by the current module and its descendants, but the exact meaning of accessing an item depends on what the item is. Accessing a module, for example, would mean looking inside of it (to import more items). On the other hand, accessing a function would mean that it is invoked. Additionally, path expressions and import statements are considered to access an item in the sense that the import/expression is only valid if the destination is in the current visibility scope.
Here's an example of a program which exemplifies the three cases outlined above:
// This module is private, meaning that no external crate can access this // module. Because it is private at the root of this current crate, however, any // module in the crate may access any publicly visible item in this module. mod crate_helper_module { // This function can be used by anything in the current crate pub fn crate_helper() {} // This function *cannot* be used by anything else in the crate. It is not // publicly visible outside of the `crate_helper_module`, so only this // current module and its descendants may access it. fn implementation_detail() {} } // This function is "public to the root" meaning that it's available to external // crates linking against this one. pub fn public_api() {} // Similarly to 'public_api', this module is public so external crates may look // inside of it. pub mod submodule { use crate_helper_module; pub fn my_method() { // Any item in the local crate may invoke the helper module's public // interface through a combination of the two rules above. crate_helper_module::crate_helper(); } // This function is hidden to any module which is not a descendant of // `submodule` fn my_implementation() {} #[cfg(test)] mod test { #[test] fn test_my_implementation() { // Because this module is a descendant of `submodule`, it's allowed // to access private items inside of `submodule` without a privacy // violation. super::my_implementation(); } } } # fn main() {}
For a Rust program to pass the privacy checking pass, all paths must be valid accesses given the two rules above. This includes all use statements, expressions, types, etc.
pub(in path)
, pub(crate)
, pub(super)
, and pub(self)
In addition to public and private, Rust allows users to declare an item as
visible within a given scope. The rules for pub
restrictions are as follows:
pub(in path)
makes an item visible within the providedpath
.path
must be a parent module of the item whose visibility is being declared.pub(crate)
makes an item visible within the current crate.pub(super)
makes an item visible to the parent module. This equivalent topub(in super)
.pub(self)
makes an item visible to the current module. This is equivalent topub(in self)
.
Here's an example:
pub mod outer_mod { pub mod inner_mod { // This function is visible within `outer_mod` pub(in outer_mod) fn outer_mod_visible_fn() {} // This function is visible to the entire crate pub(crate) fn crate_visible_fn() {} // This function is visible within `outer_mod` pub(super) fn super_mod_visible_fn() { // This function is visible since we're in the same `mod` inner_mod_visible_fn(); } // This function is visible pub(self) fn inner_mod_visible_fn() {} } pub fn foo() { inner_mod::outer_mod_visible_fn(); inner_mod::crate_visible_fn(); inner_mod::super_mod_visible_fn(); // This function is no longer visible since we're outside of `inner_mod` // Error! `inner_mod_visible_fn` is private //inner_mod::inner_mod_visible_fn(); } } fn bar() { // This function is still visible since we're in the same crate outer_mod::inner_mod::crate_visible_fn(); // This function is no longer visible since we're outside of `outer_mod` // Error! `super_mod_visible_fn` is private //outer_mod::inner_mod::super_mod_visible_fn(); // This function is no longer visible since we're outside of `outer_mod` // Error! `outer_mod_visible_fn` is private //outer_mod::inner_mod::outer_mod_visible_fn(); outer_mod::foo(); } fn main() { bar() }
Re-exporting and Visibility
Rust allows publicly re-exporting items through a pub use
directive. Because
this is a public directive, this allows the item to be used in the current
module through the rules above. It essentially allows public access into the
re-exported item. For example, this program is valid:
pub use self::implementation::api; mod implementation { pub mod api { pub fn f() {} } } # fn main() {}
This means that any external crate referencing implementation::api::f
would
receive a privacy violation, while the path api::f
would be allowed.
When re-exporting a private item, it can be thought of as allowing the "privacy chain" being short-circuited through the reexport instead of passing through the namespace hierarchy as it normally would.
Attributes
Syntax
Attribute :
InnerAttribute | OuterAttributeInnerAttribute :
#![
MetaItem]
OuterAttribute :
#[
MetaItem]
MetaItem :
IDENTIFIER
| IDENTIFIER=
LITERAL
| IDENTIFIER(
MetaSeq)
| IDENTIFIER(
MetaSeq,
)
MetaSeq :
EMPTY
| MetaItem
| MetaSeq,
MetaItem
Any item declaration may have an attribute applied to it. Attributes in Rust are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334 (C#). An attribute is a general, free-form metadatum that is interpreted according to name, convention, and language and compiler version. Attributes may appear as any of:
- A single identifier, the attribute name
- An identifier followed by the equals sign '=' and a literal, providing a key/value pair
- An identifier followed by a parenthesized list of sub-attribute arguments
Attributes with a bang ("!") after the hash ("#") apply to the item that the attribute is declared within. Attributes that do not have a bang after the hash apply to the item that follows the attribute.
An example of attributes:
# #![allow(unused_variables)] #fn main() { // General metadata applied to the enclosing module or crate. #![crate_type = "lib"] // A function marked as a unit test #[test] fn test_foo() { /* ... */ } // A conditionally-compiled module #[cfg(target_os = "linux")] mod bar { /* ... */ } // A lint attribute used to suppress a warning/error #[allow(non_camel_case_types)] type int8_t = i8; #}
Note: At some point in the future, the compiler will distinguish between language-reserved and user-available attributes. Until then, there is effectively no difference between an attribute handled by a loadable syntax extension and the compiler.
Crate-only attributes
crate_name
- specify the crate's crate name.crate_type
- see linkage.feature
- see compiler features.no_builtins
- disable optimizing certain code patterns to invocations of library functions that are assumed to existno_main
- disable emitting themain
symbol. Useful when some other object being linked to definesmain
.no_start
- disable linking to thenative
crate, which specifies the "start" language item.no_std
- disable linking to thestd
crate.plugin
- load a list of named crates as compiler plugins, e.g.#![plugin(foo, bar)]
. Optional arguments for each plugin, i.e.#![plugin(foo(... args ...))]
, are provided to the plugin's registrar function. Theplugin
feature gate is required to use this attribute.recursion_limit
- Sets the maximum depth for potentially infinitely-recursive compile-time operations like auto-dereference or macro expansion. The default is#![recursion_limit="64"]
.windows_subsystem
- Indicates that when this crate is linked for a Windows target it will configure the resulting binary's subsystem via the linker. Valid values for this attribute areconsole
andwindows
, corresponding to those two respective subsystems. More subsystems may be allowed in the future, and this attribute is ignored on non-Windows targets.
Module-only attributes
no_implicit_prelude
- disable injectinguse std::prelude::*
in this module.path
- specifies the file to load the module from.#[path="foo.rs"] mod bar;
is equivalent tomod bar { /* contents of foo.rs */ }
. The path is taken relative to the directory that the current module is in.
Function-only attributes
main
- indicates that this function should be passed to the entry point, rather than the function in the crate root namedmain
.plugin_registrar
- mark this function as the registration point for [compiler plugins][plugin], such as loadable syntax extensions.start
- indicates that this function should be used as the entry point, overriding the "start" language item. See the "start" language item for more details.test
- indicates that this function is a test function, to only be compiled in case of--test
.ignore
- indicates that this test function is disabled.
should_panic
- indicates that this test function should panic, inverting the success condition.cold
- The function is unlikely to be executed, so optimize it (and calls to it) differently.naked
- The function utilizes a custom ABI or custom inline ASM that requires epilogue and prologue to be skipped.
Static-only attributes
thread_local
- on astatic mut
, this signals that the value of this static may change depending on the current thread. The exact consequences of this are implementation-defined.
FFI attributes
On an extern
block, the following attributes are interpreted:
link_args
- specify arguments to the linker, rather than just the library name and type. This is feature gated and the exact behavior is implementation-defined (due to variety of linker invocation syntax).link
- indicate that a native library should be linked to for the declarations in this block to be linked correctly.link
supports an optionalkind
key with three possible values:dylib
,static
, andframework
. See external blocks for more about external blocks. Two examples:#[link(name = "readline")]
and#[link(name = "CoreFoundation", kind = "framework")]
.linked_from
- indicates what native library this block of FFI items is coming from. This attribute is of the form#[linked_from = "foo"]
wherefoo
is the name of a library in either#[link]
or a-l
flag. This attribute is currently required to export symbols from a Rust dynamic library on Windows, and it is feature gated behind thelinked_from
feature.
On declarations inside an extern
block, the following attributes are
interpreted:
link_name
- the name of the symbol that this function or static should be imported as.linkage
- on a static, this specifies the linkage type.
On enum
s:
repr
- on C-like enums, this sets the underlying type used for representation. Takes one argument, which is the primitive type this enum should be represented for, orC
, which specifies that it should be the defaultenum
size of the C ABI for that platform. Note that enum representation in C is undefined, and this may be incorrect when the C code is compiled with certain flags.
On struct
s:
repr
- specifies the representation to use for this struct. Takes a list of options. The currently accepted ones areC
andpacked
, which may be combined.C
will use a C ABI compatible struct layout, andpacked
will remove any padding between fields (note that this is very fragile and may break platforms which require aligned access).
Macro-related attributes
-
macro_use
on amod
— macros defined in this module will be visible in the module's parent, after this module has been included. -
macro_use
on anextern crate
— load macros from this crate. An optional list of names#[macro_use(foo, bar)]
restricts the import to just those macros named. Theextern crate
must appear at the crate root, not insidemod
, which ensures proper function of the$crate
macro variable. -
macro_reexport
on anextern crate
— re-export the named macros. -
macro_export
- export a macro for cross-crate usage. -
no_link
on anextern crate
— even if we load this crate for macros, don't link it into the output.
See the macros section of the book for more information on macro scope.
Miscellaneous attributes
deprecated
- mark the item as deprecated; the full attribute is#[deprecated(since = "crate version", note = "...")
, where both arguments are optional.export_name
- on statics and functions, this determines the name of the exported symbol.link_section
- on statics and functions, this specifies the section of the object file that this item's contents will be placed into.no_mangle
- on any item, do not apply the standard name mangling. Set the symbol for this item to its identifier.simd
- on certain tuple structs, derive the arithmetic operators, which lower to the target's SIMD instructions, if any; thesimd
feature gate is necessary to use this attribute.unsafe_destructor_blind_to_params
- onDrop::drop
method, asserts that the destructor code (and all potential specializations of that code) will never attempt to read from nor write to any references with lifetimes that come in via generic parameters. This is a constraint we cannot currently express via the type system, and therefore we rely on the programmer to assert that it holds. Adding this to a Drop impl causes the associated destructor to be considered "uninteresting" by the Drop-Check rule, and thus it can help sidestep data ordering constraints that would otherwise be introduced by the Drop-Check rule. Such sidestepping of the constraints, if done incorrectly, can lead to undefined behavior (in the form of reading or writing to data outside of its dynamic extent), and thus this attribute has the word "unsafe" in its name. To use this, theunsafe_destructor_blind_to_params
feature gate must be enabled.doc
- Doc comments such as/// foo
are equivalent to#[doc = "foo"]
.rustc_on_unimplemented
- Write a custom note to be shown along with the error when the trait is found to be unimplemented on a type. You may use format arguments like{T}
,{A}
to correspond to the types at the point of use corresponding to the type parameters of the trait of the same name.{Self}
will be replaced with the type that is supposed to implement the trait but doesn't. You can also use the trait's name which will be replaced with the full path for the trait, for example for the traitFoo
in moduleBar
,{Foo}
can be used and will show up asBar::Foo
. To use this, theon_unimplemented
feature gate must be enabled.must_use
- on structs and enums, will warn if a value of this type isn't used or assigned to a variable. You may also include an optional message by using#[must_use = "message"]
which will be given alongside the warning.
Conditional compilation
Sometimes one wants to have different compiler outputs from the same code, depending on build target, such as targeted operating system, or to enable release builds.
Configuration options are boolean (on or off) and are named either with a
single identifier (e.g. foo
) or an identifier and a string (e.g. foo = "bar"
;
the quotes are required and spaces around the =
are unimportant). Note that
similarly-named options, such as foo
, foo="bar"
and foo="baz"
may each be set
or unset independently.
Configuration options are either provided by the compiler or passed in on the
command line using --cfg
(e.g. rustc main.rs --cfg foo --cfg 'bar="baz"'
).
Rust code then checks for their presence using the #[cfg(...)]
attribute:
# #![allow(unused_variables)] #fn main() { // The function is only included in the build when compiling for macOS #[cfg(target_os = "macos")] fn macos_only() { // ... } // This function is only included when either foo or bar is defined #[cfg(any(foo, bar))] fn needs_foo_or_bar() { // ... } // This function is only included when compiling for a unixish OS with a 32-bit // architecture #[cfg(all(unix, target_pointer_width = "32"))] fn on_32bit_unix() { // ... } // This function is only included when foo is not defined #[cfg(not(foo))] fn needs_not_foo() { // ... } #}
This illustrates some conditional compilation can be achieved using the
#[cfg(...)]
attribute. any
, all
and not
can be used to assemble
arbitrarily complex configurations through nesting.
The following configurations must be defined by the implementation:
target_arch = "..."
- Target CPU architecture, such as"x86"
,"x86_64"
"mips"
,"powerpc"
,"powerpc64"
,"arm"
, or"aarch64"
. This value is closely related to the first element of the platform target triple, though it is not identical.target_os = "..."
- Operating system of the target, examples include"windows"
,"macos"
,"ios"
,"linux"
,"android"
,"freebsd"
,"dragonfly"
,"bitrig"
,"openbsd"
or"netbsd"
. This value is closely related to the second and third element of the platform target triple, though it is not identical.target_family = "..."
- Operating system family of the target, e. g."unix"
or"windows"
. The value of this configuration option is defined as a configuration itself, likeunix
orwindows
.unix
- Seetarget_family
.windows
- Seetarget_family
.target_env = ".."
- Further disambiguates the target platform with information about the ABI/libc. Presently this value is either"gnu"
,"msvc"
,"musl"
, or the empty string. For historical reasons this value has only been defined as non-empty when needed for disambiguation. Thus on many GNU platforms this value will be empty. This value is closely related to the fourth element of the platform target triple, though it is not identical. For example, embedded ABIs such asgnueabihf
will simply definetarget_env
as"gnu"
.target_endian = "..."
- Endianness of the target CPU, either"little"
or"big"
.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 64-bit pointers.target_has_atomic = "..."
- Set of integer sizes on which the target can perform atomic operations. Values are"8"
,"16"
,"32"
,"64"
and"ptr"
.target_vendor = "..."
- Vendor of the target, for exampleapple
,pc
, or simply"unknown"
.test
- Enabled when compiling the test harness (using the--test
flag).debug_assertions
- Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library'sdebug_assert!
macro.
You can also set another attribute based on a cfg
variable with cfg_attr
:
#[cfg_attr(a, b)]
This is the same as #[b]
if a
is set by cfg
, and nothing otherwise.
Lastly, configuration options can be used in expressions by invoking the cfg!
macro: cfg!(a)
evaluates to true
if a
is set, and false
otherwise.
Lint check attributes
A lint check names a potentially undesirable coding pattern, such as unreachable code or omitted documentation, for the static entity to which the attribute applies.
For any lint check C
:
allow(C)
overrides the check forC
so that violations will go unreported,deny(C)
signals an error after encountering a violation ofC
,forbid(C)
is the same asdeny(C)
, but also forbids changing the lint level afterwards,warn(C)
warns about violations ofC
but continues compilation.
The lint checks supported by the compiler can be found via rustc -W help
,
along with their default settings. Compiler
plugins can provide additional lint checks.
pub mod m1 {
// Missing documentation is ignored here
#[allow(missing_docs)]
pub fn undocumented_one() -> i32 { 1 }
// Missing documentation signals a warning here
#[warn(missing_docs)]
pub fn undocumented_too() -> i32 { 2 }
// Missing documentation signals an error here
#[deny(missing_docs)]
pub fn undocumented_end() -> i32 { 3 }
}
This example shows how one can use allow
and warn
to toggle a particular
check on and off:
# #![allow(unused_variables)] #fn main() { #[warn(missing_docs)] pub mod m2{ #[allow(missing_docs)] pub mod nested { // Missing documentation is ignored here pub fn undocumented_one() -> i32 { 1 } // Missing documentation signals a warning here, // despite the allow above. #[warn(missing_docs)] pub fn undocumented_two() -> i32 { 2 } } // Missing documentation signals a warning here pub fn undocumented_too() -> i32 { 3 } } #}
This example shows how one can use forbid
to disallow uses of allow
for
that lint check:
#[forbid(missing_docs)]
pub mod m3 {
// Attempting to toggle warning signals an error here
#[allow(missing_docs)]
/// Returns 2.
pub fn undocumented_too() -> i32 { 2 }
}
Language items
Some primitive Rust operations are defined in Rust code, rather than being
implemented directly in C or assembly language. The definitions of these
operations have to be easy for the compiler to find. The lang
attribute
makes it possible to declare these operations. For example, the str
module
in the Rust standard library defines the string equality function:
#[lang = "str_eq"]
pub fn eq_slice(a: &str, b: &str) -> bool {
// details elided
}
The name str_eq
has a special meaning to the Rust compiler, and the presence
of this definition means that it will use this definition when generating calls
to the string equality function.
The set of language items is currently considered unstable. A complete list of the built-in language items will be added in the future.
Inline attributes
The inline attribute suggests that the compiler should place a copy of the function or static in the caller, rather than generating code to call the function or access the static where it is defined.
The compiler automatically inlines functions based on internal heuristics. Incorrectly inlining functions can actually make the program slower, so it should be used with care.
#[inline]
and #[inline(always)]
always cause the function to be serialized
into the crate metadata to allow cross-crate inlining.
There are three different types of inline attributes:
#[inline]
hints the compiler to perform an inline expansion.#[inline(always)]
asks the compiler to always perform an inline expansion.#[inline(never)]
asks the compiler to never perform an inline expansion.
derive
The derive
attribute allows certain traits to be automatically implemented
for data structures. For example, the following will create an impl
for the
PartialEq
and Clone
traits for Foo
, the type parameter T
will be given
the PartialEq
or Clone
constraints for the appropriate impl
:
# #![allow(unused_variables)] #fn main() { #[derive(PartialEq, Clone)] struct Foo<T> { a: i32, b: T, } #}
The generated impl
for PartialEq
is equivalent to
# #![allow(unused_variables)] #fn main() { # struct Foo<T> { a: i32, b: T } impl<T: PartialEq> PartialEq for Foo<T> { fn eq(&self, other: &Foo<T>) -> bool { self.a == other.a && self.b == other.b } fn ne(&self, other: &Foo<T>) -> bool { self.a != other.a || self.b != other.b } } #}
You can implement derive
for your own type through procedural
macros.
Compiler Features
Certain aspects of Rust may be implemented in the compiler, but they're not necessarily ready for every-day use. These features are often of "prototype quality" or "almost production ready", but may not be stable enough to be considered a full-fledged language feature.
For this reason, Rust recognizes a special crate-level attribute of the form:
#![feature(feature1, feature2, feature3)]
This directive informs the compiler that the feature list: feature1
,
feature2
, and feature3
should all be enabled. This is only recognized at a
crate-level, not at a module-level. Without this directive, all features are
considered off, and using the features will result in a compiler error.
The currently implemented features of the reference compiler are documented in The Unstable Book.
If a feature is promoted to a language feature, then all existing programs will
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
necessary, and it's likely that existing code will break if the feature isn't
removed.
If an unknown feature is found in a directive, it results in a compiler error. An unknown feature is one which has never been recognized by the compiler.
Statements and expressions
Rust is primarily an expression language. This means that most forms of value-producing or effect-causing evaluation are directed by the uniform syntax category of expressions. Each kind of expression can typically nest within each other kind of expression, and rules for evaluation of expressions involve specifying both the value produced by the expression and the order in which its sub-expressions are themselves evaluated.
In contrast, statements in Rust serve mostly to contain and explicitly sequence expression evaluation.
Statements
A statement is a component of a block, which is in turn a component of an outer expression or function.
Rust has two kinds of statement: declaration statements and expression statements.
Declaration statements
A declaration statement is one that introduces one or more names into the enclosing statement block. The declared names may denote new variables or new items.
Item declarations
An item declaration statement has a syntactic form identical to an item declaration within a module. Declaring an item — a function, enumeration, struct, type, static, trait, implementation or module — locally within a statement block is simply a way of restricting its scope to a narrow region containing all of its uses; it is otherwise identical in meaning to declaring the item outside the statement block.
Note: there is no implicit capture of the function's dynamic environment when declaring a function-local item.
let
statements
A let
statement introduces a new set of variables, 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 variables introduced by a variable declaration are visible from the point of
declaration until the end of the enclosing block scope.
Expression statements
An expression statement is one that evaluates an
expression and ignores its result. As a rule, an expression
statement's purpose is to trigger the effects of evaluating its expression.
An expression that consists of only a block
expression or control flow expression,
that doesn't end a block and evaluates to ()
can also be used as an
expression statement by omitting the trailing semicolon.
# #![allow(unused_variables)] #fn main() { # let mut v = vec![1, 2, 3]; v.pop(); // Ignore the element returned from pop if v.is_empty() { v.push(5); } else { v.remove(0); } // Semicolon can be omitted. [1]; // Separate expression statement, not an indexing expression. #}
Expressions
An expression may have two roles: it always produces a value, and it may have effects (otherwise known as "side effects"). An expression evaluates to a value, and has effects during evaluation. Many expressions contain sub-expressions (operands). The meaning of each kind of expression dictates several things:
- Whether or not to evaluate the sub-expressions when evaluating the expression
- The order in which to evaluate the sub-expressions
- How to combine the sub-expressions' values to obtain the value of the expression
In this way, the structure of expressions dictates the structure of execution. Blocks are just another kind of expression, so blocks, statements, expressions, and blocks again can recursively nest inside each other to an arbitrary depth.
Lvalues and rvalues
Expressions are divided into two main categories: lvalues and rvalues. Likewise within each expression, sub-expressions may occur in lvalue context or rvalue context. The evaluation of an expression depends both on its own category and the context it occurs within.
An lvalue is an expression that represents a memory location. These expressions
are paths which refer to local variables, function and
method arguments, or static variables,
dereferences (*expr
), indexing
expressions (expr[expr]
), field
references (expr.f
) and parenthesized lvalue
expressions. All other expressions are rvalues.
The left operand of an assignment or
compound-assignment expression is an lvalue
context, as is the single operand of a unary borrow, and
the operand of any implicit borrow. The discriminant or
subject of a match expression and right side of a let
binding may be an lvalue context, if ref bindings are made, but is otherwise an
rvalue context. All other expression contexts are rvalue contexts.
Moved and copied types
When an lvalue is evaluated in an rvalue context, it denotes the value held
in that memory location. If value is of a type that implements Copy
, then
the value will be copied. In the remaining situations if the type of the value
is Sized
it may be possible to move the value. Only
the following lvalues may be moved out of:
- Variables which are not currently borrowed.
- Temporary values.
- Fields of an lvalue which can be moved out of and
doesn't implement
Drop
. - The result of dereferencing an expression with
type
Box<T>
and that can also be moved out of.
Moving out of an lvalue deinitializes that location (if it comes from a local variable), so that it can't be read from again. In all other cases, trying to use an lvalue in an rvalue context is an error.
Mutability
For an lvalue to be assigned to, mutably
borrowed, implicitly mutably borrowed
or bound to a pattern containing ref mut
it must be mutable, we call these
contexts mutable lvalue contexts, other lvalue contexts are called
immutable.
The following expressions can create mutable lvalues:
- Mutable variables, which are not currently borrowed.
- Mutable
static
items. - Temporary values.
- Fields, this evaluates the subexpression in a mutable lvalue context.
- Dereferences of a
*mut T
pointer. - Dereference of a variable, or field of a variable, with type
&mut T
. Note: this is an exception to the requirement for the next rule. - Dereferences of a type that implements
DerefMut
, this then requires that the value being dereferenced is evaluated is a mutable lvalue context. - Indexing of a type that implements
DerefMut
, this then evaluates the value being indexed (but not the index) in mutable lvalue context.
Temporary lifetimes
When using an rvalue in most lvalue contexts, a temporary unnamed lvalue is
created and used instead, if not promoted to 'static
. Promotion of an
rvalue expression to a 'static
slot occurs when the expression could be
written in a constant, borrowed, and dereferencing that borrow where the
expression was the originally written, without changing the runtime behavior.
That is, the promoted expression can be evaluated at compile-time and the
resulting value does not contain interior mutability or destructors (these
properties are determined based on the value where possible, e.g. &None
always has the type &'static Option<_>
, as it contains nothing disallowed).
Otherwise, the lifetime of temporary values is typically
- the innermost enclosing statement; the tail expression of a block is considered part of the statement that encloses the block, or
- the condition expression or the loop conditional expression if the
temporary is created in the condition expression of an
if
or anif
/else
or in the loop conditional expression of awhile
expression.
When a temporary rvalue is being created that is assigned into a let
declaration, however, the temporary is created with the lifetime of the
enclosing block instead, as using the enclosing statement (the let
declaration) would be a guaranteed error (since a pointer to the temporary
would be stored into a variable, but the temporary would be freed before the
variable could be used). The compiler uses simple syntactic rules to decide
which values are being assigned into a let
binding, and therefore deserve a
longer temporary lifetime.
Here are some examples:
let x = foo(&temp())
. The expressiontemp()
is an rvalue. As it is being borrowed, a temporary is created which will be freed after the innermost enclosing statement (thelet
declaration, in this case).let x = temp().foo()
. This is the same as the previous example, except that the value oftemp()
is being borrowed via autoref on a method-call. Here we are assuming thatfoo()
is an&self
method defined in some trait, sayFoo
. In other words, the expressiontemp().foo()
is equivalent toFoo::foo(&temp())
.let x = if foo(&temp()) {bar()} else {baz()};
. The expressiontemp()
is an rvalue. As the temporary is created in the condition expression of anif
/else
, it will be freed at the end of the condition expression (in this example before the call tobar
orbaz
is made).let x = if temp().must_run_bar {bar()} else {baz()};
. Here we assume the type oftemp()
is a struct with a boolean fieldmust_run_bar
. As the previous example, the temporary corresponding totemp()
will be freed at the end of the condition expression.while foo(&temp()) {bar();}
. The temporary containing the return value from the call totemp()
is created in the loop conditional expression. Hence it will be freed at the end of the loop conditional expression (in this example before the call tobar
if the loop body is executed).let x = &temp()
. Here, the same temporary is being assigned intox
, rather than being passed as a parameter, and hence the temporary's lifetime is considered to be the enclosing block.let x = SomeStruct { foo: &temp() }
. As in the previous case, the temporary is assigned into a struct which is then assigned into a binding, and hence it is given the lifetime of the enclosing block.let x = [ &temp() ]
. As in the previous case, the temporary is assigned into an array which is then assigned into a binding, and hence it is given the lifetime of the enclosing block.let ref x = temp()
. In this case, the temporary is created using a ref binding, but the result is the same: the lifetime is extended to the enclosing block.
Implicit Borrows
Certain expressions will treat an expression as an lvalue by implicitly
borrowing it. For example, it is possible to compare two unsized
slices for equality directly, because the
==
operator implicitly borrows it's operands:
# #![allow(unused_variables)] #fn main() { # let c = [1, 2, 3]; # let d = vec![1, 2, 3]; let a: &[i32]; let b: &[i32]; # a = &c; # b = &d; // ... *a == *b; // Equivalent form: ::std::cmp::PartialEq::eq(&*a, &*b); #}
Implicit borrows may be taken in the following expressions:
- Left operand in method-call expressions.
- Left operand in field expressions.
- Left operand in call expressions.
- Left operand in index expressions.
- Operand of the dereference (
*
) operator. - Operands of comparison operators.
- Left operands of the compound assignment.
Constant expressions
Certain types of expressions can be evaluated at compile time. These are called
constant expressions. Certain places, such as in
constants and statics,
require a constant expression, and are always evaluated at compile time. In
other places, such as in let
statements,
constant expressions may be evaluated at compile time. If errors, such as out
of bounds array access or overflow occurs,
then it is a compiler error if the value must be evaluated at compile time,
otherwise it is just a warning, but the code will most likely panic when run.
The following expressions are constant expressions, so long as any operands are also constant expressions:
- Literals.
- Paths to functions and constants. Recursively defining constants is not allowed.
- Paths to statics, so long as only their address, not their value, is used. This includes using their value indirectly through a complicated expression. *
- Tuple expressions.
- Array expressions.
- Struct expressions, where the type does not implement
Drop
. - Variant expressions, where the
enumeration type does not implement
Drop
. - Block expressions (and
unsafe
blocks) which contain only items and possibly a (constant) tail expression. - Field expressions.
- Index expressions, indexing a array or
slice with a
usize
. - Range expressions.
- Closure expressions which don't capture variables from the environment.
- Built in negation, arithmetic,
logical,
comparison or lazy
boolean operators used on integer and floating
point types,
bool
andchar
. - Shared borrow expressions.
- The dereference operator, but not to circumvent the rule on statics.
- Grouped expressions.
- Cast expressions, except pointer to address and function pointer to address casts.
* Only in static items.
Overloading Traits
Many of the following operators and expressions can also be overloaded for
other types using traits in std::ops
or std::cmp
, these traits here also
exist in core::ops
and core::cmp
with the same names.
Literal expressions
A literal expression consists of one of the literal forms described earlier. It directly describes a number, character, string, boolean value, or the unit value.
# #![allow(unused_variables)] #fn main() { (); // unit type "hello"; // string type '5'; // character type 5; // integer type #}
Path expressions
A path used as an expression context denotes either a local
variable or an item. Path expressions that resolve to local or static variables
are lvalues, other paths
are rvalues. Using a static mut
variable requires an unsafe
block.
# #![allow(unused_variables)] #fn main() { # mod globals { # pub static STATIC_VAR: i32 = 5; # pub static mut STATIC_MUT_VAR: i32 = 7; # } # let local_var = 3; local_var; globals::STATIC_VAR; unsafe { globals::STATIC_MUT_VAR }; let some_constructor = Some::<i32>; let push_integer = Vec::<i32>::push; let slice_reverse = <[i32]>::reverse; #}
Tuple expressions
Tuples are written by enclosing zero or more comma-separated expressions in parentheses. They are used to create tuple-typed values.
# #![allow(unused_variables)] #fn main() { (0.0, 4.5); ("a", 4usize, true); #}
You can disambiguate a single-element tuple from a value in parentheses with a comma:
# #![allow(unused_variables)] #fn main() { (0,); // single-element tuple (0); // zero in parentheses #}
Struct expressions
There are several forms of struct expressions. A struct expression consists of the path of a struct item, followed by a brace-enclosed list of zero or more comma-separated name-value pairs, providing the field values of a new instance of the struct. A field name can be any identifier, and is separated from its value expression by a colon. In the case of a tuple struct the field names are numbers corresponding to the position of the field. The numbers must be written in decimal, containing no underscores and with no leading zeros or integer suffix. A value of a union type can also be created using this syntax, except that it must specify exactly one field.
Struct expressions can't be used directly in the head of a loop or an
if
, if let
or
match
expression. But struct expressions can still be
in used inside parentheses, for example.
A tuple struct expression consists of the path of a struct item, followed by a parenthesized list of one or more comma-separated expressions (in other words, the path of a struct item followed by a tuple expression). The struct item must be a tuple struct item.
A unit-like struct expression consists only of the path of a struct item.
The following are examples of struct expressions:
# #![allow(unused_variables)] #fn main() { # struct Point { x: f64, y: f64 } # struct NothingInMe { } # struct TuplePoint(f64, f64); # mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } } # struct Cookie; fn some_fn<T>(t: T) {} Point {x: 10.0, y: 20.0}; NothingInMe {}; TuplePoint(10.0, 20.0); TuplePoint { 0: 10.0, 1: 20.0 }; // Results in the same value as the above line let u = game::User {name: "Joe", age: 35, score: 100_000}; some_fn::<Cookie>(Cookie); #}
A struct expression forms a new value of the named struct type. Note that for a given unit-like struct type, this will always be the same value.
A struct expression can terminate with the syntax ..
followed by an
expression to denote a functional update. The expression following ..
(the
base) must have the same struct type as the new struct type being formed. The
entire expression denotes the result of constructing a new struct (with the
same type as the base expression) with the given values for the fields that
were explicitly specified and the values in the base expression for all other
fields. Just as with all struct expressions, all of the fields of the struct
must be visible, even those not explicitly
named.
# #![allow(unused_variables)] #fn main() { # struct Point3d { x: i32, y: i32, z: i32 } let base = Point3d {x: 1, y: 2, z: 3}; Point3d {y: 0, z: 10, .. base}; #}
Struct field init shorthand
When initializing a data structure (struct, enum, union) with named (but not
numbered) fields, it is allowed to write fieldname
as a shorthand for
fieldname: fieldname
. This allows a compact syntax with less duplication.
Example:
# #![allow(unused_variables)] #fn main() { # struct Point3d { x: i32, y: i32, z: i32 } # let x = 0; # let y_value = 0; # let z = 0; Point3d { x: x, y: y_value, z: z }; Point3d { x, y: y_value, z }; #}
Enumeration Variant expressions
Enumeration variants can be constructed similarly to structs, using a path to an enum variant instead of to a struct:
# #![allow(unused_variables)] #fn main() { # enum Message { # Quit, # WriteString(String), # Move { x: i32, y: i32 }, # } let q = Message::Quit; let w = Message::WriteString("Some string".to_string()); let m = Message::Move { x: 50, y: 200 }; #}
Block expressions
A block expression is similar to a module in terms of the declarations that are possible, but can also contain statements and end with an expression. Each block conceptually introduces a new namespace scope. Use items can bring new names into scopes and declared items are in scope for only the block itself.
A block will execute each statement sequentially, and then execute the
expression (if given). If the block doesn't end in an expression, its value is
()
:
# #![allow(unused_variables)] #fn main() { let x: () = { println!("Hello."); }; #}
If it ends in an expression, its value and type are that of the expression:
# #![allow(unused_variables)] #fn main() { let x: i32 = { println!("Hello."); 5 }; assert_eq!(5, x); #}
Blocks are always rvalues and evaluate the last expression in rvalue context. This can be used to force moving a value if really needed.
unsafe
blocks
See unsafe
block for more information on when to use unsafe
A block of code can be prefixed with the unsafe
keyword, to permit calling
unsafe
functions or dereferencing raw pointers within a safe function.
Method-call expressions
A method call consists of an expression followed by a single dot, an
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 trait
object. Method call expressions will automatically
take a shared or mutable borrow of the receiver if needed.
# #![allow(unused_variables)] #fn main() { let pi: Result<f32, _> = "3.14".parse(); let log_pi = pi.unwrap_or(1.0).log(2.72); # assert!(1.14 < log_pi && log_pi < 1.15) #}
When resolving method calls on an expression of type A
, Rust will use the
following order:
- Inherent methods, with receiver of type
A
,&A
,&mut A
. - Trait methods with receiver of type
A
. - Trait methods with receiver of type
&A
. - Trait methods with receiver of type
&mut A
. - If it's possible, Rust will then repeat steps 1-5 with
<A as std::ops::Deref>::Target
, and insert a dereference operator. - If
A
is now an array type, then repeat steps 1-4 with the corresponding slice type.
Note: that in steps 1-4 the receiver is used, not the type of Self
nor the
type of A
. For example
// `Self` is `&A`, receiver is `&A`.
impl<'a> Trait for &'a A {
fn method(self) {}
}
// If `A` is `&B`, then `Self` is `B` and the receiver is `A`.
impl B {
fn method(&self) {}
}
Another note: this process does not use the mutability or lifetime of the
receiver, or whether unsafe
methods can currently be called to resolve
methods. These constraints instead lead to compiler errors.
If a step is reached where there is more than one possible method (where generic methods or traits are considered the same), then it is a compiler error. These cases require a more specific syntax. for method and function invocation.
Field expressions
A field expression consists of an expression followed by a single dot and an identifier, when not immediately followed by a parenthesized expression-list (the latter is always a method call expression). A field expression denotes a field of a struct or union. To call a function stored in a struct parentheses are needed around the field expression
mystruct.myfield;
foo().x;
(Struct {a: 10, b: 20}).a;
mystruct.method(); // Method expression
(mystruct.function_field)() // Call expression containing a field expression
A field access is an lvalue referring to the location of that field. When the subexpression is mutable, the field expression is also mutable.
Also, if the type of the expression to the left of the dot is a pointer, it is automatically dereferenced as many times as necessary to make the field access possible. In cases of ambiguity, we prefer fewer autoderefs to more.
Finally the fields of a struct, a reference to a struct are treated as separate
entities when borrowing. If the struct does not implement
Drop
this also applies to moving out of each of its fields
where possible. This also does not apply if automatic dereferencing is done
though user defined types.
# #![allow(unused_variables)] #fn main() { # struct A { f1: String, f2: String, f3: String } # let mut x = A { # f1: "f1".to_string(), # f2: "f2".to_string(), # f3: "f3".to_string() # }; let a: &mut String = &mut x.f1; // x.f1 borrowed mutably let b: &String = &x.f2; // x.f2 borrowed immutably let c: &String = &x.f2; // Can borrow again let d: String = x.f3; // Move out of x.f3 #}
Tuple indexing expressions
Tuples and struct tuples can be indexed using the number corresponding to the position of the field. The index must be written as a decimal literal with no underscores or suffix. Tuple indexing expressions also differ from field expressions in that they can unambiguously be called as a function. In all other aspects they have the same behavior.
# #![allow(unused_variables)] #fn main() { # struct Point(f32, f32); let pair = (1, 2); assert_eq!(pair.1, 2); let unit_x = Point(1.0, 0.0); assert_eq!(unit_x.0, 1.0); #}
Call expressions
A call expression consists of an expression followed by a parenthesized
expression-list. It invokes a function, providing zero or more input variables.
If the function eventually returns, then the expression completes. For
non-function types, the expression f(...) uses the
method on one of the std::ops::Fn
, std::ops::FnMut
or std::ops::FnOnce
traits, which differ in whether they take the type by reference, mutable
reference, or take ownership respectively. An automatic borrow will be taken if
needed. Rust will also automatically dereference f
as required. Some examples
of call expressions:
# #![allow(unused_variables)] #fn main() { # fn add(x: i32, y: i32) -> i32 { 0 } let three: i32 = add(1i32, 2i32); let name: &'static str = (|| "Rust")(); #}
Disambiguating Function Calls
Rust treats all function calls as sugar for a more explicit, fully-qualified syntax. Upon compilation, Rust will desugar all function calls into the explicit form. Rust may sometimes require you to qualify function calls with trait, depending on the ambiguity of a call in light of in-scope items.
Note: In the past, the Rust community used the terms "Unambiguous Function Call Syntax", "Universal Function Call Syntax", or "UFCS", in documentation, issues, RFCs, and other community writings. However, the term lacks descriptive power and potentially confuses the issue at hand. We mention it here for searchability's sake.
Several situations often occur which result in ambiguities about the receiver or referent of method or associated function calls. These situations may include:
- Multiple in-scope traits define methods with the same name for the same types
- Auto-
deref
is undesirable; for example, distinguishing between methods on a smart pointer itself and the pointer's referent - Methods which take no arguments, like
default()
, and return properties of a type, likesize_of()
To resolve the ambiguity, the programmer may refer to their desired method or function using more specific paths, types, or traits.
For example,
trait Pretty { fn print(&self); } trait Ugly { fn print(&self); } struct Foo; impl Pretty for Foo { fn print(&self) {} } struct Bar; impl Pretty for Bar { fn print(&self) {} } impl Ugly for Bar{ fn print(&self) {} } fn main() { let f = Foo; let b = Bar; // we can do this because we only have one item called `print` for `Foo`s f.print(); // more explicit, and, in the case of `Foo`, not necessary Foo::print(&f); // if you're not into the whole brevity thing <Foo as Pretty>::print(&f); // b.print(); // Error: multiple 'print' found // Bar::print(&b); // Still an error: multiple `print` found // necessary because of in-scope items defining `print` <Bar as Pretty>::print(&b); }
Refer to RFC 132 for further details and motivations.
Closure expressions
A closure expression defines a closure and denotes it as a value, in a single
expression. A closure expression is a pipe-symbol-delimited (|
) list of
patterns followed by an expression. Type annotations may optionally be added
for the type of the parameters or for the return type. If there is a return
type, the expression used for the body of the closure must be a normal
block. A closure expression also may begin with the
move
keyword before the initial |
.
A closure expression denotes a function that maps a list of parameters
(ident_list
) onto the expression that follows the ident_list
. The patterns
in the ident_list
are the parameters to the closure. If a parameter's types
is not specified, then the compiler infers it from context. Each closure
expression has a unique anonymous type.
Closure expressions are most useful when passing functions as arguments to other functions, as an abbreviation for defining and capturing a separate function.
Significantly, closure expressions capture their environment, which regular
function definitions do not. Without the move
keyword, the closure expression infers how it captures each variable from its
environment, preferring to capture by shared reference, effectively borrowing
all outer variables mentioned inside the closure's body. If needed the compiler
will infer that instead mutable references should be taken, or that the values
should be moved or copied (depending on their type) from the environment. A
closure can be forced to capture its environment by copying or moving values by
prefixing it with the move
keyword. This is often used to ensure that the
closure's type is 'static
.
The compiler will determine which of the closure
traits the closure's type will implement by how it
acts on its captured variables. The closure will also implement
Send
and/or Sync
if all of
its captured types do. These traits allow functions to accept closures using
generics, even though the exact types can't be named.
In this example, we define a function ten_times
that takes a higher-order
function argument, and we then call it with a closure expression as an argument,
followed by a closure expression that moves values from its environment.
# #![allow(unused_variables)] #fn main() { fn ten_times<F>(f: F) where F: Fn(i32) { for index in 0..10 { f(index); } } ten_times(|j| println!("hello, {}", j)); // With type annotations ten_times(|j: i32| -> () { println!("hello, {}", j) }); let word = "konnichiwa".to_owned(); ten_times(move |j| println!("{}, {}", word, j)); #}
Array expressions
An array expression can be written by enclosing zero or more comma-separated expressions of uniform type in square brackets. This produces and array containing each of these values in the order they are written.
Alternatively there can be exactly two expressions inside the brackets,
separated by a semi-colon. The expression after the ;
must be a have type
usize
and be a constant expression, such as a
literal or a constant
item. [a; b]
creates an array containing b
copies of the value of a
. If the expression after the semi-colon has a value
greater than 1 then this requires that the type of a
is
Copy
.
# #![allow(unused_variables)] #fn main() { [1, 2, 3, 4]; ["a", "b", "c", "d"]; [0; 128]; // array with 128 zeros [0u8, 0u8, 0u8, 0u8]; #}
Index expressions
Array and slice-typed expressions can be
indexed by writing a square-bracket-enclosed expression (the index) after them.
When the array is mutable, the resulting
lvalue can be assigned to.
For other types an index expression a[b]
is equivalent to
*std::ops::Index::index(&a, b)
, or *std::opsIndexMut::index_mut(&mut a, b)
in a mutable lvalue context. Just as with methods, Rust will also insert
dereference operations on a
repeatedly to find an implementation.
Indices are zero-based, and are of type usize
for arrays and slices. Array
access is a constant expression, so bounds can be
checked at compile-time for constant arrays with a constant index value.
Otherwise a check will be performed at run-time that will put the thread in a
panicked state if it fails.
# #![allow(unused_variables)] #fn main() { ([1, 2, 3, 4])[2]; // Evaluates to 3 let x = (["a", "b"])[10]; // warning: const index-expr is out of bounds let n = 10; let y = (["a", "b"])[n]; // panics let arr = ["a", "b"]; arr[10]; // panics #}
Range expressions
The ..
operator will construct an object of one of the std::ops::Range
(or
core::ops::Range
) variants.
# #![allow(unused_variables)] #fn main() { 1..2; // std::ops::Range 3..; // std::ops::RangeFrom ..4; // std::ops::RangeTo ..; // std::ops::RangeFull #}
The following expressions are equivalent.
# #![allow(unused_variables)] #fn main() { let x = std::ops::Range {start: 0, end: 10}; let y = 0..10; assert_eq!(x, y); #}
Operator expressions
Operators are defined for built in types by the Rust language. Many of the
following operators can also be overloaded using traits in std::ops
or
std::cmp
.
Overflow
Integer operators will panic when they overflow when compiled in debug mode.
The -C debug-assertions
and -C overflow-checks
compiler flags can be used
to control this more directly. The following things are considered to be
overflow:
- When
+
,*
or-
create a value greater than the maximum value, or less than the minimum value that can be stored. This includes unary-
on the smallest value of any signed integer type. - Using
/
or%
, where the left-hand argument is the smallest integer of a signed integer type and the right-hand argument is-1
. - Using
<<
or>>
where the right-hand argument is greater than or equal to the number of bits in the type of the left-hand argument, or is negative.
Borrow operators
The &
(shared borrow) and &mut
(mutable borrow) operators are unary prefix
operators. When applied to an lvalue produce a reference (pointer) to the
location that the value refers to. The lvalue is also placed into a borrowed
state for the duration of the reference. For a shared borrow (&
), this
implies that the lvalue may not be mutated, but it may be read or shared again.
For a mutable borrow (&mut
), the lvalue may not be accessed in any way until
the borrow expires. &mut
evaluates its operand in a mutable lvalue context.
If the &
or &mut
operators are applied to an rvalue, a temporary value is
created; the lifetime of this temporary value is defined by syntactic
rules. These operators cannot be overloaded.
# #![allow(unused_variables)] #fn main() { { // a temporary with value 7 is created that lasts for this scope. let shared_reference = &7; } let mut array = [-2, 3, 9]; { // Mutably borrows `array` for this scope. // `array` may only be used through `mutable_reference`. let mutable_reference = &mut array; } #}
The dereference operator
The *
(dereference) operator is also a unary prefix operator. When applied to
a pointer it denotes the pointed-to location. If
the expression is of type &mut T
and *mut T
, and is either a local
variable, a (nested) field of a local variance or is a mutable lvalue, then the
resulting lvalue can be
assigned to. Dereferencing a raw pointer requires unsafe
.
On non-pointer types *x
is equivalent to *std::ops::Deref::deref(&x)
in an
immutable lvalue context and *std::ops::Deref::deref_mut(&mut x)
in a mutable lvalue context.
# #![allow(unused_variables)] #fn main() { let x = &7; assert_eq!(*x, 7); let y = &mut 9; *y = 11; assert_eq!(*y, 11); #}
The ?
operator.
The ?
("question mark") operator can be applied to values of the Result<T, E>
type to propagate errors. If applied to Err(e)
it will return
Err(From::from(e))
from the enclosing function or closure. If applied to
Ok(x)
it will unwrap the value to return x
. Unlike other unary operators
?
is written in postfix notation. ?
cannot be overloaded.
# #![allow(unused_variables)] #fn main() { # use std::num::ParseIntError; fn try_to_parse() -> Result<i32, ParseIntError> { let x: i32 = "123".parse()?; // x = 123 let y: i32 = "24a".parse()?; // returns an Err() immediately Ok(x + y) // Doesn't run. } let res = try_to_parse(); println!("{:?}", res); # assert!(res.is_err()) #}
Negation operators
These are the last two unary operators. This table summarizes the behavior of them on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two's complement. The operands of all of these operators are evaluated in rvalue context so are moved or copied.
Symbol | Integer | bool | Floating Point | Overloading Trait |
---|---|---|---|---|
- | Negation* | Negation | std::ops::Neg | |
! | Bitwise NOT | Logical NOT | std::ops::Not |
* Only for signed integer types.
Here are some example of these operators
# #![allow(unused_variables)] #fn main() { let x = 6; assert_eq!(-x, -6); assert_eq!(!x, -7); assert_eq!(true, !false); #}
Arithmetic and Logical Binary Operators
Binary operators expressions are all written with infix notation. This table summarizes the behavior of arithmetic and logical binary operators on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two's complement. The operands of all of these operators are evaluated in rvalue context so are moved or copied.
Symbol | Integer | bool | Floating Point | Overloading Trait |
---|---|---|---|---|
+ | Addition | Addition | std::ops::Add | |
- | Subtraction | Subtraction | std::ops::Sub | |
* | Multiplication | Multiplication | std::ops::Mul | |
/ | Division | Division | std::ops::Div | |
% | Remainder | Remainder | std::ops::Rem | |
& | Bitwise AND | Logical AND | std::ops::BitAnd | |
| | Bitwise OR | Logical OR | std::ops::BitOr | |
^ | Bitwise XOR | Logical XOR | std::ops::BitXor | |
<< | Left Shift | std::ops::Shl | ||
>> | Right Shift* | std::ops::Shr |
* Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.
Here are examples of these operators being used.
# #![allow(unused_variables)] #fn main() { assert_eq!(3 + 6, 9); assert_eq!(5.5 - 1.25, 4.25); assert_eq!(-5 * 14, -70); assert_eq!(14 / 3, 4); assert_eq!(100 % 7, 2); assert_eq!(0b1010 & 0b1100, 0b1000); assert_eq!(0b1010 | 0b1100, 0b1110); assert_eq!(0b1010 ^ 0b1100, 0b110); assert_eq!(13 << 3, 104); assert_eq!(-10 >> 2, -3); #}
Comparison Operators
Comparison operators are also defined both for primitive types and many type in
the standard library. Parentheses are required when chaining comparison
operators. For example, the expression a == b == c
is invalid and may be
written as (a == b) == c
.
Unlike arithmetic and logical operators, the traits for overloading the operators the traits for these operators are used more generally to show how a type may be compared and will likely be assumed to define actual comparisons by functions that use these traits as bounds. Many functions and macros in the standard library can then use that assumption (although not to ensure safety). Unlike the arithmetic and logical operators above, these operators implicitly take shared borrows of their operands, evaluating them in lvalue context:
a == b;
// is equivalent to
::std::cmp::PartialEq::eq(&a, &b);
This means that the operands don't have to be moved out of.
Symbol | Meaning | Overloading method |
---|---|---|
== | Equal | std::cmp::PartialEq::eq |
!= | Not equal | std::cmp::PartialEq::ne |
> | Greater than | std::cmp::PartialOrd::gt |
< | Less than | std::cmp::PartialOrd::lt |
>= | Greater than or equal to | std::cmp::PartialOrd::ge |
<= | Less than or equal to | std::cmp::PartialOrd::le |
Here are examples of the comparison operators being used.
# #![allow(unused_variables)] #fn main() { assert!(123 == 123); assert!(23 != -12); assert!(12.5 > 12.2); assert!([1, 2, 3] < [1, 3, 4]); assert!('A' <= 'B'); assert!("World" >= "Hello"); #}
Lazy boolean operators
The operators ||
and &&
may be applied to operands of boolean type. The
||
operator denotes logical 'or', and the &&
operator denotes logical
'and'. They differ from |
and &
in that the right-hand operand is only
evaluated when the left-hand operand does not already determine the result of
the expression. That is, ||
only evaluates its right-hand operand when the
left-hand operand evaluates to false
, and &&
only when it evaluates to
true
.
# #![allow(unused_variables)] #fn main() { let x = false || true; // true let y = false && panic!(); // false, doesn't evaluate `panic!()` #}
Type cast expressions
A type cast expression is denoted with the binary operator as
.
Executing an as
expression casts the value on the left-hand side to the type
on the right-hand side.
An example of an as
expression:
# #![allow(unused_variables)] #fn main() { # fn sum(values: &[f64]) -> f64 { 0.0 } # fn len(values: &[f64]) -> i32 { 0 } fn average(values: &[f64]) -> f64 { let sum: f64 = sum(values); let size: f64 = len(values) as f64; sum / size } #}
as
can be used to explicitly perform coercions, as
well as the following additional casts. Here *T
means either *const T
or
*mut T
.
Type of e | U | Cast performed by e as U |
---|---|---|
Integer or Float type | Integer or Float type | Numeric cast |
C-like enum | Integer type | Enum cast |
bool or char | Integer type | Primitive to integer cast |
u8 | char | u8 to char cast |
*T | *V where V: Sized * | Pointer to pointer cast |
*T where T: Sized | Numeric type | Pointer to address cast |
Integer type | *V where V: Sized | Address to pointer cast |
&[T; n] | *const T | Array to pointer cast |
Function pointer | *V where V: Sized | Function pointer to pointer cast |
Function pointer | Integer | Function pointer to address cast |
* or T
and V
are compatible unsized types, e.g., both slices, both the
same trait object.
Semantics
- Numeric cast
- Casting between two integers of the same size (e.g. i32 -> u32) is a no-op
- Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate
- Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will
- zero-extend if the source is unsigned
- sign-extend if the source is signed
- Casting from a float to an integer will round the float towards zero
- NOTE: currently this will cause Undefined Behavior if the rounded value cannot be represented by the target integer type. This includes Inf and NaN. This is a bug and will be fixed.
- Casting from an integer to float will produce the floating point representation of the integer, rounded if necessary (rounding strategy unspecified)
- Casting from an f32 to an f64 is perfect and lossless
- Casting from an f64 to an f32 will produce the closest possible value (rounding strategy unspecified)
- Enum cast
- Casts an enum to its discriminant, then uses a numeric cast if needed.
- Primitive to integer cast
false
casts to0
,true
casts to1
char
casts to the value of the code point, then uses a numeric cast if needed.
u8
tochar
cast- Casts to the
char
with the corresponding code point.
- Casts to the
Assignment expressions
An assignment expression consists of an
lvalue expression followed
by an equals sign (=
) and an
rvalue expression.
Evaluating an assignment expression either copies or moves its right-hand operand to its left-hand operand. The left-hand operand must be an lvalue: using an rvalue results in a compiler error, rather than promoting it to a temporary.
# #![allow(unused_variables)] #fn main() { # let mut x = 0; # let y = 0; x = y; #}
Compound assignment expressions
The +
, -
, *
, /
, %
, &
, |
, ^
, <<
, and >>
operators may be
composed with the =
operator. The expression lval OP= val
is equivalent to
lval = lval OP val
. For example, x = x + 1
may be written as x += 1
.
Any such expression always has the unit
type.
These operators can all be overloaded using the trait with the same name as for
the normal operation followed by 'Assign', for example, std::ops::AddAssign
is used to overload +=
. As with =
, lval
must be an lvalue.
# #![allow(unused_variables)] #fn main() { let mut x = 10; x += 4; assert_eq!(x, 14); #}
Operator precedence
The precedence of Rust operators is ordered as follows, going from strong to weak. Binary Operators at the same precedence level are evaluated in the order given by their associativity.
Operator | Associativity |
---|---|
? | |
Unary - * ! & &mut | |
as : | left to right |
* / % | left to right |
+ - | left to right |
<< >> | left to right |
& | left to right |
^ | left to right |
| | left to right |
== != < > <= >= | Require parentheses |
&& | left to right |
|| | left to right |
.. ... | Require parentheses |
<- | right to left |
= += -= *= /= %= &= |= ^= <<= >>= | right to left |
Grouped expressions
An expression enclosed in parentheses evaluates to the result of the enclosed expression. Parentheses can be used to explicitly specify evaluation order within an expression.
An example of a parenthesized expression:
# #![allow(unused_variables)] #fn main() { let x: i32 = 2 + 3 * 4; let y: i32 = (2 + 3) * 4; assert_eq!(x, 14); assert_eq!(y, 20); #}
Loops
Rust supports three loop expressions:
- A
loop
expression denotes an infinite loop. - A
while
expression loops until a predicate is false. - A
for
expression extracts values from an iterator, looping until the iterator is empty.
All three types of loop support break
expressions,
continue
expressions, and labels.
Only loop
supports evaluation to non-trivial values.
Infinite loops
A loop
expression repeats execution of its body continuously:
loop { println!("I live."); }
.
A loop
expression without an associated break
expression is
diverging, and doesn't
return anything. A loop
expression containing associated
break
expression(s)
may terminate, and must have type compatible with the value of the break
expression(s).
Predicate loops
A while
loop begins by evaluating the boolean loop conditional expression. If
the loop conditional expression evaluates to true
, the loop body block
executes, then control returns to the loop conditional expression. If the loop
conditional expression evaluates to false
, the while
expression completes.
An example:
# #![allow(unused_variables)] #fn main() { let mut i = 0; while i < 10 { println!("hello"); i = i + 1; } #}
Iterator loops
A for
expression is a syntactic construct for looping over elements provided
by an implementation of std::iter::IntoIterator
. If the iterator yields a
value, that value is given the specified name and the body of the loop is
executed, then control returns to the head of the for
loop. If the iterator
is empty, the for
expression completes.
An example of a for
loop over the contents of an array:
# #![allow(unused_variables)] #fn main() { let v = &["apples", "cake", "coffee"]; for text in v { println!("I like {}.", text); } #}
An example of a for loop over a series of integers:
# #![allow(unused_variables)] #fn main() { let mut sum = 0; for n in 1..11 { sum += n; } assert_eq!(sum, 55); #}
Loop labels
A loop expression may optionally have a label. The label is written as
a lifetime preceding the loop expression, as in 'foo: loop { break 'foo; }
,
'bar: while false {}
, 'humbug: for _ in 0..0 {}
.
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 and continue
expressions.
break
expressions
When break
is encountered, execution of the associated loop body is
immediately terminated, for example:
# #![allow(unused_variables)] #fn main() { let mut last = 0; for x in 1..100 { if x > 12 { break; } last = x; } assert_eq!(last, 12); #}
A break
expression is normally associated with the innermost loop
, for
or
while
loop enclosing the break
expression, but a label can
be used to specify which enclosing loop is affected. Example:
# #![allow(unused_variables)] #fn main() { 'outer: loop { while true { break 'outer; } } #}
A break
expression is only permitted in the body of a loop, and has one of
the forms break
, break 'label
or (see below)
break EXPR
or break 'label EXPR
.
continue
expressions
When continue
is encountered, the current iteration of the associated loop
body is immediately terminated, 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.
Like break
, continue
is normally associated with the innermost enclosing
loop, but continue 'label
may be used to specify the loop affected.
A continue
expression is only permitted in the body of a loop.
break
and loop values
When associated with a loop
, a break expression may be used to return a value
from that loop, via one of the forms break EXPR
or break 'label EXPR
, where
EXPR
is an expression whose result is returned from the loop
. For example:
# #![allow(unused_variables)] #fn main() { let (mut a, mut b) = (1, 1); let result = loop { if b > 10 { break b; } let c = a + b; a = b; b = c; }; // first number in Fibonacci sequence over 10: assert_eq!(result, 13); #}
In the case a loop
has an associated break
, it is not considered diverging,
and the loop
must have a type compatible with each break
expression.
break
without an expression is considered identical to break
with
expression ()
.
if
expressions
An if
expression is a conditional branch in program control. The form of an
if
expression is a condition expression, followed by a consequent block, any
number of else if
conditions and blocks, and an optional trailing else
block. The condition expressions must have type bool
. If a condition
expression evaluates to true
, the consequent block is executed and any
subsequent else if
or else
block is skipped. If a condition expression
evaluates to false
, the consequent block is skipped and any subsequent else if
condition is evaluated. If all if
and else if
conditions evaluate to
false
then any else
block is executed. An if expression evaluates to the
same value as the executed block, or ()
if no block is evaluated. An if
expression must have the same type in all situations.
# #![allow(unused_variables)] #fn main() { # let x = 3; if x == 4 { println!("x is four"); } else if x == 3 { println!("x is three"); } else { println!("x is something else"); } let y = if 12 * 15 > 150 { "Bigger" } else { "Smaller" }; assert_eq!(y, "Bigger"); #}
match
expressions
A match
expression branches on a pattern. The exact form of matching that
occurs depends on the pattern. Patterns consist of some combination of
literals, destructured arrays or enum constructors, structs and tuples,
variable binding specifications, wildcards (..
), and placeholders (_
). A
match
expression has a head expression, which is the value to compare to
the patterns. The type of the patterns must equal the type of the head
expression.
A match
behaves differently depending on whether or not the head expression
is an lvalue or an rvalue.
If the head expression is an rvalue, it is first evaluated into a temporary
location, and the resulting value is sequentially compared to the patterns in
the arms until a match is found. The first arm with a matching pattern is
chosen as the branch target of the match
, any variables bound by the pattern
are assigned to local variables in the arm's block, and control enters the
block.
When the head expression is an lvalue, the match does not allocate a temporary location (however, a by-value binding may copy or move from the lvalue). When possible, it is preferable to match on lvalues, as the lifetime of these matches inherits the lifetime of the lvalue, rather than being restricted to the inside of the match.
An example of a match
expression:
# #![allow(unused_variables)] #fn main() { let x = 1; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"), } #}
Patterns that bind variables default to binding to a copy or move of the
matched value (depending on the matched value's type). This can be changed to
bind to a reference by using the ref
keyword, or to a mutable reference using
ref mut
.
Patterns can be used to destructure structs, enums, and tuples. Destructuring
breaks a value up into its component pieces. The syntax used is the same as
when creating such values. When destructing a data structure with named (but
not numbered) fields, it is allowed to write fieldname
as a shorthand for
fieldname: fieldname
. In a pattern whose head expression has a struct
,
enum
or tupl
type, a placeholder (_
) stands for a single data field,
whereas a wildcard ..
stands for all the fields of a particular variant.
# #![allow(unused_variables)] #fn main() { # enum Message { # Quit, # WriteString(String), # Move { x: i32, y: i32 }, # ChangeColor(u8, u8, u8), # } # let message = Message::Quit; match message { Message::Quit => println!("Quit"), Message::WriteString(write) => println!("{}", &write), Message::Move{ x, y: 0 } => println!("move {} horizontally", x), Message::Move{ .. } => println!("other move"), Message::ChangeColor { 0: red, 1: green, 2: _ } => { println!("color change, red: {}, green: {}", red, green); } }; #}
Patterns can also dereference pointers by using the &
, &mut
and box
symbols, as appropriate. For example, these two matches on x: &i32
are
equivalent:
# #![allow(unused_variables)] #fn main() { # let x = &3; let y = match *x { 0 => "zero", _ => "some" }; let z = match x { &0 => "zero", _ => "some" }; assert_eq!(y, z); #}
Subpatterns can also be bound to variables by the use of the syntax variable @ subpattern
. For example:
# #![allow(unused_variables)] #fn main() { let x = 1; match x { e @ 1 ... 5 => println!("got a range element {}", e), _ => println!("anything"), } #}
Multiple match patterns may be joined with the |
operator. A range of values
may be specified with ...
. For example:
# #![allow(unused_variables)] #fn main() { # let x = 2; let message = match x { 0 | 1 => "not many", 2 ... 9 => "a few", _ => "lots" }; #}
Range patterns only work on scalar types (like integers and characters; not
like arrays and structs, which have sub-components). A range pattern may not be
a sub-range of another range pattern inside the same match
.
Finally, match patterns can accept pattern guards to further refine the
criteria for matching a case. Pattern guards appear after the pattern and
consist of a bool-typed expression following the if
keyword. A pattern guard
may refer to the variables bound within the pattern they follow.
# #![allow(unused_variables)] #fn main() { # let maybe_digit = Some(0); # fn process_digit(i: i32) { } # fn process_other(i: i32) { } let message = match maybe_digit { Some(x) if x < 10 => process_digit(x), Some(x) => process_other(x), None => panic!(), }; #}
if let
expressions
An if let
expression is semantically similar to an if
expression but in
place of a condition expression it expects the keyword let
followed by a
refutable pattern, an =
and an expression. If the value of the expression on
the right hand side of the =
matches the pattern, the corresponding block
will execute, otherwise flow proceeds to the following else
block if it
exists. Like if
expressions, if let
expressions have a value determined by
the block that is evaluated.
# #![allow(unused_variables)] #fn main() { let dish = ("Ham", "Eggs"); // this body will be skipped because the pattern is refuted if let ("Bacon", b) = dish { println!("Bacon is served with {}", b); } else { // This block is evaluated instead. println!("No bacon will be served"); } // this body will execute if let ("Ham", b) = dish { println!("Ham is served with {}", b); } #}
while let
loops
A while let
loop is semantically similar to a while
loop but in place of a
condition expression it expects the keyword let
followed by a refutable
pattern, an =
and an expression. If the value of the expression on the right
hand side of the =
matches the pattern, the loop body block executes then
control returns to the pattern matching statement. Otherwise, the while
expression completes.
# #![allow(unused_variables)] #fn main() { let mut x = vec![1, 2, 3]; while let Some(y) = x.pop() { println!("y = {}", y); } #}
return
expressions
Return expressions are denoted with the keyword return
. Evaluating a return
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:
# #![allow(unused_variables)] #fn main() { fn max(a: i32, b: i32) -> i32 { if a > b { return a; } return b; } #}
Type system
Types
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, in nontrivial ways that are not possible to emulate in user-defined types. User-defined types have limited capabilities.
Primitive types
The primitive types are the following:
- The boolean type
bool
with valuestrue
andfalse
. - The machine types (integer and floating-point).
- The machine-dependent integer types.
- Arrays
- Tuples
- Slices
- Function pointers
Machine types
The machine types are the following:
-
The unsigned word types
u8
,u16
,u32
andu64
, with values drawn from the integer intervals [0, 2^8 - 1], [0, 2^16 - 1], [0, 2^32 - 1] and [0, 2^64 - 1] respectively. -
The signed two's complement word types
i8
,i16
,i32
andi64
, with values drawn from the integer intervals [-(2^(7)), 2^7 - 1], [-(2^(15)), 2^15 - 1], [-(2^(31)), 2^31 - 1], [-(2^(63)), 2^63 - 1] respectively. -
The IEEE 754-2008
binary32
andbinary64
floating-point types:f32
andf64
, respectively.
Machine-dependent integer types
The usize
type is an unsigned integer type with the same number of bits as the
platform's pointer type. It can represent every memory address in the process.
The isize
type is a signed integer type with the same number of bits as the
platform's pointer type. The theoretical upper bound on object and array size
is the maximum isize
value. This ensures that isize
can be used to calculate
differences between pointers into an object or array and can address every byte
within an object along with one byte past the end.
Textual types
The types char
and str
hold textual data.
A value of type char
is a Unicode scalar value (i.e. a code point that
is not a surrogate) represented as a 32-bit unsigned word in the 0x0000 to
0xD7FF or 0xE000 to 0x10FFFF range. A [char]
array is effectively a UCS-4 /
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 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
.
Tuple types
A tuple type is a heterogeneous product of other types, called the elements of the tuple. It has no nominal name and is instead structurally typed.
Tuple types and values are denoted by listing the types or values of their elements, respectively, in a parenthesized, comma-separated list.
Because tuple elements don't have a name, they can only be accessed by
pattern-matching or by using N
directly as a field to access the
N
th element.
An example of a tuple type and its use:
# #![allow(unused_variables)] #fn main() { type Pair<'a> = (i32, &'a str); let p: Pair<'static> = (10, "ten"); let (a, b) = p; assert_eq!(a, 10); assert_eq!(b, "ten"); assert_eq!(p.0, 10); assert_eq!(p.1, "ten"); #}
For historical reasons and convenience, the tuple type with no elements (()
)
is often called ‘unit’ or ‘the unit type’.
Array, and Slice types
Rust has two different types for a list of items:
[T; N]
, an 'array'&[T]
, a 'slice'
An array has a fixed size, and can be allocated on either the stack or the heap.
A slice is a 'view' into an array. It doesn't own the data it points to, it borrows it.
Examples:
# #![allow(unused_variables)] #fn main() { // A stack-allocated array let array: [i32; 3] = [1, 2, 3]; // A heap-allocated array let vector: Vec<i32> = vec![1, 2, 3]; // A slice into an array let slice: &[i32] = &vector[..]; #}
As you can see, the vec!
macro allows you to create a Vec<T>
easily. The
vec!
macro is also part of the standard library, rather than the language.
All in-bounds elements of arrays and slices are always initialized, and access to an array or slice is always bounds-checked.
Struct types
A struct
type is a heterogeneous product of other types, called the
fields of the type.1
struct
types are analogous to struct
types in C,
the record types of the ML family,
or the struct types of the Lisp family.
New instances of a struct
can be constructed with a struct
expression.
The memory layout of a struct
is undefined by default to allow for compiler
optimizations like field reordering, but it can be fixed with the
#[repr(...)]
attribute. In either case, fields may be given in any order in
a corresponding struct expression; the resulting struct
value will always
have the same memory layout.
The fields of a struct
may be qualified by visibility
modifiers, to allow access to data in a
struct outside a module.
A tuple struct type is just like a struct type, except that the fields are anonymous.
A unit-like struct type is like a struct type, except that it has no fields. The one value constructed by the associated struct expression is the only value that inhabits such a type.
Enumerated types
An enumerated type is a nominal, heterogeneous disjoint union type, denoted
by the name of an enum
item. 2
The enum
type is analogous to a data
constructor declaration in
ML, or a pick ADT in Limbo.
An enum
item declares both the type and a number of variant
constructors, each of which is independently named and takes an optional tuple
of arguments.
New instances of an enum
can be constructed by calling one of the variant
constructors, in a call expression.
Any enum
value consumes as much memory as the largest variant constructor for
its corresponding enum
type.
Enum types cannot be denoted structurally as types, but must be denoted by
named reference to an enum
item.
Recursive types
Nominal types — enumerations and
structs — may be recursive. That is, each enum
constructor or struct
field may refer, directly or indirectly, to the
enclosing enum
or struct
type itself. Such recursion has restrictions:
- Recursive types must include a nominal type in the recursion (not mere type definitions, or other structural types such as arrays or tuples).
- A recursive
enum
item must have at least one non-recursive constructor (in order to give the recursion a basis case). - The size of a recursive type must be finite; in other words the recursive fields of the type must be pointer types.
- Recursive type definitions can cross module boundaries, but not module visibility boundaries, or crate boundaries (in order to simplify the module system and type checker).
An example of a recursive type and its use:
# #![allow(unused_variables)] #fn main() { enum List<T> { Nil, Cons(T, Box<List<T>>) } let a: List<i32> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil)))); #}
Pointer types
All pointers in Rust are explicit first-class values. They can be copied, stored into data structs, and returned from functions. There are two varieties of pointer in Rust:
-
References (
&
) : These point to memory owned by some other value. A reference type is written&type
, or&'a type
when you need to specify an explicit lifetime. Copying a reference is a "shallow" operation: it involves only copying the pointer itself. Releasing a reference has no effect on the value it points to, but a reference of a temporary value will keep it alive during the scope of the reference itself. -
Raw pointers (
*
) : Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written as*const T
or*mut T
, for example*const i32
means a raw pointer to a 32-bit integer. Copying or dropping a raw pointer has no effect on the lifecycle of any other value. Dereferencing a raw pointer or converting it to any other pointer type is anunsafe
operation. Raw pointers are generally discouraged in Rust code; they exist to support interoperability with foreign code, and writing performance-critical or low-level functions.
The standard library contains additional 'smart pointer' types beyond references and raw pointers.
Function item types
When referred to, a function item yields a zero-sized value of its function item type. That type explicitly identifies the function - its name, its type arguments, and its early-bound lifetime arguments (but not its late-bound lifetime arguments, which are only assigned when the function is called) - so the value does not need to contain an actual function pointer, and no indirection is needed when the function is called.
There is currently no syntax that directly refers to a function item type, but
the compiler will display the type as something like fn() {foo::<u32>}
in error
messages.
Because the function item type explicitly identifies the function, the item types of different functions - different items, or the same item with different generics - are distinct, and mixing them will create a type error:
fn foo<T>() { }
let x = &mut foo::<i32>;
*x = foo::<u32>; //~ ERROR mismatched types
However, there is a coercion from function items to function pointers
with the same signature, which is triggered not only when a function item
is used when a function pointer is directly expected, but also when different
function item types with the same signature meet in different arms of the same
if
or match
:
# #![allow(unused_variables)] #fn main() { # let want_i32 = false; # fn foo<T>() { } // `foo_ptr_1` has function pointer type `fn()` here let foo_ptr_1: fn() = foo::<i32>; // ... and so does `foo_ptr_2` - this type-checks. let foo_ptr_2 = if want_i32 { foo::<i32> } else { foo::<u32> }; #}
Function pointer types
Function pointer types, created using the fn
type constructor, refer
to a function whose identity is not necessarily known at compile-time. They
can be created via a coercion from both function items
and non-capturing closures.
A function pointer type consists of a possibly-empty set of function-type
modifiers (such as unsafe
or extern
), a sequence of input types and an
output type.
An example of a fn
type:
# #![allow(unused_variables)] #fn main() { fn add(x: i32, y: i32) -> i32 { x + y } let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); #}
Closure types
A closure expression produces a closure value with a unique, anonymous type that cannot be written out.
Depending on the requirements of the closure, its type implements one or more of the closure traits:
-
FnOnce
: The closure can be called once. A closure called asFnOnce
can move out values from its environment. -
FnMut
: The closure can be called multiple times as mutable. A closure called asFnMut
can mutate values from its environment.FnMut
inherits fromFnOnce
(i.e. anything implementingFnMut
also implementsFnOnce
). -
Fn
: The closure can be called multiple times through a shared reference. A closure called asFn
can neither move out from nor mutate values from its environment, but read-only access to such values is allowed.Fn
inherits fromFnMut
, which itself inherits fromFnOnce
.
Closures that don't use anything from their environment ("non capturing closures")
can be coerced to function pointers (fn
) with the matching signature.
To adopt the example from the section above:
# #![allow(unused_variables)] #fn main() { let add = |x, y| x + y; let mut x = add(5,7); type Binop = fn(i32, i32) -> i32; let bo: Binop = add; x = bo(5,7); #}
Trait objects
In Rust, a type like &SomeTrait
or Box<SomeTrait>
is called a trait object.
Each instance of a trait object includes:
- a pointer to an instance of a type
T
that implementsSomeTrait
- a virtual method table, often just called a vtable, which contains, for
each method of
SomeTrait
thatT
implements, a pointer toT
's implementation (i.e. a function pointer).
The purpose of trait objects is to permit "late binding" of methods. Calling a method on a trait object results in virtual dispatch at runtime: that is, a function pointer is loaded from the trait object vtable and invoked indirectly. The actual implementation for each vtable entry can vary on an object-by-object basis.
Note that for a trait object to be instantiated, the trait must be object-safe. Object safety rules are defined in RFC 255.
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 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 a trait object:
trait Printable { fn stringify(&self) -> String; } impl Printable for i32 { fn stringify(&self) -> String { self.to_string() } } fn print(a: Box<Printable>) { println!("{}", a.stringify()); } fn main() { print(Box::new(10) as Box<Printable>); }
In this example, the trait Printable
occurs as a trait object in both the
type signature of print
, and the cast expression in main
.
Since a trait object can contain references, the lifetimes of those references need to be expressed as part of the trait object. The assumed lifetime of references held by a trait object is called its default object lifetime bound. These were defined in RFC 599 and amended in RFC 1156.
For traits that themselves have no lifetime parameters, the default bound is based on what kind of trait object is used:
// For the following trait...
trait Foo { }
// ...these two are the same:
Box<Foo>
Box<Foo + 'static>
// ...and so are these:
&'a Foo
&'a (Foo + 'a)
The + 'static
and + 'a
refer to the default bounds of those kinds of trait
objects, and also to how you can directly override them. Note that the innermost
object sets the bound, so &'a Box<Foo>
is still &'a Box<Foo + 'static>
.
For traits that have lifetime parameters of their own, the default bound is based on that lifetime parameter:
// For the following trait...
trait Bar<'a>: 'a { }
// ...these two are the same:
Box<Bar<'a>>
Box<Bar<'a> + 'a>
The default for user-defined trait objects is based on the object type itself.
If a type parameter has a lifetime bound, then that lifetime bound becomes the
default bound for trait objects of that type. For example, std::cell::Ref<'a, T>
contains a T: 'a
bound, therefore trait objects of type Ref<'a, SomeTrait>
are the same as Ref<'a, (SomeTrait + 'a)>
.
Type parameters
Within the body of an item that has type parameter declarations, the names of its type parameters are types:
# #![allow(unused_variables)] #fn main() { fn to_vec<A: Clone>(xs: &[A]) -> Vec<A> { if xs.is_empty() { return vec![]; } let first: A = xs[0].clone(); let mut rest: Vec<A> = to_vec(&xs[1..]); rest.insert(0, first); rest } #}
Here, first
has type A
, referring to to_vec
's A
type parameter; and rest
has type Vec<A>
, a vector with element type A
.
Self types
The special type Self
has a meaning within traits and impls. In a trait definition, it refers
to an implicit type parameter representing the "implementing" type. In an impl,
it is an alias for the implementing type. For example, in:
# #![allow(unused_variables)] #fn main() { pub trait From<T> { fn from(T) -> Self; } impl From<i32> for String { fn from(x: i32) -> Self { x.to_string() } } #}
The notation Self
in the impl refers to the implementing type: String
. In another
example:
# #![allow(unused_variables)] #fn main() { trait Printable { fn make_string(&self) -> String; } impl Printable for String { fn make_string(&self) -> String { (*self).clone() } } #}
The notation &self
is a shorthand for self: &Self
. In this case,
in the impl, Self
refers to the value of type String
that is the
receiver for a call to the method make_string
.
Subtyping
Subtyping is implicit and can occur at any stage in type checking or inference. Subtyping in Rust is very restricted and occurs only due to variance with respect to lifetimes and between types with higher ranked lifetimes. If we were to erase lifetimes from types, then the only subtyping would be due to type equality.
Consider the following example: string literals always have 'static
lifetime. Nevertheless, we can assign s
to t
:
# #![allow(unused_variables)] #fn main() { fn bar<'a>() { let s: &'static str = "hi"; let t: &'a str = s; } #}
Since 'static
"lives longer" than 'a
, &'static str
is a subtype of
&'a str
.
Type coercions
Coercions are defined in RFC 401. RFC 1558 then expanded on that. A coercion is implicit and has no syntax.
Coercion sites
A coercion can only occur at certain coercion sites in a program; these are typically places where the desired type is explicit or can be derived by propagation from explicit types (without type inference). Possible coercion sites are:
-
let
statements where an explicit type is given.For example,
42
is coerced to have typei8
in the following:# #![allow(unused_variables)] #fn main() { let _: i8 = 42; #}
-
static
andconst
statements (similar tolet
statements). -
Arguments for function calls
The value being coerced is the actual parameter, and it is coerced to the type of the formal parameter.
For example,
42
is coerced to have typei8
in the following:fn bar(_: i8) { } fn main() { bar(42); }
-
Instantiations of struct or variant fields
For example,
42
is coerced to have typei8
in the following:struct Foo { x: i8 } fn main() { Foo { x: 42 }; }
-
Function results, either the final line of a block if it is not semicolon-terminated or any expression in a
return
statementFor example,
42
is coerced to have typei8
in the following:# #![allow(unused_variables)] #fn main() { fn foo() -> i8 { 42 } #}
If the expression in one of these coercion sites is a coercion-propagating expression, then the relevant sub-expressions in that expression are also coercion sites. Propagation recurses from these new coercion sites. Propagating expressions and their relevant sub-expressions are:
-
Array literals, where the array has type
[U; n]
. Each sub-expression in the array literal is a coercion site for coercion to typeU
. -
Array literals with repeating syntax, where the array has type
[U; n]
. The repeated sub-expression is a coercion site for coercion to typeU
. -
Tuples, where a tuple is a coercion site to type
(U_0, U_1, ..., U_n)
. Each sub-expression is a coercion site to the respective type, e.g. the zeroth sub-expression is a coercion site to typeU_0
. -
Parenthesized sub-expressions (
(e)
): if the expression has typeU
, then the sub-expression is a coercion site toU
. -
Blocks: if a block has type
U
, then the last expression in the block (if it is not semicolon-terminated) is a coercion site toU
. This includes blocks which are part of control flow statements, such asif
/else
, if the block has a known type.
Coercion types
Coercion is allowed between the following types:
-
T
toU
ifT
is a subtype ofU
(reflexive case) -
T_1
toT_3
whereT_1
coerces toT_2
andT_2
coerces toT_3
(transitive case)Note that this is not fully supported yet
-
&mut T
to&T
-
*mut T
to*const T
-
&T
to*const T
-
&mut T
to*mut T
-
&T
to&U
ifT
implementsDeref<Target = U>
. For example:use std::ops::Deref; struct CharContainer { value: char, } impl Deref for CharContainer { type Target = char; fn deref<'a>(&'a self) -> &'a char { &self.value } } fn foo(arg: &char) {} fn main() { let x = &mut CharContainer { value: 'y' }; foo(x); //&mut CharContainer is coerced to &char. }
-
&mut T
to&mut U
ifT
implementsDerefMut<Target = U>
. -
TyCtor(
T
) to TyCtor(coerce_inner(T
)), where TyCtor(T
) is one of&T
&mut T
*const T
*mut T
Box<T>
and where
- coerce_inner(
[T, ..n]
) =[T]
- coerce_inner(
T
) =U
whereT
is a concrete type which implements the traitU
.
In the future, coerce_inner will be recursively extended to tuples and structs. In addition, coercions from sub-traits to super-traits will be added. See RFC 401 for more details.
-
Non capturing closures to
fn
pointers
Special traits
Several traits define special evaluation behavior.
The Copy
trait
The Copy
trait changes the semantics of a type implementing it. Values whose
type implements Copy
are copied rather than moved upon assignment.
The Sized
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.
The Deref
trait
The Deref<Target = U>
trait allows a type to implicitly implement all the methods
of the type U
. When attempting to resolve a method call, the compiler will search
the top-level type for the implementation of the called method. If no such method is
found, .deref()
is called and the compiler continues to search for the method
implementation in the returned type U
.
The Send
trait
The Send
trait indicates that a value of this type is safe to send from one
thread to another.
The Sync
trait
The Sync
trait indicates that a value of this type is safe to share between
multiple threads.
Memory model
A Rust program's memory consists of a static set of items and a heap. 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 variables, and allocations in the heap consist of boxes.
Memory allocation and lifetime
The items of a program are those functions, modules and types that have their value calculated at compile-time and stored uniquely in the memory image of the rust process. Items are neither dynamically allocated nor freed.
The heap is a general term that describes boxes. The lifetime of an allocation in the heap depends on the lifetime of the box values pointing to it. Since box values may themselves be passed in and out of frames, or stored in the heap, heap allocations may outlive the frame they are allocated within. An allocation in the heap is guaranteed to reside at a single location in the heap for the whole lifetime of the allocation - it will never be relocated as a result of moving a box value.
Memory ownership
When a stack frame is exited, its local allocations are all released, and its references to boxes are dropped.
Variables
A variable is a component of a stack frame, either a named function parameter, an anonymous temporary, 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.
Local variables are immutable unless declared otherwise. For example: let mut x = ...
.
Function parameters are immutable unless declared with mut
. The mut
keyword
applies only to the following parameter. For example: |mut x, y|
and fn f(mut x: Box<i32>, y: Box<i32>)
declare one mutable variable x
and one immutable
variable y
.
Methods that take either self
or Box<Self>
can optionally place them in a
mutable variable by prefixing them with mut
(similar to regular arguments). For example:
# #![allow(unused_variables)] #fn main() { trait Changer: Sized { fn change(mut self) {} fn modify(mut self: Box<Self>) {} } #}
Local variables are not initialized when allocated. Instead, the entire frame worth of local variables are allocated, on frame-entry, in an uninitialized state. Subsequent statements within a function may or may not initialize the local variables. Local variables can be used only after they have been initialized; this is enforced by the compiler.
Linkage
The Rust compiler supports various methods to link crates together both statically and dynamically. This section will explore the various methods to link Rust crates together, and more information about native libraries can be found in the FFI section of the book.
In one session of compilation, the compiler can generate multiple artifacts
through the usage of either command line flags or the crate_type
attribute.
If one or more command line flags are specified, all crate_type
attributes will
be ignored in favor of only building the artifacts specified by command line.
-
--crate-type=bin
,#[crate_type = "bin"]
- A runnable executable will be produced. This requires that there is amain
function in the crate which will be run when the program begins executing. This will link in all Rust and native dependencies, producing a distributable binary. -
--crate-type=lib
,#[crate_type = "lib"]
- A Rust library will be produced. This is an ambiguous concept as to what exactly is produced because a library can manifest itself in several forms. The purpose of this genericlib
option is to generate the "compiler recommended" style of library. The output library will always be usable by rustc, but the actual type of library may change from time-to-time. The remaining output types are all different flavors of libraries, and thelib
type can be seen as an alias for one of them (but the actual one is compiler-defined). -
--crate-type=dylib
,#[crate_type = "dylib"]
- A dynamic Rust library will be produced. This is different from thelib
output type in that this forces dynamic library generation. The resulting dynamic library can be used as a dependency for other libraries and/or executables. This output type will create*.so
files on linux,*.dylib
files on osx, and*.dll
files on windows. -
--crate-type=staticlib
,#[crate_type = "staticlib"]
- A static system library will be produced. This is different from other library outputs in that the Rust compiler will never attempt to link tostaticlib
outputs. The purpose of this output type is to create a static library containing all of the local crate's code along with all upstream dependencies. The static library is actually a*.a
archive on linux and osx and a*.lib
file on windows. This format is recommended for use in situations such as linking Rust code into an existing non-Rust application because it will not have dynamic dependencies on other Rust code. -
--crate-type=cdylib
,#[crate_type = "cdylib"]
- A dynamic system library will be produced. This is used when compiling Rust code as a dynamic library to be loaded from another language. This output type will create*.so
files on Linux,*.dylib
files on macOS, and*.dll
files on Windows. -
--crate-type=rlib
,#[crate_type = "rlib"]
- A "Rust library" file will be produced. This is used as an intermediate artifact and can be thought of as a "static Rust library". Theserlib
files, unlikestaticlib
files, are interpreted by the Rust compiler in future linkage. This essentially means thatrustc
will look for metadata inrlib
files like it looks for metadata in dynamic libraries. This form of output is used to produce statically linked executables as well asstaticlib
outputs. -
--crate-type=proc-macro
,#[crate_type = "proc-macro"]
- The output produced is not specified, but if a-L
path is provided to it then the compiler will recognize the output artifacts as a macro and it can be loaded for a program. If a crate is compiled with theproc-macro
crate type it will forbid exporting any items in the crate other than those functions tagged#[proc_macro_derive]
and those functions must also be placed at the crate root. Finally, the compiler will automatically set thecfg(proc_macro)
annotation whenever any crate type of a compilation is theproc-macro
crate type.
Note that these outputs are stackable in the sense that if multiple are
specified, then the compiler will produce each form of output at once without
having to recompile. However, this only applies for outputs specified by the
same method. If only crate_type
attributes are specified, then they will all
be built, but if one or more --crate-type
command line flags are specified,
then only those outputs will be built.
With all these different kinds of outputs, if crate A depends on crate B, then
the compiler could find B in various different forms throughout the system. The
only forms looked for by the compiler, however, are the rlib
format and the
dynamic library format. With these two options for a dependent library, the
compiler must at some point make a choice between these two formats. With this
in mind, the compiler follows these rules when determining what format of
dependencies will be used:
-
If a static library is being produced, all upstream dependencies are required to be available in
rlib
formats. This requirement stems from the reason that a dynamic library cannot be converted into a static format.Note that it is impossible to link in native dynamic dependencies to a static library, and in this case warnings will be printed about all unlinked native dynamic dependencies.
-
If an
rlib
file is being produced, then there are no restrictions on what format the upstream dependencies are available in. It is simply required that all upstream dependencies be available for reading metadata from.The reason for this is that
rlib
files do not contain any of their upstream dependencies. It wouldn't be very efficient for allrlib
files to contain a copy oflibstd.rlib
! -
If an executable is being produced and the
-C prefer-dynamic
flag is not specified, then dependencies are first attempted to be found in therlib
format. If some dependencies are not available in an rlib format, then dynamic linking is attempted (see below). -
If a dynamic library or an executable that is being dynamically linked is being produced, then the compiler will attempt to reconcile the available dependencies in either the rlib or dylib format to create a final product.
A major goal of the compiler is to ensure that a library never appears more than once in any artifact. For example, if dynamic libraries B and C were each statically linked to library A, then a crate could not link to B and C together because there would be two copies of A. The compiler allows mixing the rlib and dylib formats, but this restriction must be satisfied.
The compiler currently implements no method of hinting what format a library should be linked with. When dynamically linking, the compiler will attempt to maximize dynamic dependencies while still allowing some dependencies to be linked in via an rlib.
For most situations, having all libraries available as a dylib is recommended if dynamically linking. For other situations, the compiler will emit a warning if it is unable to determine which formats to link each library with.
In general, --crate-type=bin
or --crate-type=lib
should be sufficient for
all compilation needs, and the other options are just available if more
fine-grained control is desired over the output format of a Rust crate.
Static and dynamic C runtimes
The standard library in general strives to support both statically linked and
dynamically linked C runtimes for targets as appropriate. For example the
x86_64-pc-windows-msvc
and x86_64-unknown-linux-musl
targets typically come
with both runtimes and the user selects which one they'd like. All targets in
the compiler have a default mode of linking to the C runtime. Typically targets
are linked dynamically by default, but there are exceptions which are static by
default such as:
arm-unknown-linux-musleabi
arm-unknown-linux-musleabihf
armv7-unknown-linux-musleabihf
i686-unknown-linux-musl
x86_64-unknown-linux-musl
The linkage of the C runtime is configured to respect the crt-static
target
feature. These target features are typically configured from the command line
via flags to the compiler itself. For example to enable a static runtime you
would execute:
rustc -C target-feature=+crt-static foo.rs
whereas to link dynamically to the C runtime you would execute:
rustc -C target-feature=-crt-static foo.rs
Targets which do not support switching between linkage of the C runtime will ignore this flag. It's recommended to inspect the resulting binary to ensure that it's linked as you would expect after the compiler succeeds.
Crates may also learn about how the C runtime is being linked. Code on MSVC, for
example, needs to be compiled differently (e.g. with /MT
or /MD
) depending
on the runtime being linked. This is exported currently through the
target_feature
attribute (note this is a nightly feature):
#[cfg(target_feature = "crt-static")]
fn foo() {
println!("the C runtime should be statically linked");
}
#[cfg(not(target_feature = "crt-static"))]
fn foo() {
println!("the C runtime should be dynamically linked");
}
Also note that Cargo build scripts can learn about this feature through environment variables. In a build script you can detect the linkage via:
use std::env; fn main() { let linkage = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new()); if linkage.contains("crt-static") { println!("the C runtime will be statically linked"); } else { println!("the C runtime will be dynamically linked"); } }
To use this feature locally, you typically will use the RUSTFLAGS
environment
variable to specify flags to the compiler through Cargo. For example to compile
a statically linked binary on MSVC you would execute:
RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-msvc
Unsafety
Unsafe operations are those that potentially violate the memory-safety guarantees of Rust's static semantics.
The following language level features cannot be used in the safe subset of Rust:
- Dereferencing a raw pointer.
- Reading or writing a mutable static variable.
- Calling an unsafe function (including an intrinsic or foreign function).
Unsafe functions
Unsafe functions are functions that are not safe in all contexts and/or for all
possible inputs. Such a function must be prefixed with the keyword unsafe
and
can only be called from an unsafe
block or another unsafe
function.
Unsafe blocks
A block of code can be prefixed with the unsafe
keyword, to permit calling
unsafe
functions or dereferencing raw pointers within a safe function.
When a programmer has sufficient conviction that a sequence of potentially
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, in the surrounding context.
Unsafe blocks are used to wrap foreign libraries, make direct use of hardware or implement features not directly present in the language. For example, Rust provides the language features necessary to implement memory-safe concurrency in the language but the implementation of threads and message passing is in the standard library.
Rust's type system is a conservative approximation of the dynamic safety
requirements, so in some cases there is a performance cost to using safe code.
For example, a doubly-linked list is not a tree structure and can only be
represented with reference-counted pointers in safe code. By using unsafe
blocks to represent the reverse links as raw pointers, it can be implemented
with only boxes.
Behavior considered undefined
The following is a list of behavior which is forbidden in all Rust code,
including within unsafe
blocks and unsafe
functions. Type checking provides
the guarantee that these issues are never caused by safe code.
- Data races
- Dereferencing a null/dangling raw pointer
- Reads of undef (uninitialized) memory
- Breaking the pointer aliasing rules on accesses through raw pointers (a subset of the rules used by C)
&mut T
and&T
follow LLVM’s scoped noalias model, except if the&T
contains anUnsafeCell<U>
. Unsafe code must not violate these aliasing guarantees.- Mutating non-mutable data (that is, data reached through a shared reference or
data owned by a
let
binding), unless that data is contained within anUnsafeCell<U>
. - Invoking undefined behavior via compiler intrinsics:
- Indexing outside of the bounds of an object with
std::ptr::offset
(offset
intrinsic), with the exception of one byte past the end which is permitted. - Using
std::ptr::copy_nonoverlapping_memory
(memcpy32
/memcpy64
intrinsics) on overlapping buffers
- Indexing outside of the bounds of an object with
- Invalid values in primitive types, even in private fields/locals:
- Dangling/null references or boxes
- A value other than
false
(0) ortrue
(1) in abool
- A discriminant in an
enum
not included in the type definition - A value in a
char
which is a surrogate or abovechar::MAX
- Non-UTF-8 byte sequences in a
str
- Unwinding into Rust from foreign code or unwinding from Rust into foreign code. Rust's failure system is not compatible with exception handling in other languages. Unwinding must be caught and handled at FFI boundaries.
Behavior not considered unsafe
The Rust compiler does not consider the following behaviors unsafe, though a programmer may (should) find them undesirable, unexpected, or erroneous.
Deadlocks
Leaks of memory and other resources
Exiting without calling destructors
Exposing randomized base addresses through pointer leaks
Integer overflow
If a program contains arithmetic overflow, the programmer has made an error. In the following discussion, we maintain a distinction between arithmetic overflow and wrapping arithmetic. The first is erroneous, while the second is intentional.
When the programmer has enabled debug_assert!
assertions (for
example, by enabling a non-optimized build), implementations must
insert dynamic checks that panic
on overflow. Other kinds of builds
may result in panics
or silently wrapped values on overflow, at the
implementation's discretion.
In the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two's complement overflow conventions.
The integral types provide inherent methods to allow programmers
explicitly to perform wrapping arithmetic. For example,
i32::wrapping_add
provides two's complement, wrapping addition.
The standard library also provides a Wrapping<T>
newtype which
ensures all standard arithmetic operations for T
have wrapping
semantics.
See RFC 560 for error conditions, rationale, and more details about integer overflow.
Influences
Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed):
- SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation
- C++: references, RAII, smart pointers, move semantics, monomorphization, memory model
- ML Kit, Cyclone: region based memory management
- Haskell (GHC): typeclasses, type families
- Newsqueak, Alef, Limbo: channels, concurrency
- Erlang: message passing, thread failure,
linked thread failure,lightweight concurrency - Swift: optional bindings
- Scheme: hygienic macros
- C#: attributes
- Ruby:
block syntax - NIL, Hermes:
typestate - Unicode Annex #31: identifier and pattern syntax
As-yet-undocumented Features
Several accepted, stabilized, and implemented RFCs lack documentation in this reference, The Book, Rust by Example, or some combination of those three. Until we have written reference documentation for these features, we provide links to other sources of information about them. Therefore, expect this list to shrink!
libstd
facade- Trait reform – some partial documentation exists (the use of
Self
), but not for everything: e.g. coherence and orphan rules. - Attributes on
match
arms – the underlying idea is documented in the [Attributes] section, but the applicability to internal items is never specified. - Flexible target specification - Some---but not all---flags are documented in Conditional compilation
- Require parentheses for chained comparisons
dllimport
- one element mentioned but not explained at FFI attributes- define
crt_link
- define
unaligned_access
Glossary
Abstract Syntax Tree
An ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of the structure of the program when the compiler is compiling it.
Arity
Arity refers to the number of arguments a function or operation takes.
For example, (2, 3)
and (4, 6)
have arity 2, and(8, 2, 6)
has arity 3.
Array
An array, sometimes also called a fixed-size array or an inline array, is a value describing a collection of elements, each selected by an index that can be computed at run time by the program. It occupies a contiguous region of memory.
Bound
Bounds are constraints on a type or trait. For example, if a bound is placed on the argument a function takes, types passed to that function must abide by that constraint.
Combinator
Combinators are higher-order functions that apply only functions and earlier defined combinators to provide a result from its arguments. They can be used to manage control flow in a modular fashion.
Dispatch
Dispatch is the mechanism to determine which specific version of code is actually run when it involves polymorphism. Two major forms of dispatch are static dispatch and dynamic dispatch. While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called ‘trait objects’.
Dynamically Sized Type
A dynamically sized type (DST) is a type without a statically known size or alignment.
Expression
An expression is a combination of values, constants, variables, operators and functions that evaluate to a single value, with or without side-effects.
For example, 2 + (3 * 4)
is an expression that returns the value 14.
Prelude
Prelude, or The Rust Prelude, is a small collection of items - mostly traits - that are imported into very module of every crate. The traits in the prelude are pervasive.
Slice
A slice is dynamically-sized view into a contiguous sequence, written as [T]
.
It is often seen in its borrowed forms, either mutable or shared. The shared
slice type is &[T]
, while the mutable slice type is &mut [T]
, where T
represents
the element type.
Statement
A statement is the smallest standalone element of a programming language that commands a computer to perform an action.
String literal
A string literal is a string stored directly in the final binary, and so will be
valid for the 'static
duration.
Its type is 'static
duration borrowed string slice, &'static str
.
String slice
A string slice is the most primitive string type in Rust, written as str
. It is
often seen in its borrowed forms, either mutable or shared. The shared
string slice type is &str
, while the mutable string slice type is &mut str
.
Strings slices are always valid UTF-8.
Trait
A trait is a language item that is used for describing the functionalities a type must provide. It allow a type to make certain promises about its behavior.
Generic functions and generic structs can exploit traits to constrain, or bound, the types they accept.