The Rust Reference

99
Rust 1.2.0 082e47636 The Rust Reference 1 Introduction 2 Notation 2.1 Unicode productions 2.2 String table productions 3 Lexical structure 3.1 Input format 3.2 Identiers 3.3 Comments 3.4 Whitespace 3.5 Tokens 3.5.1 Literals 3.5.1.1 Examples 3.5.1.1.1 Characters and strings 3.5.1.1.2 Byte escapes 3.5.1.1.3 Unicode escapes 3.5.1.1.4 Numbers 3.5.1.1.5 Sufxes 3.5.1.2 Character and string literals 3.5.1.2.1 Character literals 3.5.1.2.2 String literals 3.5.1.2.3 Character escapes 3.5.1.2.4 Raw string literals 3.5.1.3 Byte and byte string literals 3.5.1.3.1 Byte literals 3.5.1.3.2 Byte string literals 3.5.1.3.3 Raw byte string literals 3.5.1.4 Number literals 3.5.1.4.1 Integer literals 3.5.1.4.2 Floating-point literals 3.5.1.5 Boolean literals 3.5.2 Symbols 3.6 Paths 4 Syntax extensions 4.1 Macros

description

The rust book

Transcript of The Rust Reference

Page 1: The Rust Reference

Rust 1.2.0082e47636

The Rust Reference

1 Introduction2 Notation

2.1 Unicode productions2.2 String table productions

3 Lexical structure3.1 Input format3.2 Identi�ers3.3 Comments3.4 Whitespace3.5 Tokens

3.5.1 Literals3.5.1.1 Examples

3.5.1.1.1 Characters and strings3.5.1.1.2 Byte escapes3.5.1.1.3 Unicode escapes3.5.1.1.4 Numbers3.5.1.1.5 Suf�xes

3.5.1.2 Character and string literals3.5.1.2.1 Character literals3.5.1.2.2 String literals3.5.1.2.3 Character escapes3.5.1.2.4 Raw string literals

3.5.1.3 Byte and byte string literals3.5.1.3.1 Byte literals3.5.1.3.2 Byte string literals3.5.1.3.3 Raw byte string literals

3.5.1.4 Number literals3.5.1.4.1 Integer literals3.5.1.4.2 Floating-point literals

3.5.1.5 Boolean literals3.5.2 Symbols

3.6 Paths4 Syntax extensions

4.1 Macros

Page 2: The Rust Reference

4.1.1 Macro By Example4.1.2 Parsing limitations

5 Crates and source �les6 Items and attributes

6.1 Items6.1.1 Type Parameters6.1.2 Modules

6.1.2.1 Extern crate declarations6.1.2.2 Use declarations

6.1.3 Functions6.1.3.1 Generic functions6.1.3.2 Unsafety

6.1.3.2.1 Unsafe functions6.1.3.2.2 Unsafe blocks6.1.3.2.3 Behavior considered unde�ned6.1.3.2.4 Behavior not considered unsafe

6.1.3.3 Diverging functions6.1.3.4 Extern functions

6.1.4 Type aliases6.1.5 Structures6.1.6 Enumerations6.1.7 Constant items6.1.8 Static items

6.1.8.1 Mutable statics6.1.9 Traits6.1.10 Implementations6.1.11 External blocks

6.2 Visibility and Privacy6.2.1 Re-exporting and Visibility

6.3 Attributes6.3.1 Crate-only attributes6.3.2 Module-only attributes6.3.3 Function-only attributes6.3.4 Static-only attributes6.3.5 FFI attributes6.3.6 Macro-related attributes6.3.7 Miscellaneous attributes6.3.8 Conditional compilation6.3.9 Lint check attributes6.3.10 Language items6.3.11 Inline attributes6.3.12 derive6.3.13 Compiler Features

Page 3: The Rust Reference

7 Statements and expressions7.1 Statements

7.1.1 Declaration statements7.1.1.1 Item declarations7.1.1.2 Variable declarations

7.1.2 Expression statements7.2 Expressions

7.2.0.1 Lvalues, rvalues and temporaries7.2.0.1.1 Temporary lifetimes

7.2.0.2 Moved and copied types7.2.1 Literal expressions7.2.2 Path expressions7.2.3 Tuple expressions7.2.4 Structure expressions7.2.5 Block expressions7.2.6 Method-call expressions7.2.7 Field expressions7.2.8 Array expressions7.2.9 Index expressions7.2.10 Range expressions7.2.11 Unary operator expressions7.2.12 Binary operator expressions

7.2.12.1 Arithmetic operators7.2.12.2 Bitwise operators7.2.12.3 Lazy boolean operators7.2.12.4 Comparison operators7.2.12.5 Type cast expressions7.2.12.6 Assignment expressions7.2.12.7 Compound assignment expressions7.2.12.8 Operator precedence

7.2.13 Grouped expressions7.2.14 Call expressions7.2.15 Lambda expressions7.2.16 In�nite loops7.2.17 Break expressions7.2.18 Continue expressions7.2.19 While loops7.2.20 For expressions7.2.21 If expressions7.2.22 Match expressions7.2.23 If let expressions7.2.24 While let loops7.2.25 Return expressions

Page 4: The Rust Reference

8 Type system8.1 Types

8.1.1 Primitive types8.1.1.1 Machine types8.1.1.2 Machine-dependent integer types

8.1.2 Textual types8.1.3 Tuple types8.1.4 Array, and Slice types8.1.5 Structure types8.1.6 Enumerated types8.1.7 Recursive types8.1.8 Pointer types8.1.9 Function types

8.1.9.1 Function types for speci�c items8.1.10 Closure types8.1.11 Trait objects8.1.12 Type parameters8.1.13 Self types

8.2 Subtyping8.3 Type coercions

8.3.1 Coercion sites8.3.2 Coercion types

9 Special traits9.1 The Copy trait9.2 The Sized trait9.3 The Drop trait9.4 The Deref trait

10 Memory model10.0.1 Memory allocation and lifetime10.0.2 Memory ownership10.0.3 Variables

11 Linkage12 Appendix: Rationales and design tradeoffs13 Appendix: In�uences

1 IntroductionThis document is the primary reference for the Rust programming language. Itprovides three kinds of material:

Chapters that informally describe each language construct and their use.

Page 5: The Rust Reference

Chapters that informally describe the memory model, concurrency model,runtime services, linkage model and debugging facilities.Appendix chapters providing rationale and references to languages thatinfluenced the design.

This document does not serve as an introduction to the language. Backgroundfamiliarity with the language is assumed. A separate book (book/) is available to helpacquire such background familiarity.

This document also does not serve as a reference to the standard (std/) libraryincluded in the language distribution. Those libraries are documented separately byextracting documentation attributes from their source code. Many of the featuresthat one might expect to be language features are library features in Rust, so whatyou're looking for may be there, not here.

You may also be interested in the grammar (grammar.html).

2 Notation

2.1 Unicode productions

A few productions in Rust's grammar permit Unicode code points outside the ASCIIrange. We define these productions in terms of character properties specified in theUnicode standard, rather than in terms of ASCII-range code points. The grammarhas a Special Unicode Productions (grammar.html#special-unicode-productions)section that lists these productions.

2.2 String table productions

Some rules in the grammar — notably unary operators (#unary-operator-expressions), binary operators (#binary-operator-expressions), and keywords(grammar.html#keywords) — are given in a simplified form: as a listing of a table ofunquoted, printable whitespace-separated strings. These cases form a subset of therules regarding the token (#tokens) rule, and are assumed to be the result of alexical-analysis phase feeding the parser, driven by a DFA, operating over thedisjunction of all such string table entries.

Page 6: The Rust Reference

When such a string enclosed in double-quotes (") occurs inside the grammar, it is animplicit reference to a single member of such a string table production. See tokens(#tokens) for more information.

3 Lexical structure

3.1 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 pointlists.

3.2 Identi�ers

An identifier is any nonempty Unicode string of the following form:

The first character has property XID_startThe remaining characters have property XID_continue

that does not occur in the set of keywords (grammar.html#keywords).

Note: XID_start and XID_continue as character properties cover the characterranges used to form the more familiar C and Java language-family identifiers.

3.3 Comments

Comments in Rust code follow the general C++ style of line (//) and block (/* ...*/) comment forms. Nested block comments are supported.

Line comments beginning with exactly three slashes (///), and block commentsbeginning with exactly one repeated asterisk in the block-open sequence (/**), areinterpreted as a special syntax for doc attributes (#attributes). That is, they areequivalent to writing #[doc="..."] around the body of the comment, i.e., ///Foo turns into #[doc="Foo"].

1 (#fn1)

2 (#fn2)

Page 7: The Rust Reference

Line comments beginning with //! and block comments beginning with /*! aredoc comments that apply to the parent of the comment, rather than the item thatfollows. That is, they are equivalent to writing #![doc="..."] around the body ofthe comment. //! comments are usually used to document modules that occupy asource file.

Non-doc comments are interpreted as a form of whitespace.

3.4 Whitespace

Whitespace is any non-empty string containing only the following characters:

U+0020 (space, ' ')U+0009 (tab, '\t')U+000A (LF, '\n')U+000D (CR, '\r')

Rust is a "free-form" language, meaning that all forms of whitespace serve only toseparate tokens in the grammar, and have no semantic significance.

A Rust program has identical meaning if each whitespace element is replaced withany other legal whitespace element, such as a single space character.

3.5 Tokens

Tokens are primitive productions in the grammar defined by regular (non-recursive)languages. "Simple" tokens are given in string table production (#string-table-productions) form, and occur in the rest of the grammar as double-quoted strings.Other tokens have exact rules given.

3.5.1 Literals

A literal is an expression consisting of a single token, rather than a sequence oftokens, that immediately and directly denotes the value it evaluates to, rather thanreferring to it by name or some other evaluation rule. A literal is a form of constantexpression, so is evaluated (primarily) at compile time.

Page 8: The Rust Reference

3.5.1.1 Examples

3.5.1.1.1 Characters and strings

Example # sets Characters Escapes

Character 'H' N/A All Unicode \' & Byte & Unicode

String "hello" N/A All Unicode \" & Byte & Unicode

Raw r#"hello"# 0... All Unicode N/A

Byte b'H' N/A All ASCII \' & Byte

Byte string b"hello" N/A All ASCII \" & Byte

Raw byte string br#"hello"# 0... All ASCII N/A

3.5.1.1.2 Byte escapes

Name

\x7F 8-bit character code (exactly 2 digits)

\n Newline

\r Carriage return

\t Tab

\\ Backslash

3.5.1.1.3 Unicode escapes

Name

\u{7FFF} 24-bit Unicode character code (up to 6 digits)

3.5.1.1.4 Numbers

Number literals* Example Exponentiation Suffixes

Decimal integer 98_222 N/A Integer suffixes

Hex integer 0xff N/A Integer suffixes

Page 9: The Rust Reference

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

3.5.1.1.5 Suf�xes

Integer Floating-point

u8, i8, u16, i16, u32, i32, u64, i64, isize, usize f32, f64

3.5.1.2 Character and string literals

3.5.1.2.1 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 apreceding U+005C character (\).

3.5.1.2.2 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 beescaped by a preceding U+005C character (\).

Line-break characters are allowed in string literals. Normally they representthemselves (i.e. no translation), but as a special exception, when a U+005C character(\) occurs immediately before the newline, the U+005C character, the newline, andall whitespace at the beginning of the next line are ignored. Thus a and b are equal:

let a = "foobar";let b = "foo\ bar";

assert_eq!(a,b);

Page 10: The Rust Reference

3.5.1.2.3 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 twohex 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 hexdigits surrounded by braces U+007B ({) and U+007D (}). It denotes the Unicodecode 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 values U+000A (LF), U+000D (CR) orU+0009 (HT) respectively.The backslash escape is the character U+005C (\) which must be escaped inorder to denote itself.

3.5.1.2.4 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 Unicodecharacters and is terminated only by another U+0022 (double-quote) character,followed by the same number of U+0023 (#) characters that preceded the openingU+0022 (double-quote) character.

All Unicode characters contained in the raw string body represent themselves, thecharacters U+0022 (double-quote) (except when followed by at least as manyU+0023 (#) characters as were used to start the raw string literal) or U+005C (\) donot have any special meaning.

Examples for string literals:

Page 11: The Rust Reference

3.5.1.3 Byte and byte string literals

3.5.1.3.1 Byte literals

A byte literal is a single ASCII character (in the U+0000 to U+007F range) or a singleescape preceded by the characters U+0062 (b) and U+0027 (single-quote), andfollowed by the character U+0027. If the character U+0027 is present within theliteral, it must be escaped by a preceding U+005C (\) character. It is equivalent to au8 unsigned 8-bit integer number literal.

3.5.1.3.2 Byte string literals

A non-raw byte string literal is a sequence of ASCII characters and escapes, precededby the characters U+0062 (b) and U+0022 (double-quote), and followed by thecharacter U+0022. If the character U+0022 is present within the literal, it must beescaped by a preceding U+005C (\) character. Alternatively, a byte string literal canbe a raw byte string literal, defined below. A byte string literal of length n isequivalent to a &'static [u8; n] borrowed fixed-sized array of unsigned 8-bitintegers.

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 hexdigits. 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 values 0x0A (ASCII LF), 0x0D (ASCII CR) or0x09 (ASCII HT) respectively.The backslash escape is the character U+005C (\) which must be escaped in

"foo"; r"foo"; // foo"\"foo\""; r#""foo""#; // "foo"

"foo #\"# bar";r##"foo #"# bar"##; // foo #"# bar

"\x52"; "R"; r"R"; // R"\\x52"; r"\x52"; // \x52

Page 12: The Rust Reference

order to denote its ASCII encoding 0x5C.

3.5.1.3.3 Raw byte string literals

Raw byte string literals do not process any escapes. They start with the characterU+0062 (b), followed by U+0072 (r), followed by zero or more of the characterU+0023 (#), and a U+0022 (double-quote) character. The raw string body cancontain any sequence of ASCII characters and is terminated only by anotherU+0022 (double-quote) character, followed by the same number of U+0023 (#)characters that preceded the opening U+0022 (double-quote) character. A raw bytestring literal can not contain any non-ASCII byte.

All characters contained in the raw string body represent their ASCII encoding, thecharacters U+0022 (double-quote) (except when followed by at least as manyU+0023 (#) characters as were used to start the raw string literal) or U+005C (\) donot have any special meaning.

Examples for byte string literals:

3.5.1.4 Number literals

A number literal is either an integer literal or a floating-point literal. The grammarfor recognizing the two kinds of literals is mixed.

3.5.1.4.1 Integer literals

An integer literal has one of four forms:

A decimal literal starts with a decimal digit and continues with any mixture ofdecimal digits and underscores.

b"foo"; br"foo"; // foob"\"foo\""; br#""foo""#; // "foo"

b"foo #\"# bar";br##"foo #"# bar"##; // foo #"# bar

b"\x52"; b"R"; br"R"; // Rb"\\x52"; br"\x52"; // \x52

Page 13: The Rust Reference

A hex literal starts with the character sequence U+0030 U+0078 (0x) andcontinues as any mixture of hex digits and underscores.An octal literal starts with the character sequence U+0030 U+006F (0o) andcontinues as any mixture of octal digits and underscores.A binary literal starts with the character sequence U+0030 U+0062 (0b) andcontinues 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 mustbe 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 aninteger type can be uniquely determined from the surrounding program context, theunsuffixed integer literal has that type. If the program context underconstrains thetype, it defaults to the signed 32-bit integer i32; if the program contextoverconstrains the type, it is considered a static type error.

Examples of integer literals of various forms:

3.5.1.4.2 Floating-point literals

A floating-point literal has one of two forms:

A decimal literal followed by a period character U+002E (.). This is optionallyfollowed by another decimal literal, with an optional exponent.A single decimal literal followed by an exponent.

123i32; // type i32123u32; // type u32123_u32; // type u320xff_u8; // type u80o70_i16; // type i160b1111_1111_1001_0000_i32; // type i320usize; // type usize

Page 14: The Rust Reference

Like integer literals, a floating-point literal may be followed by a suffix, so long as thepre-suffix part does not end with U+002E (.). The suffix forcibly sets the type of theliteral. 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 afloating-point type can be uniquely determined from the surrounding programcontext, the unsuffixed floating-point literal has that type. If the program contextunderconstrains the type, it defaults to double-precision f64; if the program contextoverconstrains the type, it is considered a static type error.

Examples of floating-point literals of various forms:

This last example is different because it is not possible to use the suffix syntax with afloating point literal ending in a period. 2.f64 would attempt to call a methodnamed f64 on 2.

The representation semantics of floating-point numbers are described in "MachineTypes" (#machine-types).

3.5.1.5 Boolean literals

The two values of the boolean type are written true and false.

3.5.2 Symbols

Symbols are a general class of printable token (#tokens) that play structural roles in avariety of grammar productions. They are catalogued here for completeness as theset of remaining miscellaneous printable tokens that do not otherwise appear asunary operators (#unary-operator-expressions), binary operators (#binary-operator-expressions), or keywords (grammar.html#keywords).

123.0f64; // type f640.1f64; // type f640.1f32; // type f3212E+99_f64; // type f64let x: f64 = 2.; // type f64

Page 15: The Rust Reference

3.6 Paths

A path is a sequence of one or more path components logically separated by anamespace qualifier (::). If a path consists of only one component, it may refer toeither an item (#items) or a variable (#variables) in a local control scope. If a pathhas multiple components, it refers to an item.

Every item has a canonical path within its crate, but the path naming an item is onlymeaningful within a given crate. There is no global namespace across crates; anitem's canonical path merely identifies it within the crate.

Two examples of simple paths consisting of only identifier components:

Path components are usually identifiers (#identifiers), but they may also includeangle-bracket-enclosed lists of type arguments. In expression (#expressions) context,the type argument list is given a�er a :: namespace qualifier in order todisambiguate it from a relational expression involving the less-than symbol (<). Intype expression context, the final namespace qualifier is omitted.

Two examples of paths with type arguments:

Paths can be denoted with various leading qualifiers to change the meaning of how itis resolved:

Paths starting with :: are considered to be global paths where the componentsof the path start being resolved from the crate root. Each identifier in the pathmust resolve to an item.

x;x::y::z;

type T = HashMap<i32,String>; // Type arguments used in a type expressionlet x = id::<i32>(10); // Type arguments used in a call expression

Page 16: The Rust Reference

Paths starting with the keyword super begin resolution relative to the parentmodule. Each further identifier must resolve to an item.

Paths starting with the keyword self begin resolution relative to the currentmodule. Each further identifier must resolve to an item.

4 Syntax extensionsA 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, andinvoked through a consistent syntax: some_extension!(...).

Users of rustc can define new syntax extensions in two ways:

mod a { pub fn foo() {}}mod b { pub fn foo() { ::a::foo(); // call a's foo function }}

mod a { pub fn foo() {}}mod b { pub fn foo() { super::a::foo(); // call a's foo function }}

fn foo() {}fn bar() { self::foo();}

Page 17: The Rust Reference

Compiler plugins (book/compiler-plugins.html) can include arbitrary Rust codethat manipulates syntax trees at compile time. Note that the interface forcompiler plugins is considered highly unstable.

Macros (book/macros.html) define new syntax in a higher-level, declarative way.

4.1 Macros

macro_rules allows users to define syntax extension in a declarative way. We callsuch extensions "macros by example" or simply "macros" — to be distinguished fromthe "procedural macros" defined in compiler plugins (book/compiler-plugins.html).

Currently, macros can expand to expressions, statements, items, or patterns.

(A sep_token is any token other than * and +. A non_special_token is anytoken other than a delimiter or $.)

The macro expander looks up macro invocations by name, and tries each macro rulein turn. It transcribes the first successful match. Matching and transcription areclosely related to each other, and we will describe them together.

4.1.1 Macro By Example

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 syntaxnamed by designator. Valid designators are item, block, stmt, pat, expr, ty(type), ident, path, tt (either side of the => in macro rules). In the transcriber,the designator is already known, and so only the name of a matched nonterminalcomes a�er the dollar sign.

In both the matcher and transcriber, the Kleene star-like operator indicatesrepetition. The Kleene star operator consists of $ and parentheses, optionallyfollowed by a separator token, followed by * or +. * means zero or morerepetitions, + means at least one repetition. The parentheses are not matched or

Page 18: The Rust Reference

transcribed. On the matcher side, a name is bound to all of the names it matches, ina structure that mimics the structure of the repetition encountered on a successfulmatch. 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 bedischarged 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 sthat occur in its body. At the "current layer", they all must repeat the same number oftimes, 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 theformer input transcribes to (a,d), (b,e), (c,f).

Nested repetitions are allowed.

4.1.2 Parsing limitations

The parser used by the macro system is reasonably powerful, but the parsing of Rustsyntax is restricted in two ways:

1. Macro definitions are required to include suitable separators a�er parsingexpressions and other bits of the Rust grammar. This implies that a macrodefinition like $i:expr [ , ] is not legal, because [ could be part of anexpression. A macro definition like $i:expr, or $i:expr; would be legal,however, because , and ; are legal separators. See RFC 550 for moreinformation.

2. The parser must have eliminated all ambiguity by the time it reaches a $ name :designator. This requirement most o�en affects name-designator pairs when theyoccur at the beginning of, or immediately a�er, a $(...)*; requiring adistinctive token in front can solve the problem.

5 Crates and source �les

Page 19: The Rust Reference

Although Rust, like any other language, can be implemented by an interpreter aswell as a compiler, the only existing implementation is a compiler — from now onreferred to as the Rust compiler — and the language has always been designed to becompiled. For these reasons, this section assumes a compiler.

Rust's semantics obey a phase distinction between compile-time and run-time.Those semantic rules that have a static interpretation govern the success or failure ofcompilation. Those semantics that have a dynamic interpretation govern thebehavior of the program at run-time.

The compilation model centers on artifacts called crates. Each compilationprocesses a single crate in source form, and if successful, produces a single crate inbinary form: either an executable or some sort of library.

A crate is a unit of compilation and linking, as well as versioning, distribution andruntime loading. A crate contains a tree of nested module (#modules) scopes. Thetop level of this tree is a module that is anonymous (from the point of view of pathswithin the module) and any item within a crate has a canonical module path (#paths)denoting its location within the crate's module tree.

The Rust compiler is always invoked with a single source file as input, and alwaysproduces a single output crate. The processing of that source file may result in othersource 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 themodule tree of the current crate — are defined from outside the source file: either byan 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: moduledefinitions (#modules) can be nested within one file.

Each source file contains a sequence of zero or more item definitions, and mayoptionally begin with any number of attributes (#items-and-attributes) that apply tothe containing module, most of which influence the behavior of the compiler. Theanonymous crate module can have additional attributes that apply to the crate as awhole.

3 (#fn3)

4 (#fn4)

Page 20: The Rust Reference

A crate that contains a main function can be compiled to an executable. If a mainfunction is present, its return type must be unit (#tuple-types) and it must take noarguments.

6 Items and attributesCrates contain items (#items), each of which may have some number of attributes(#attributes) attached to it.

6.1 Items

An item is a component of a crate. Items are organized within a crate by a nested setof modules (#modules). Every crate has a single "outermost" anonymous module; allfurther items within the crate have paths (#paths) within the module tree of thecrate.

Items are entirely determined at compile-time, generally remain fixed duringexecution, and may reside in read-only memory.

There are several kinds of item:

extern crate declarationsuse declarationsmodulesfunctionstype definitionsstructuresenumerations

// 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)]

Page 21: The Rust Reference

constant itemsstatic itemstraitsimplementations

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 mixedwith the statements, control blocks, and similar artifacts that otherwise compose theitem body. The meaning of these scoped items is the same as if the item was declaredoutside the scope — it is still a static item — except that the item's path name withinthe module namespace is qualified by the name of the enclosing item, or is private tothe enclosing item (in the case of functions). The grammar specifies the exactlocations in which sub-item declarations may appear.

6.1.1 Type Parameters

All items except modules, constants and statics may be parameterized by type. Typeparameters are given as a comma-separated list of identifiers enclosed in anglebrackets (<...>), a�er the name of the item and before its definition. The typeparameters of an item are considered "part of the name", not part of the type of theitem. A referencing path (#paths) must (in principle) provide type arguments as a listof comma-separated types enclosed within angle brackets, in order to refer to thetype-parameterized item. In practice, the type-inference system can usually infersuch argument types from context. There are no general type-parametric types, onlytype-parametric items. That is, Rust has no notion of type abstraction: there are nohigher-ranked (or "forall") types abstracted over other types, though higher-rankedtypes do exist for lifetimes.

6.1.2 Modules

A module is a container for zero or more items (#items).

A module item is a module, surrounded in braces, named, and prefixed with thekeyword mod. A module item introduces a new, named module into the tree ofmodules making up a crate. Modules can nest arbitrarily.

An example of a module:

Page 22: The Rust Reference

Modules and types share the same namespace. Declaring a named type with thesame name as a module in scope is forbidden: that is, a type definition, trait, struct,enumeration, or type parameter can't shadow the name of a module in scope, or viceversa.

A module without a body is loaded from an external file, by default with the samename as the module, plus the .rs extension. When a nested submodule is loadedfrom an external file, it is loaded from a subdirectory path that mirrors the modulehierarchy.

The directories and files used for loading external file modules can be influencedwith the path attribute.

mod math { type Complex = (f64, f64); fn sin(f: f64) -> f64 { /* ... */ } fn cos(f: f64) -> f64 { /* ... */ } fn tan(f: f64) -> f64 { /* ... */ }}

// Load the vec module from vec.rsmod vec;

mod thread { // Load the local_data module from thread/local_data.rs // or thread/local_data/mod.rs. mod local_data;}

#[path = "thread_files"]mod thread { // Load the local_data module from thread_files/tls.rs #[path = "tls.rs"] mod local_data;}

Page 23: The Rust Reference

6.1.2.1 Extern crate declarations

An extern crate declaration specifies a dependency on an external crate. Theexternal crate is then bound into the declaring scope as the ident provided in theextern_crate_decl.

The external crate is resolved to a specific soname at compile time, and a runtimelinkage 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 andmatching the optional crateid provided against the crateid attributes that weredeclared on the external crate when it was compiled. If no crateid is provided, adefault name attribute is assumed, equal to the ident given in theextern_crate_decl.

Three examples of extern crate declarations:

6.1.2.2 Use declarations

A use declaration creates one or more local name bindings synonymous with someother path (#paths). Usually a use declaration is used to shorten the path requiredto refer to a module item. These declarations may appear at the top of modules(#modules) and blocks (grammar.html#block-expressions).

Note: Unlike in many languages, use declarations in Rust do not declare linkagedependency with external crates. Rather, extern crate declarations (#extern-crate-declarations) declare linkage dependencies.

Use declarations support a number of convenient shortcuts:

Rebinding the target name as a new local name, using the syntax use p::q::r

extern crate pcre;

extern crate std; // equivalent to: extern crate std as std;

extern crate std as ruststd; // linking to 'std' under another name

Page 24: The Rust Reference

as x;Simultaneously binding a list of paths differing only in their final element, usingthe glob-like brace syntax use a::b::{c,d,e,f};Binding all paths matching a given prefix, using the asterisk wildcard syntax usea::b::*;Simultaneously binding a list of paths differing only in their final element andtheir immediate parent module, using the self keyword, such as use a::b::{self, c, d};

An example of use declarations:

Like items, use declarations are private to the containing module, by default. Alsolike items, a use declaration can be public, if qualified by the pub keyword. Such ause declaration serves to re-export a name. A public use declaration can thereforeredirect some public name to a different target definition: even a definition with aprivate canonical path, inside a different module. If a sequence of such redirectionsform a cycle or cannot be resolved unambiguously, they represent a compile-timeerror.

An example of re-exporting:

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);}

Page 25: The Rust Reference

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, inthe previous example, the use refers to quux::foo::{bar, baz}, and notsimply to foo::{bar, baz}. This also means that top-level module declarationsshould be at the crate root if direct usage of the declared modules within use itemsis desired. It is also possible to use self and super at the beginning of a use itemto refer to the current and direct parent modules respectively. All rules regardingaccessing declared modules in use declarations apply to both module declarationsand extern crate declarations.

An example of what will and will not work for use items:

mod quux { pub use quux::foo::{bar, baz};

pub mod foo { pub fn bar() { } pub fn baz() { } }}

Page 26: The Rust Reference

6.1.3 Functions

A function item defines a sequence of statements (#statements) and an optional finalexpression (#expressions), along with a name and a set of parameters. Functions aredeclared with the keyword fn. Functions declare a set of input variables (#variables)as parameters, through which the caller passes arguments into the function, and theoutput type (#types) of the value the function will return to its caller on completion.

A function may also be copied into a first-class value, in which case the value has thecorresponding function type (#function-types), and can be used otherwise exactly asa function item (with a minor additional cost of calling the function indirectly).

Every control path in a function logically ends with a return expression or adiverging expression. If the outermost block of a function has a value-producingexpression in its final-expression position, that expression is interpreted as animplicit return expression applied to the final-expression.

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: core is not at the crate root use self::baz::foobaz; // good: self refers to module 'foo' use foo::bar::foobar; // good: foo is at crate root

pub mod bar { pub fn foobar() { } }

pub mod baz { use super::bar::foobar; // good: super refers to module 'foo' pub fn foobaz() { } }}

fn main() {}

Page 27: The Rust Reference

An example of a function:

As with let bindings, function arguments are irrefutable patterns, so any patternthat is valid in a let binding is also valid as an argument.

6.1.3.1 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,comma-separated list following the function name.

Inside the function signature and body, the name of the type parameter can be usedas a type name. Trait (#traits) bounds can be specified for type parameters to allowmethods with that trait to be called on values of that type. This is specified using thewhere syntax:

When a generic function is referenced, its type is instantiated based on the contextof the reference. For example, calling the foo function here:

fn add(x: i32, y: i32) -> i32 { return x + y;}

fn first((value, _): (i32, i32)) -> i32 { value }

// foo is generic over A and B

fn foo<A, B>(x: A, y: B) {

fn foo<T>(x: T) where T: Debug {

Page 28: The Rust Reference

will instantiate type parameter T with i32.

The type parameters can also be explicitly supplied in a trailing path (#paths)component a�er the function name. This might be necessary if there is not sufficientcontext to determine the type parameters. For example, mem::size_of::<u32>()== 4.

6.1.3.2 Unsafety

Unsafe operations are those that potentially violate the memory-safety guarantees ofRust'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).

6.1.3.2.1 Unsafe functions

Unsafe functions are functions that are not safe in all contexts and/or for all possibleinputs. Such a function must be prefixed with the keyword unsafe and can only becalled from an unsafe block or another unsafe function.

6.1.3.2.2 Unsafe blocks

A block of code can be prefixed with the unsafe keyword, to permit callingunsafe functions or dereferencing raw pointers within a safe function.

use std::fmt::Debug;

fn foo<T>(x: &[T]) where T: Debug { // details elided}

foo(&[1, 2]);

Page 29: The Rust Reference

When a programmer has sufficient conviction that a sequence of potentially unsafeoperations 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 thesurrounding context.

Unsafe blocks are used to wrap foreign libraries, make direct use of hardware orimplement features not directly present in the language. For example, Rust providesthe language features necessary to implement memory-safe concurrency in thelanguage but the implementation of threads and message passing is in the standardlibrary.

Rust's type system is a conservative approximation of the dynamic safetyrequirements, so in some cases there is a performance cost to using safe code. Forexample, a doubly-linked list is not a tree structure and can only be represented withreference-counted pointers in safe code. By using unsafe blocks to represent thereverse links as raw pointers, it can be implemented with only boxes.

6.1.3.2.3 Behavior considered unde�ned

The following is a list of behavior which is forbidden in all Rust code, includingwithin unsafe blocks and unsafe functions. Type checking provides theguarantee that these issues are never caused by safe code.

Data racesDereferencing a null/dangling raw pointerReads of undef (uninitialized) memoryBreaking the pointer aliasing rules with raw pointers (a subset of the rules usedby C)&mut and & 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 ordata 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 ispermitted.

Page 30: The Rust Reference

Using std::ptr::copy_nonoverlapping_memory(memcpy32/memcpy64 intrinsics) on overlapping buffers

Invalid values in primitive types, even in private fields/locals:Dangling/null references or boxesA value other than false (0) or true (1) in a boolA discriminant in an enum not included in the type definitionA value in a char which is a surrogate or above char::MAXNon-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 otherlanguages. Unwinding must be caught and handled at FFI boundaries.

6.1.3.2.4 Behavior not considered unsafe

This is a list of behavior not considered unsafe in Rust terms, but that may beundesired.

DeadlocksReading data from private fields (std::repr)Leaks of memory and other resourcesExiting without calling destructorsSending signalsAccessing/modifying the file systemInteger overflow

Overflow is considered "unexpected" behavior and is always user-error, unlessthe wrapping primitives are used. In non-optimized builds, the compiler willinsert debug checks that panic on overflow, but in optimized builds overflowinstead results in wrapped values. See RFC 560 for the rationale and moredetails.

6.1.3.3 Diverging functions

A special kind of function can be declared with a ! character where the output typewould normally be. For example:

Page 31: The Rust Reference

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!() or a call toanother diverging function on every control path. The ! annotation does not denotea type.

It might be necessary to declare a diverging function because as mentionedpreviously, the typechecker checks that every control path in a function ends with areturn (#return-expressions) or diverging expression. So, if my_err were declaredwithout the ! annotation, the following code would not typecheck:

This will not compile without the ! annotation on my_err, since the else branchof 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 controlever enter my_err, no further type judgments about f need to hold, since controlwill never resume in any context that relies on those judgments. Thus the return typeon f only needs to reflect the if branch of the conditional.

6.1.3.4 Extern functions

Extern functions are part of Rust's foreign function interface, providing the oppositefunctionality to external blocks (#external-blocks). Whereas external blocks allowRust code to call foreign code, extern functions with bodies defined in Rust code can

fn my_err(s: &str) -> ! { println!("{}", s); panic!();}

fn f(i: i32) -> i32 { if i == 42 { return 42; } else { my_err("Bad number!"); }}

Page 32: The Rust Reference

be called by foreign code. They are defined in the same way as any other Rustfunction, except that they have the extern modifier.

Unlike normal functions, extern fns have type extern "ABI" fn(). This is thesame type as the functions declared in an extern block.

Extern functions may be called directly from Rust code as Rust uses large,contiguous stack segments like C.

6.1.4 Type aliases

A type alias defines a new name for an existing type (#types). Type aliases aredeclared with the keyword type. Every value has a single, specific type, but mayimplement several different traits, or be compatible with several different typeconstraints.

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:

6.1.5 Structures

A structure is a nominal structure type (#structure-types) defined with the keywordstruct.

An example of a struct item and its use:

// Declares an extern fn, the ABI defaults to "C"extern fn new_i32() -> i32 { 0 }

// Declares an extern fn with "stdcall" ABIextern "stdcall" fn new_i32_stdcall() -> i32 { 0 }

let fptr: extern "C" fn() -> i32 = new_i32;

type Point = (u8, u8);let p: Point = (41, 68);

Page 33: The Rust Reference

A tuple structure is a nominal tuple type (#tuple-types), also defined with thekeyword struct. For example:

A unit-like struct is a structure without any fields, defined by leaving off the list offields entirely. Such types will have a single value. For example:

The precise memory layout of a structure is not specified. One can specify aparticular layout using the repr attribute (#ffi-attributes).

6.1.6 Enumerations

An enumeration is a simultaneous definition of a nominal enumerated type(#enumerated-types) as well as a set of constructors, that can be used to create orpattern-match values of the corresponding enumerated type.

Enumerations are declared with the keyword enum.

An example of an enum item and its use:

struct Point {x: i32, y: i32}let p = Point {x: 10, y: 11};let px: i32 = p.x;

struct Point(i32, i32);let p = Point(10, 11);let px: i32 = match p { Point(x, _) => x };

struct Cookie;let c = [Cookie, Cookie, Cookie, Cookie];

enum Animal { Dog, Cat}

let mut a: Animal = Animal::Dog;a = Animal::Cat;

Page 34: The Rust Reference

Enumeration constructors can have either named or unnamed fields:

In this example, Cat is a struct-like enum variant, whereas Dog is simply called anenum variant.

Enums have a discriminant. You can assign them explicitly:

If a discriminant isn't assigned, they start at zero, and add one for each variant, inorder.

You can cast an enum to get this value:

This only works as long as none of the variants have data attached. If it wereBar(i32), this is disallowed.

6.1.7 Constant items

A constant item is a named constant value which is not associated with a specificmemory location in the program. Constants are essentially inlined wherever they areused, 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 samememory address.

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 };

enum Foo { Bar = 123,}

let x = Foo::Bar as u32; // x is now 123u32

Page 35: The Rust Reference

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 willhave the static lifetime. The compiler is, however, still at liberty to translate theconstant many times, so the address referred to may not be stable.

Constants must be explicitly typed. The type may be bool, char, a number, or atype derived from those primitive types. The derived types are references with thestatic lifetime, fixed-size arrays, tuples, enum variants, and structs.

6.1.8 Static items

A static item is similar to a constant, except that it represents a precise memorylocation in the program. A static is never "inlined" at the usage site, and allreferences to it refer to the same memory location. Static items have the staticlifetime, which outlives all other lifetimes in a Rust program. Static items may beplaced in read-only memory if they do not contain any interior mutability.

Statics may contain interior mutability through the UnsafeCell language item. Allaccess 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 threadsafe access.Statics may not refer to other statics by value, only by reference.Constants cannot refer to statics.

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};

Page 36: The Rust Reference

Constants should in general be preferred over statics, unless large amounts of dataare being stored, or single-address and mutability properties are required.

6.1.8.1 Mutable statics

If a static item is declared with the mut keyword, then it is allowed to be modified bythe program. One of Rust's goals is to make concurrency bugs hard to run into, andthis 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 staticvariable. Care should be taken to ensure that modifications to a mutable static aresafe with respect to other threads running in the same process.

Mutable statics are still very useful, however. They can be used with C libraries andcan also be bound from C libraries (in an extern block).

Mutable statics have the same restrictions as normal statics, except that the type ofthe value is not required to ascribe to Sync.

6.1.9 Traits

A trait describes an abstract interface that types can implement. This interfaceconsists of associated items, which come in three varieties:

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 unsafeunsafe 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 unsafeunsafe fn bump_levels_unsafe2() -> u32 { return atomic_add(&mut LEVELS, 1);}

Page 37: The Rust Reference

functionsconstantstypes

Associated functions whose first parameter is named self are called methods andmay be invoked using . notation (e.g., x.foo()).

All traits define an implicit type parameter Self that refers to "the type that isimplementing this interface". Traits may also contain additional type parameters.These type parameters (including Self) may be constrained by other traits and soforth as usual.

Trait bounds on Self are considered "supertraits". These are required to be acyclic.Supertraits are somewhat different from other constraints in that they affect whatmethods are available in the vtable when the trait is used as a trait object (#trait-objects).

Traits are implemented for specific types through separate implementations(#implementations).

Consider the following trait:

This defines a trait with two methods. All values that have implementations(#implementations) of this trait in scope can have their draw and bounding_boxmethods called, using value.bounding_box() syntax (#method-call-expressions).

Traits can include default implementations of methods, as in:

trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox;}

trait Foo { fn bar(&self); fn baz(&self) { println!("We called baz."); }}

Page 38: The Rust Reference

Here the baz method has a default implementation, so types that implement Fooneed only implement bar. It is also possible for implementing types to override amethod that has a default implementation.

Type parameters can be specified for a trait to make it generic. These appear a�erthe trait name, using the same syntax used in generic functions (#generic-functions).

It is also possible to define associated types for a trait. Consider the followingexample of a Container trait. Notice how the type is available for use in themethod signatures:

In order for a type to implement this trait, it must not only provide implementationsfor every method, but it must specify the type E. Here's an implementation ofContainer for the standard library type Vec:

Generic functions may use traits as bounds on their type parameters. This will havetwo 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

trait Seq<T> { fn len(&self) -> u32; fn elt_at(&self, n: u32) -> T; fn iter<F>(&self, F) where F: Fn(T);}

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); }}

Page 39: The Rust Reference

have the parameter's type.

For example:

Traits also define an trait object (#trait-objects) with the same name as the trait.Values of this type are created by coercing from a pointer of some specific type to apointer of trait type. For example, &T could be coerced to &Shape if T: Shapeholds (and similarly for Box<T>). This coercion can either be implicit or explicit(#type-cast-expressions). Here is an example of an explicit coercion:

The resulting value is a box containing the value that was cast, along withinformation that identifies the methods of the implementation that was used. Valueswith a trait type can have methods called (#method-call-expressions) on them, forany method in the trait, and can be used to instantiate type parameters that arebounded by the trait.

Trait methods may be static, which means that they lack a self argument. Thismeans that they can only be called with function call syntax (f(x)) and not methodcall syntax (obj.f()). The way to refer to the name of a static method is to qualify itwith the trait name, treating the trait name like a module. For example:

fn draw_twice<T: Shape>(surface: Surface, sh: T) { sh.draw(surface); sh.draw(surface);}

trait Shape { }impl Shape for i32 { }let mycircle = 0i32;let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;

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);

Page 40: The Rust Reference

Traits may inherit from other traits. For example, in

the syntax Circle : Shape means that types that implement Circle must alsohave an implementation for Shape. Multiple supertraits are separated by +, traitCircle : Shape + PartialEq { }. In an implementation of Circle for agiven type T, methods can refer to Shape methods, since the typechecker checksthat any type with an implementation of Circle also has an implementation ofShape.

In type-parameterized functions, methods of the supertrait may be called on valuesof subtrait-bound type parameters. Referring to the previous example of traitCircle : Shape:

Likewise, supertrait methods may also be called on trait objects.

6.1.10 Implementations

An implementation is an item that implements a trait (#traits) for a specific type.

Implementations are defined with the keyword impl.

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()}

let mycircle = Box::new(mycircle) as Box<Circle>;let nonsense = mycircle.radius() * mycircle.area();

Page 41: The Rust Reference

It is possible to define an implementation without referring to a trait. The methodsin such an implementation can only be used as direct calls on the values of the typethat the implementation targets. In such an implementation, the trait type and fora�er impl are omitted. Such implementations are limited to nominal types (enums,structs), and the implementation must appear in the same crate as the self type:

When a trait is specified in an impl, all methods declared as part of the trait mustbe implemented, with matching types and type parameter counts.

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} }}

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();

Page 42: The Rust Reference

An implementation can take type parameters, which can be different from the typeparameters taken by the trait it implements. Implementation parameters are writtena�er the impl keyword.

6.1.11 External blocks

External blocks form the basis for Rust's foreign function interface. Declarations inan external block describe symbols in external, non-Rust libraries.

Functions within external blocks are declared in the same way as other Rustfunctions, with the exception that they may not have a body and are insteadterminated by a semicolon.

Functions within external blocks may be called by Rust code, just like functionsdefined in Rust. The Rust compiler automatically translates between the Rust ABIand the foreign ABI.

A number of attributes (#attributes) control the behavior of external blocks.

By default external blocks assume that the library they are calling uses the standardC "cdecl" ABI. Other ABIs may be specified using an abi string, as shown here:

The link attribute allows the name of the library to be specified. When specifiedthe compiler will attempt to link against the native library of the specified name.

impl<T> Seq<T> for Vec<T> { /* ... */}impl Seq<bool> for u32 { /* Treat the integer as a sequence of bits */}

// Interface to the Windows APIextern "stdcall" { }

#[link(name = "crypto")]extern { }

Page 43: The Rust Reference

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 isthe declared return type.

6.2 Visibility and Privacy

These two terms are o�en used interchangeably, and what they are attempting toconvey 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 inthe hierarchy can be thought of as some item. The items are one of those mentionedabove, but also include external crates. Declaring or defining a new module can bethought 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 ofan item to see whether it should be allowed or not. This is where privacy warningsare generated, or otherwise "you used a private item of another module and weren'tallowed to."

By default, everything in Rust is private, with one exception. Enum variants in a pubenum are also public by default. When an item is declared as pub, it can be thoughtof as being accessible to the outside world. For example:

With the notion of an item being either public or private, Rust allows item accessesin two cases:

// Declare a private structstruct Foo;

// Declare a public struct with a private fieldpub struct Bar { field: i32}

// Declare a public enum with two public variantspub enum State { PubliclyAccessibleState, PubliclyAccessibleState2,}

Page 44: The Rust Reference

1. If an item is public, then it can be used externally through any of its publicancestors.

2. If an item is private, it may be accessed by the current module and itsdescendants.

These two cases are surprisingly powerful for creating module hierarchies exposingpublic APIs while hiding internal implementation details. To help explain, here's afew use cases and what they would entail:

A library developer needs to expose functionality to crates which link againsttheir library. As a consequence of the first case, this means that anything which isusable externally must be pub from the root down to the destination item. Anyprivate item in the chain will disallow external accesses.

A crate needs a global available "helper module" to itself, but it doesn't want toexpose the helper module as a public API. To accomplish this, the root of thecrate's hierarchy would have a private module which then internally has a "publicapi". Because the entire crate is a descendant of the root, then the entire localcrate can access this private module through the second case.

When writing unit tests for a module, it's o�en a common idiom to have animmediate child of the module to-be-tested named mod test. This modulecould access any items of the parent module through the second case, meaningthat internal implementation details could also be seamlessly tested from thechild module.

In the second case, it mentions that a private item "can be accessed" by the currentmodule and its descendants, but the exact meaning of accessing an item depends onwhat 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 itis invoked. Additionally, path expressions and import statements are considered toaccess an item in the sense that the import/expression is only valid if the destinationis in the current visibility scope.

Here's an example of a program which exemplifies the three cases outlined above:

Page 45: The Rust Reference

For a rust program to pass the privacy checking pass, all paths must be validaccesses given the two rules above. This includes all use statements, expressions,

// 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(); } }}

Page 46: The Rust Reference

types, etc.

6.2.1 Re-exporting and Visibility

Rust allows publicly re-exporting items through a pub use directive. Because this isa public directive, this allows the item to be used in the current module through therules above. It essentially allows public access into the re-exported item. Forexample, this program is valid:

This means that any external crate referencing implementation::api::f wouldreceive 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 thenamespace hierarchy as it normally would.

6.3 Attributes

Any item declaration may have an attribute applied to it. Attributes in Rust aremodeled 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 toname, convention, and language and compiler version. Attributes may appear as anyof:

A single identifier, the attribute nameAn identifier followed by the equals sign '=' and a literal, providing a key/valuepairAn identifier followed by a parenthesized list of sub-attribute arguments

pub use self::implementation::api;

mod implementation { pub mod api { pub fn f() {} }}

Page 47: The Rust Reference

Attributes with a bang ("!") a�er the hash ("#") apply to the item that the attribute isdeclared within. Attributes that do not have a bang a�er the hash apply to the itemthat follows the attribute.

An example of attributes:

Note: At some point in the future, the compiler will distinguish between language-reserved and user-available attributes. Until then, there is effectively no differencebetween an attribute handled by a loadable syntax extension and the compiler.

6.3.1 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 libraryfunctions that are assumed to existno_main - disable emitting the main symbol. Useful when some other objectbeing linked to defines main.no_start - disable linking to the native crate, which specifies the "start"

// 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;

Page 48: The Rust Reference

language item.no_std - disable linking to the std 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 registrarfunction. The plugin feature gate is required to use this attribute.

6.3.2 Module-only attributes

no_implicit_prelude - disable injecting use std::prelude::* in thismodule.path - specifies the file to load the module from. #[path="foo.rs"] modbar; is equivalent to mod bar { /* contents of foo.rs */ }. The pathis taken relative to the directory that the current module is in.

6.3.3 Function-only attributes

main - indicates that this function should be passed to the entry point, ratherthan the function in the crate root named main.plugin_registrar - mark this function as the registration point for compilerplugins, such as loadable syntax extensions.start - indicates that this function should be used as the entry point, overridingthe "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 caseof --test.should_panic - indicates that this test function should panic, inverting thesuccess condition.cold - The function is unlikely to be executed, so optimize it (and calls to it)differently.

6.3.4 Static-only attributes

thread_local - on a static mut, this signals that the value of this static maychange depending on the current thread. The exact consequences of this areimplementation-defined.

Page 49: The Rust Reference

6.3.5 FFI attributes

On an extern block, the following attributes are interpreted:

link_args - specify arguments to the linker, rather than just the library nameand 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 inthis block to be linked correctly. link supports an optional kind key with threepossible values: dylib, static, and framework. See external blocks for moreabout external blocks. Two examples: #[link(name = "readline")] and #[link(name = "CoreFoundation", kind = "framework")].

On declarations inside an extern block, the following attributes are interpreted:

link_name - the name of the symbol that this function or static should beimported as.linkage - on a static, this specifies the linkage type.

On enums:

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 representedfor, or C, which specifies that it should be the default enum size of the C ABI forthat platform. Note that enum representation in C is undefined, and this may beincorrect when the C code is compiled with certain flags.

On structs:

repr - specifies the representation to use for this struct. Takes a list of options.The currently accepted ones are C and packed, which may be combined. C willuse a C ABI compatible struct layout, and packed will remove any paddingbetween fields (note that this is very fragile and may break platforms whichrequire aligned access).

6.3.6 Macro-related attributes

Page 50: The Rust Reference

macro_use on a mod — macros defined in this module will be visible in themodule's parent, a�er this module has been included.

macro_use on an extern crate — load macros from this crate. An optionallist of names #[macro_use(foo, bar)] restricts the import to just thosemacros named. The extern crate must appear at the crate root, not insidemod, which ensures proper function of the $crate macro variable(book/macros.html#the-variable-$crate).

macro_reexport on an extern crate — re-export the named macros.

macro_export - export a macro for cross-crate usage.

no_link on an extern crate — even if we load this crate for macros, don'tlink it into the output.

See the macros section of the book (book/macros.html#scoping-and-macro-import/export) for more information on macro scope.

6.3.7 Miscellaneous attributes

export_name - on statics and functions, this determines the name of theexported symbol.link_section - on statics and functions, this specifies the section of the objectfile that this item's contents will be placed into.no_mangle - on any item, do not apply the standard name mangling. Set thesymbol for this item to its identifier.packed - on structs or enums, eliminate any padding that would be used to alignfields.simd - on certain tuple structs, derive the arithmetic operators, which lower tothe target's SIMD instructions, if any; the simd feature gate is necessary to usethis attribute.unsafe_no_drop_flag - on structs, remove the flag that prevents destructorsfrom being run twice. Destructors might be run multiple times on the sameobject with this attribute. To use this, the unsafe_no_drop_flag feature gatemust be enabled.doc - Doc comments such as /// foo are equivalent to #[doc = "foo"].

Page 51: The Rust Reference

rustc_on_unimplemented - Write a custom note to be shown along with theerror when the trait is found to be unimplemented on a type. You may use formatarguments like {T}, {A} to correspond to the types at the point of usecorresponding to the type parameters of the trait of the same name. {Self} willbe replaced with the type that is supposed to implement the trait but doesn't. Touse this, the on_unimplemented feature gate must be enabled.

6.3.8 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 releasebuilds.

There are two kinds of configuration options, one that is either defined or not (#[cfg(foo)]), and the other that contains a string that can be checked against (#[cfg(bar = "baz")]). Currently, only compiler-defined configuration optionscan have the latter form.

// The function is only included in the build when compiling for OSX#[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() { // ...}

Page 52: The Rust Reference

This illustrates some conditional compilation can be achieved using the #[cfg(...)] attribute. any, all and not can be used to assemble arbitrarilycomplex configurations through nesting.

The following configurations must be defined by the implementation:

debug_assertions. Enabled by default when compiling withoutoptimizations. This can be used to enable extra debugging code in developmentbut not in production. For example, it controls the behavior of the standardlibrary's debug_assert! macro.target_arch = "...". Target CPU architecture, such as "x86", "x86_64""mips", "powerpc", "arm", or "aarch64".target_endian = "...". Endianness of the target CPU, either "little" or"big".target_family = "...". Operating system family of the target, e. g. "unix"or "windows". The value of this configuration option is defined as aconfiguration itself, like unix or windows.target_os = "...". Operating system of the target, examples include"windows", "macos", "ios", "linux", "android", "freebsd","dragonfly", "bitrig" or "openbsd".target_pointer_width = "...". Target pointer width in bits. This is set to"32" for targets with 32-bit pointers, and likewise set to "64" for 64-bit pointers.unix. See target_family.windows. See target_family.

You can also set another attribute based on a cfg variable with cfg_attr:

Will be the same as #[b] if a is set by cfg, and nothing otherwise.

6.3.9 Lint check attributes

A lint check names a potentially undesirable coding pattern, such as unreachablecode or omitted documentation, for the static entity to which the attribute applies.

#[cfg_attr(a, b)]

Page 53: The Rust Reference

For any lint check C:

allow(C) overrides the check for C so that violations will go unreported,deny(C) signals an error a�er encountering a violation of C,forbid(C) is the same as deny(C), but also forbids changing the lint levela�erwards,warn(C) warns about violations of C but continues compilation.

The lint checks supported by the compiler can be found via rustc -W help, alongwith their default settings. Compiler plugins (book/compiler-plugins.html#lint-plugins) can provide additional lint checks.

This example shows how one can use allow and warn to toggle a particular checkon and off:

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 }}

Page 54: The Rust Reference

This example shows how one can use forbid to disallow uses of allow for that lintcheck:

6.3.10 Language items

Some primitive Rust operations are defined in Rust code, rather than beingimplemented directly in C or assembly language. The definitions of these operationshave to be easy for the compiler to find. The lang attribute makes it possible todeclare these operations. For example, the str module in the Rust standard librarydefines the string equality function:

#[warn(missing_docs)]mod m2{ #[allow(missing_docs)] 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 }}

#[forbid(missing_docs)]mod m3 { // Attempting to toggle warning signals an error here #[allow(missing_docs)] /// Returns 2. pub fn undocumented_too() -> i32 { 2 }}

#[lang = "str_eq"]pub fn eq_slice(a: &str, b: &str) -> bool { // details elided}

Page 55: The Rust Reference

The name str_eq has a special meaning to the Rust compiler, and the presence ofthis definition means that it will use this definition when generating calls to thestring equality function.

The set of language items is currently considered unstable. A complete list of thebuilt-in language items will be added in the future.

6.3.11 Inline attributes

The inline attribute suggests that the compiler should place a copy of the function orstatic in the caller, rather than generating code to call the function or access thestatic 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 beused with care.

#[inline] and #[inline(always)] always cause the function to be serializedinto 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.

6.3.12 derive

The derive attribute allows certain traits to be automatically implemented for datastructures. For example, the following will create an impl for the PartialEq andClone traits for Foo, the type parameter T will be given the PartialEq or Cloneconstraints for the appropriate impl:

#[derive(PartialEq, Clone)]struct Foo<T> { a: i32, b: T}

Page 56: The Rust Reference

The generated impl for PartialEq is equivalent to

6.3.13 Compiler Features

Certain aspects of Rust may be implemented in the compiler, but they're notnecessarily ready for every-day use. These features are o�en 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:

This directive informs the compiler that the feature list: feature1, feature2, andfeature3 should all be enabled. This is only recognized at a crate-level, not at amodule-level. Without this directive, all features are considered off, and using thefeatures will result in a compiler error.

The currently implemented features of the reference compiler are:

advanced_slice_patterns - See the match expressions (#match-expressions)section for discussion; the exact semantics of slice patterns are subject to change,so some types are still unstable.

slice_patterns - OK, actually, slice patterns are just scary and completelyunstable.

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 }}

#![feature(feature1, feature2, feature3)]

Page 57: The Rust Reference

asm - The asm! macro provides a means for inline assembly. This is o�en useful,but the exact syntax for this feature along with its semantics are likely to change,so this macro usage must be opted into.

associated_consts - Allows constants to be defined in impl and traitblocks, so that they can be associated with a type or trait in a similar manner tomethods and associated types.

box_patterns - Allows box patterns, the exact semantics of which is subject tochange.

box_syntax - Allows use of box expressions, the exact semantics of which issubject to change.

concat_idents - Allows use of the concat_idents macro, which is in manyways insufficient for concatenating identifiers, and may be removed entirely forsomething more wholesome.

custom_attribute - Allows the usage of attributes unknown to the compilerso that new attributes can be added in a backwards compatible manner (RFC 572).

custom_derive - Allows the use of #[derive(Foo,Bar)] as sugar for #[derive_Foo] #[derive_Bar], which can be user-defined syntax extensions.

intrinsics - Allows use of the "rust-intrinsics" ABI. Compiler intrinsics areinherently unstable and no promise about them is made.

lang_items - Allows use of the #[lang] attribute. Like intrinsics, langitems are inherently unstable and no promise about them is made.

link_args - This attribute is used to specify custom flags to the linker, but usageis strongly discouraged. The compiler's usage of the system linker is notguaranteed to continue in the future, and if the system linker is not used thenspecifying custom flags doesn't have much meaning.

link_llvm_intrinsics – Allows linking to LLVM intrinsics via #[link_name="llvm.*"].

Page 58: The Rust Reference

linkage - Allows use of the linkage attribute, which is not portable.

log_syntax - Allows use of the log_syntax macro attribute, which is a nastyhack that will certainly be removed.

main - Allows use of the #[main] attribute, which changes the entry point intoa Rust program. This capability is subject to change.

macro_reexport - Allows macros to be re-exported from one crate a�er beingimported from another. This feature was originally designed with the sole usecase of the Rust standard library in mind, and is subject to change.

non_ascii_idents - The compiler supports the use of non-ascii identifiers, butthe implementation is a little rough around the edges, so this can be seen as anexperimental feature for now until the specification of identifiers is fully fleshedout.

no_std - Allows the #![no_std] crate attribute, which disables the implicitextern crate std. This typically requires use of the unstable APIs behind thelibstd "facade", such as libcore and libcollections. It may also cause problemswhen using syntax extensions, including #[derive].

on_unimplemented - Allows the #[rustc_on_unimplemented] attribute,which allows trait definitions to add specialized notes to error messages when animplementation was expected but not found.

optin_builtin_traits - Allows the definition of default and negative traitimplementations. Experimental.

plugin - Usage of compiler plugins (book/compiler-plugins.html) for customlints or syntax extensions. These depend on compiler internals and are subject tochange.

plugin_registrar - Indicates that a crate provides compiler plugins(book/compiler-plugins.html).

quote - Allows use of the quote_*! family of macros, which are implementedvery poorly and will likely change significantly with a proper implementation.

Page 59: The Rust Reference

rustc_attrs - Gates internal #[rustc_*] attributes which may be forinternal use only or have meaning added to them in the future.

rustc_diagnostic_macros- A mysterious feature, used in theimplementation of rustc, not meant for mortals.

simd - Allows use of the #[simd] attribute, which is overly simple and not theSIMD interface we want to expose in the long term.

simd_ffi - Allows use of SIMD vectors in signatures for foreign functions. TheSIMD interface is subject to change.

staged_api - Allows usage of stability markers and #![staged_api] in acrate. Stability markers are also attributes: #[stable], #[unstable], and #[deprecated] are the three levels.

start - Allows use of the #[start] attribute, which changes the entry pointinto a Rust program. This capability, especially the signature for the annotatedfunction, is subject to change.

struct_inherit - Allows using struct inheritance, which is barelyimplemented and will probably be removed. Don't use this.

struct_variant - Structural enum variants (those with named fields). It iscurrently unknown whether this style of enum variant is as fully supported as thetuple-forms, and it's not certain that this style of variant should remain in thelanguage. For now this style of variant is hidden behind a feature flag.

thread_local - The usage of the #[thread_local] attribute is experimentaland should be seen as unstable. This attribute is used to declare a static asbeing unique per-thread leveraging LLVM's implementation which works inconcert with the kernel loader and dynamic linker. This is not necessarilyavailable on all platforms, and usage of it is discouraged.

trace_macros - Allows use of the trace_macros macro, which is a nastyhack that will certainly be removed.

Page 60: The Rust Reference

unboxed_closures - Rust's new closure design, which is currently a work inprogress feature with many known bugs.

unsafe_no_drop_flag - Allows use of the #[unsafe_no_drop_flag]attribute, which removes hidden flag added to a type that implements the Droptrait. The design for the Drop flag is subject to change, and this feature may beremoved in the future.

unmarked_api - Allows use of items within a #![staged_api] crate whichhave not been marked with a stability marker. Such items should not be allowedby the compiler to exist, so if you need this there probably is a compiler bug.

visible_private_types - Allows public APIs to expose otherwise privatetypes, e.g. as the return type of a public function. This capability may be removedin the future.

allow_internal_unstable - Allows macro_rules! macros to be taggedwith the #[allow_internal_unstable] attribute, designed to allow stdmacros to call #[unstable]/feature-gated functionality internally withoutimposing on callers (i.e. making them behave like function calls in terms ofencapsulation).

If a feature is promoted to a language feature, then all existing programs will start toreceive compilation warnings about #![feature] directives which enabled thenew feature (because the directive is no longer necessary). However, if a feature isdecided to be removed from the language, errors will be issued (if there isn't a parsererror first). The directive in this case is no longer necessary, and it's likely thatexisting code will break if the feature isn't removed.

If an unknown feature is found in a directive, it results in a compiler error. Anunknown feature is one which has never been recognized by the compiler.

7 Statements and expressionsRust is primarily an expression language. This means that most forms of value-producing or effect-causing evaluation are directed by the uniform syntax categoryof expressions. Each kind of expression can typically nest within each other kind of

Page 61: The Rust Reference

expression, and rules for evaluation of expressions involve specifying both the valueproduced by the expression and the order in which its sub-expressions arethemselves evaluated.

In contrast, statements in Rust serve mostly to contain and explicitly sequenceexpression evaluation.

7.1 Statements

A statement is a component of a block, which is in turn a component of an outerexpression (#expressions) or function (#functions).

Rust has two kinds of statement: declaration statements (#declaration-statements)and expression statements (#expression-statements).

7.1.1 Declaration statements

A declaration statement is one that introduces one or more names into the enclosingstatement block. The declared names may denote new variables or new items.

7.1.1.1 Item declarations

An item declaration statement has a syntactic form identical to an item (#items)declaration within a module. Declaring an item — a function, enumeration,structure, type, static, trait, implementation or module — locally within a statementblock is simply a way of restricting its scope to a narrow region containing all of itsuses; it is otherwise identical in meaning to declaring the item outside the statementblock.

Note: there is no implicit capture of the function's dynamic environment whendeclaring a function-local item.

7.1.1.2 Variable declarations

A variable declaration introduces a new set of variable, given by a pattern. Thepattern may be followed by a type annotation, and/or an initializer expression. Whenno type annotation is given, the compiler will infer the type, or signal an error if

Page 62: The Rust Reference

insufficient type information is available for definite inference. Any variablesintroduced by a variable declaration are visible from the point of declaration untilthe end of the enclosing block scope.

7.1.2 Expression statements

An expression statement is one that evaluates an expression (#expressions) andignores its result. The type of an expression statement e; is always (), regardless ofthe type of e. As a rule, an expression statement's purpose is to trigger the effects ofevaluating its expression.

7.2 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 haseffects 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 expressionThe order in which to evaluate the sub-expressionsHow 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. Blocksare just another kind of expression, so blocks, statements, expressions, and blocksagain can recursively nest inside each other to an arbitrary depth.

7.2.0.1 Lvalues, rvalues and temporaries

Expressions are divided into two main categories: lvalues and rvalues. Likewisewithin each expression, sub-expressions may occur in lvalue context or rvaluecontext. The evaluation of an expression depends both on its own category and thecontext it occurs within.

An lvalue is an expression that represents a memory location. These expressions arepaths (#path-expressions) (which refer to local variables, function and methodarguments, or static variables), dereferences (*expr), indexing expressions (#index-

Page 63: The Rust Reference

expressions) (expr[expr]), and field references (#field-expressions) (expr.f). Allother expressions are rvalues.

The le� operand of an assignment (#assignment-expressions) or compound-assignment (#compound-assignment-expressions) expression is an lvalue context, asis the single operand of a unary borrow (#unary-operator-expressions). Thediscriminant or subject of a match expression (#match-expressions) may be anlvalue context, if ref bindings are made, but is otherwise an rvalue context. All otherexpression contexts are rvalue contexts.

When an lvalue is evaluated in an lvalue context, it denotes a memory location;when evaluated in an rvalue context, it denotes the value held in that memorylocation.

7.2.0.1.1 Temporary lifetimes

When an rvalue is used in an lvalue context, a temporary un-named lvalue is createdand used instead. The lifetime of temporary values is typically the innermostenclosing statement; the tail expression of a block is considered part of thestatement that encloses the block.

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, asusing 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 temporarywould be freed before the variable could be used). The compiler uses simplesyntactic rules to decide which values are being assigned into a let binding, andtherefore deserve a longer temporary lifetime.

Here are some examples:

let x = foo(&temp()). The expression temp() is an rvalue. As it is beingborrowed, a temporary is created which will be freed a�er the innermostenclosing statement (the let declaration, in this case).let x = temp().foo(). This is the same as the previous example, except thatthe value of temp() is being borrowed via autoref on a method-call. Here we areassuming that foo() is an &self method defined in some trait, say Foo. In

Page 64: The Rust Reference

other words, the expression temp().foo() is equivalent toFoo::foo(&temp()).let x = &temp(). Here, the same temporary is being assigned into x, ratherthan being passed as a parameter, and hence the temporary's lifetime isconsidered to be the enclosing block.let x = SomeStruct { foo: &temp() }. As in the previous case, thetemporary is assigned into a struct which is then assigned into a binding, andhence it is given the lifetime of the enclosing block.let x = [ &temp() ]. As in the previous case, the temporary is assigned intoan array which is then assigned into a binding, and hence it is given the lifetimeof the enclosing block.let ref x = temp(). In this case, the temporary is created using a refbinding, but the result is the same: the lifetime is extended to the enclosing block.

7.2.0.2 Moved and copied types

When a local variable (#variables) is used as an rvalue (#lvalues,-rvalues-and-temporaries) the variable will either be moved or copied, depending on its type. Allvalues whose type implements Copy are copied, all others are moved.

7.2.1 Literal expressions

A literal expression consists of one of the literal (#literals) forms described earlier. Itdirectly describes a number, character, string, boolean value, or the unit value.

(); // unit type"hello"; // string type'5'; // character type5; // integer type

7.2.2 Path expressions

A path (#paths) used as an expression context denotes either a local variable or anitem. Path expressions are lvalues (#lvalues,-rvalues-and-temporaries).

7.2.3 Tuple expressions

Page 65: The Rust Reference

Tuples are written by enclosing zero or more comma-separated expressions inparentheses. They are used to create tuple-typed (#tuple-types) values.

(0.0, 4.5);("a", 4usize, true);

You can disambiguate a single-element tuple from a value in parentheses with acomma:

7.2.4 Structure expressions

There are several forms of structure expressions. A structure expression consists ofthe path (#paths) of a structure item (#structures), followed by a brace-enclosed listof one or more comma-separated name-value pairs, providing the field values of anew instance of the structure. A field name can be any identifier, and is separatedfrom its value expression by a colon. The location denoted by a structure field ismutable if and only if the enclosing structure is mutable.

A tuple structure expression consists of the path (#paths) of a structure item(#structures), followed by a parenthesized list of one or more comma-separatedexpressions (in other words, the path of a structure item followed by a tupleexpression). The structure item must be a tuple structure item.

A unit-like structure expression consists only of the path (#paths) of a structure item(#structures).

The following are examples of structure expressions:

(0,); // single-element tuple(0); // zero in parentheses

Point {x: 10.0, y: 20.0};TuplePoint(10.0, 20.0);let u = game::User {name: "Joe", age: 35, score: 100_000};some_fn::<Cookie>(Cookie);

Page 66: The Rust Reference

A structure expression forms a new value of the named structure type. Note that fora given unit-like structure type, this will always be the same value.

A structure expression can terminate with the syntax .. followed by an expressionto denote a functional update. The expression following .. (the base) must have thesame structure type as the new structure type being formed. The entire expressiondenotes the result of constructing a new structure (with the same type as the baseexpression) with the given values for the fields that were explicitly specified and thevalues in the base expression for all other fields.

7.2.5 Block expressions

A block expression is similar to a module in terms of the declarations that arepossible. Each block conceptually introduces a new namespace scope. Use items canbring new names into scopes and declared items are in scope for only the blockitself.

A block will execute each statement sequentially, and then execute the expression (ifgiven). If the block ends in a statement, its value is ():

If it ends in an expression, its value and type are that of the expression:

7.2.6 Method-call expressions

let base = Point3d {x: 1, y: 2, z: 3};Point3d {y: 0, z: 10, .. base};

let x: () = { println!("Hello."); };

let x: i32 = { println!("Hello."); 5 };

assert_eq!(5, x);

Page 67: The Rust Reference

A method call consists of an expression followed by a single dot, an identifier, and aparenthesized expression-list. Method calls are resolved to methods on specifictraits, either statically dispatching to a method if the exact self-type of the le�-hand-side is known, or dynamically dispatching if the le�-hand-side expression is anindirect trait object (#trait-objects).

7.2.7 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 amethod call expression (#method-call-expressions)). A field expression denotes afield of a structure (#structure-types).

A field access is an lvalue (#lvalues,-rvalues-and-temporaries) referring to the valueof that field. When the type providing the field inherits mutability, it can be assigned(#assignment-expressions) to.

Also, if the type of the expression to the le� of the dot is a pointer, it is automaticallydereferenced as many times as necessary to make the field access possible. In casesof ambiguity, we prefer fewer autoderefs to more.

7.2.8 Array expressions

An array (#array,-and-slice-types) expression is written by enclosing zero or morecomma-separated expressions of uniform type in square brackets.

In the [expr ';' expr] form, the expression a�er the ';' must be a constantexpression that can be evaluated at compile time, such as a literal (#literals) or astatic item (#static-items).

mystruct.myfield;foo().x;(Struct {a: 10, b: 20}).a;

Page 68: The Rust Reference

7.2.9 Index expressions

Array (#array,-and-slice-types)-typed expressions can be indexed by writing a square-bracket-enclosed expression (the index) a�er them. When the array is mutable, theresulting lvalue (#lvalues,-rvalues-and-temporaries) can be assigned to.

Indices are zero-based, and may be of any integral type. Vector access is bounds-checked at compile-time for constant arrays being accessed with a constant indexvalue. Otherwise a check will be performed at run-time that will put the thread in apanicked state if it fails.

([1, 2, 3, 4])[0];

let x = (["a", "b"])[10]; // compiler error: const index-expr is out of bounds

let n = 10;let y = (["a", "b"])[n]; // panics

let arr = ["a", "b"];arr[10]; // panics

Also, if the type of the expression to the le� of the brackets is a pointer, it isautomatically dereferenced as many times as necessary to make the indexingpossible. In cases of ambiguity, we prefer fewer autoderefs to more.

7.2.10 Range expressions

The .. operator will construct an object of one of the std::ops::Range variants.

[1, 2, 3, 4];["a", "b", "c", "d"];[0; 128]; // array with 128 zeros[0u8, 0u8, 0u8, 0u8];

1..2; // std::ops::Range3..; // std::ops::RangeFrom..4; // std::ops::RangeTo..; // std::ops::RangeFull

Page 69: The Rust Reference

The following expressions are equivalent.

7.2.11 Unary operator expressions

Rust defines the following unary operators. They are all written as prefix operators,before the expression they apply to.

- : Negation. May only be applied to numeric types.* : Dereference. When applied to a pointer it denotes the pointed-to location. Forpointers to mutable locations, the resulting lvalue can be assigned to. On non-pointer types, it calls the deref method of the std::ops::Deref trait, or thederef_mut method of the std::ops::DerefMut trait (if implemented by thetype and required for an outer expression that will or could mutate thedereference), and produces the result of dereferencing the & or &mut borrowedpointer returned from the overload method.! : Logical negation. On the boolean type, this flips between true and false.On integer types, this inverts the individual bits in the two's complementrepresentation of the value.& and &mut : Borrowing. When applied to an lvalue, these operators produce areference (pointer) to the lvalue. The lvalue is also placed into a borrowed statefor the duration of the reference. For a shared borrow (&), this implies that thelvalue may not be mutated, but it may be read or shared again. For a mutableborrow (&mut), the lvalue may not be accessed in any way until the borrowexpires. If the & or &mut operators are applied to an rvalue, a temporary value iscreated; the lifetime of this temporary value is defined by syntactic rules.

7.2.12 Binary operator expressions

Binary operators expressions are given in terms of operator precedence (#operator-precedence).

let x = std::ops::Range {start: 0, end: 10};let y = 0..10;

assert_eq!(x,y);

Page 70: The Rust Reference

7.2.12.1 Arithmetic operators

Binary arithmetic expressions are syntactic sugar for calls to built-in traits, definedin the std::ops module of the std library. This means that arithmetic operatorscan be overridden for user-defined types. The default meaning of the operators onstandard types is given here.

+ : Addition and array/string concatenation. Calls the add method on thestd::ops::Add trait.- : Subtraction. Calls the sub method on the std::ops::Sub trait.* : Multiplication. Calls the mul method on the std::ops::Mul trait./ : Quotient. Calls the div method on the std::ops::Div trait.% : Remainder. Calls the rem method on the std::ops::Rem trait.

7.2.12.2 Bitwise operators

Like the arithmetic operators (#arithmetic-operators), bitwise operators are syntacticsugar for calls to methods of built-in traits. This means that bitwise operators can beoverridden for user-defined types. The default meaning of the operators on standardtypes is given here. Bitwise &, | and applied to boolean arguments are equivalentto logical &&, || and != evaluated in non-lazy fashion.

& : Bitwise AND. Calls the bitand method of the std::ops::BitAnd trait.| : Bitwise inclusive OR. Calls the bitor method of the std::ops::BitOrtrait.

: Bitwise exclusive OR. Calls the bitxor method of the std::ops::BitXortrait.<< : Le� shi�. Calls the shl method of the std::ops::Shl trait.>> : Right shi� (arithmetic). Calls the shr method of the std::ops::Shr trait.

7.2.12.3 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 differfrom | and & in that the right-hand operand is only evaluated when the le�-hand

Page 71: The Rust Reference

operand does not already determine the result of the expression. That is, || onlyevaluates its right-hand operand when the le�-hand operand evaluates to false,and && only when it evaluates to true.

7.2.12.4 Comparison operators

Comparison operators are, like the arithmetic operators (#arithmetic-operators), andbitwise operators (#bitwise-operators), syntactic sugar for calls to built-in traits. Thismeans that comparison operators can be overridden for user-defined types. Thedefault meaning of the operators on standard types is given here.

== : Equal to. Calls the eq method on the std::cmp::PartialEq trait.!= : Unequal to. Calls the ne method on the std::cmp::PartialEq trait.< : Less than. Calls the lt method on the std::cmp::PartialOrd trait.> : Greater than. Calls the gt method on the std::cmp::PartialOrd trait.<= : Less than or equal. Calls the le method on the std::cmp::PartialOrdtrait.>= : Greater than or equal. Calls the ge method on thestd::cmp::PartialOrd trait.

7.2.12.5 Type cast expressions

A type cast expression is denoted with the binary operator as.

Executing an as expression casts the value on the le�-hand side to the type on theright-hand side.

An example of an as expression:

fn average(values: &[f64]) -> f64 { let sum: f64 = sum(values); let size: f64 = len(values) as f64; sum / size}

Page 72: The Rust Reference

Some of the conversions which can be done through the as operator can also bedone implicitly at various points in the program, such as argument passing andassignment to a let binding with an explicit type. Implicit conversions are limitedto "harmless" conversions that do not lose information and which have minimal orno risk of surprising side-effects on the dynamic execution semantics.

7.2.12.6 Assignment expressions

An assignment expression consists of an lvalue (#lvalues,-rvalues-and-temporaries)expression followed by an equals sign (=) and an rvalue (#lvalues,-rvalues-and-temporaries) expression.

Evaluating an assignment expression either copies or moves (#moved-and-copied-types) its right-hand operand to its le�-hand operand.

7.2.12.7 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 (#tuple-types) type.

7.2.12.8 Operator precedence

The precedence of Rust binary operators is ordered as follows, going from strong toweak:

x = y;

Page 73: The Rust Reference

as* / %+ -<< >>&^|== != < > <= >=&&||= ..

Operators at the same precedence level are evaluated le�-to-right. Unary operators(#unary-operator-expressions) have the same precedence level and are stronger thanany of the binary operators.

7.2.13 Grouped expressions

An expression enclosed in parentheses evaluates to the result of the enclosedexpression. Parentheses can be used to explicitly specify evaluation order within anexpression.

An example of a parenthesized expression:

7.2.14 Call expressions

A call expression invokes a function, providing zero or more input variables and anoptional location to move the function's output into. If the function eventuallyreturns, then the expression completes.

Some examples of call expressions:

let x: i32 = (2 + 3) * 4;

let x: i32 = add(1i32, 2i32);let pi: Result<f32, _> = "3.14".parse();

Page 74: The Rust Reference

7.2.15 Lambda expressions

A lambda expression (sometimes called an "anonymous function expression")defines a function and denotes it as a value, in a single expression. A lambdaexpression is a pipe-symbol-delimited (|) list of identifiers followed by anexpression.

A lambda expression denotes a function that maps a list of parameters(ident_list) onto the expression that follows the ident_list. The identifiers inthe ident_list are the parameters to the function. These parameters' types neednot be specified, as the compiler infers them from context.

Lambda expressions are most useful when passing functions as arguments to otherfunctions, as an abbreviation for defining and capturing a separate function.

Significantly, lambda expressions capture their environment, which regular functiondefinitions (#functions) do not. The exact type of capture depends on the functiontype (#function-types) inferred for the lambda expression. In the simplest and least-expensive form (analogous to a || { } expression), the lambda expressioncaptures its environment by reference, effectively borrowing pointers to all outervariables mentioned inside the function. Alternately, the compiler may infer that alambda expression should copy or move values (depending on their type) from theenvironment into the lambda expression's captured environment.

In this example, we define a function ten_times that takes a higher-order functionargument, and call it with a lambda expression as an argument:

7.2.16 In�nite loops

fn ten_times<F>(f: F) where F: Fn(i32) { let mut i = 0i32; while i < 10 { f(i); i += 1; }}

ten_times(|j| println!("hello, {}", j));

Page 75: The Rust Reference

A loop expression denotes an infinite loop.

A loop expression may optionally have a label. The label is written as a lifetimepreceding the loop expression, as in 'foo: loop{ }. If a label is present, thenlabeled break and continue expressions nested within this loop may exit out ofthis loop or return control to its head. See Break expressions (#break-expressions)and Continue expressions (#continue-expressions).

7.2.17 Break expressions

A break expression has an optional label. If the label is absent, then executing abreak expression immediately terminates the innermost loop enclosing it. It is onlypermitted in the body of a loop. If the label is present, then break 'foo terminatesthe loop with label 'foo, which need not be the innermost label enclosing thebreak expression, but must enclose it.

7.2.18 Continue expressions

A continue expression has an optional label. If the label is absent, then executing acontinue expression immediately terminates the current iteration of theinnermost loop enclosing it, returning control to the loop head. In the case of awhile loop, the head is the conditional expression controlling the loop. In the caseof a for loop, the head is the call-expression controlling the loop. If the label ispresent, then continue 'foo returns control to the head of the loop with label'foo, which need not be the innermost label enclosing the break expression, butmust enclose it.

A continue expression is only permitted in the body of a loop.

7.2.19 While loops

A while loop begins by evaluating the boolean loop conditional expression. If theloop conditional expression evaluates to true, the loop body block executes andcontrol returns to the loop conditional expression. If the loop conditional expressionevaluates to false, the while expression completes.

Page 76: The Rust Reference

An example:

Like loop expressions, while loops can be controlled with break or continue,and may optionally have a label. See infinite loops (#infinite-loops), breakexpressions (#break-expressions), and continue expressions (#continue-expressions)for more information.

7.2.20 For expressions

A for expression is a syntactic construct for looping over elements provided by animplementation of std::iter::IntoIterator.

An example of a for loop over the contents of an array:

An example of a for loop over a series of integers:

Like loop expressions, for loops can be controlled with break or continue, andmay optionally have a label. See infinite loops (#infinite-loops), break expressions(#break-expressions), and continue expressions (#continue-expressions) for moreinformation.

let mut i = 0;

while i < 10 { println!("hello"); i = i + 1;}

let v: &[Foo] = &[a, b, c];

for e in v { bar(e);}

for i in 0..256 { bar(i);}

Page 77: The Rust Reference

7.2.21 If expressions

An if expression is a conditional branch in program control. The form of an ifexpression is a condition expression, followed by a consequent block, any number ofelse if conditions and blocks, and an optional trailing else block. The conditionexpressions must have type bool. If a condition expression evaluates to true, theconsequent block is executed and any subsequent else if or else block isskipped. If a condition expression evaluates to false, the consequent block isskipped and any subsequent else if condition is evaluated. If all if and elseif conditions evaluate to false then any else block is executed.

7.2.22 Match expressions

A match expression branches on a pattern. The exact form of matching that occursdepends on the pattern. Patterns consist of some combination of literals,destructured arrays or enum constructors, structures and tuples, variable bindingspecifications, wildcards (..), and placeholders (_). A match expression has a headexpression, which is the value to compare to the patterns. The type of the patternsmust equal the type of the head expression.

In a pattern whose head expression has an enum type, a placeholder (_) stands for asingle data field, whereas a wildcard .. stands for all the fields of a particularvariant.

A match behaves differently depending on whether or not the head expression is anlvalue or an rvalue (#lvalues,-rvalues-and-temporaries). If the head expression is anrvalue, it is first evaluated into a temporary location, and the resulting value issequentially compared to the patterns in the arms until a match is found. The firstarm with a matching pattern is chosen as the branch target of the match, anyvariables bound by the pattern are assigned to local variables in the arm's block, andcontrol enters the block.

When the head expression is an lvalue, the match does not allocate a temporarylocation (however, a by-value binding may copy or move from the lvalue). Whenpossible, it is preferable to match on lvalues, as the lifetime of these matches

Page 78: The Rust Reference

inherits the lifetime of the lvalue, rather than being restricted to the inside of thematch.

An example of a match expression:

Patterns that bind variables default to binding to a copy or move of the matchedvalue (depending on the matched value's type). This can be changed to bind to areference by using the ref keyword, or to a mutable reference using ref mut.

Subpatterns can also be bound to variables by the use of the syntax variable @subpattern. For example:

Patterns can also dereference pointers by using the &, &mut and box symbols, asappropriate. For example, these two matches on x: &i32 are equivalent:

let x = 1;

match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 => println!("four"), 5 => println!("five"), _ => println!("something else"),}

let x = 1;

match x { e @ 1 ... 5 => println!("got a range element {}", e), _ => println!("anything"),}

let y = match *x { 0 => "zero", _ => "some" };let z = match x { &0 => "zero", _ => "some" };

assert_eq!(y, z);

Page 79: The Rust Reference

A pattern that's just an identifier, like Nil in the previous example, could eitherrefer to an enum variant that's in scope, or bind a new variable. The compilerresolves this ambiguity by forbidding variable bindings that occur in match patternsfrom shadowing names of variants that are in scope. For example, wherever List isin scope, a match pattern would not be able to bind Nil as a new name. Thecompiler interprets a variable pattern x as a binding only if there is no variantnamed x in scope. A convention you can use to avoid conflicts is simply to namevariants with upper-case letters, and local variables with lower-case letters.

Multiple match patterns may be joined with the | operator. A range of values may bespecified with .... For example:

Range patterns only work on scalar types (like integers and characters; not likearrays 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 formatching a case. Pattern guards appear a�er the pattern and consist of a bool-typedexpression following the if keyword. A pattern guard may refer to the variablesbound within the pattern they follow.

7.2.23 If let expressions

let message = match x { 0 | 1 => "not many", 2 ... 9 => "a few", _ => "lots"};

let message = match maybe_digit { Some(x) if x < 10 => process_digit(x), Some(x) => process_other(x), None => panic!()};

Page 80: The Rust Reference

An if let expression is semantically identical to an if expression but in place ofa condition expression it expects a refutable let statement. If the value of theexpression on the right hand side of the let statement matches the pattern, thecorresponding block will execute, otherwise flow proceeds to the first else blockthat follows.

7.2.24 While let loops

A while let loop is semantically identical to a while loop but in place of acondition expression it expects a refutable let statement. If the value of theexpression on the right hand side of the let statement matches the pattern, the loopbody block executes and control returns to the pattern matching statement.Otherwise, the while expression completes.

7.2.25 Return expressions

Return expressions are denoted with the keyword return. Evaluating a returnexpression moves its argument into the designated output location for the currentfunction call, destroys the current function activation frame, and transfers control tothe caller frame.

An example of a return expression:

let dish = ("Ham", "Eggs");

// this body will be skipped because the pattern is refutedif let ("Bacon", b) = dish { println!("Bacon is served with {}", b);}

// this body will executeif let ("Ham", b) = dish { println!("Ham is served with {}", b);}

Page 81: The Rust Reference

8 Type system

8.1 Types

Every variable, item and value in a Rust program has a type. The type of a valuedefines the interpretation of the memory holding it.

Built-in types and type-constructors are tightly integrated into the language, innontrivial ways that are not possible to emulate in user-defined types. User-definedtypes have limited capabilities.

8.1.1 Primitive types

The primitive types are the following:

The boolean type bool with values true and false.The machine types (integer and floating-point).The machine-dependent integer types.

8.1.1.1 Machine types

The machine types are the following:

The unsigned word types u8, u16, u32 and u64, with values drawn from theinteger intervals [0, 2 - 1], [0, 2 - 1], [0, 2 - 1] and [0, 2 - 1] respectively.

The signed two's complement word types i8, i16, i32 and i64, with valuesdrawn from the integer intervals [-(2 ), 2 - 1], [-(2 ), 2 - 1], [-(2 ), 2 - 1], [-(2 ),2 - 1] respectively.

fn max(a: i32, b: i32) -> i32 { if a > b { return a; } return b;}

8 16 32 64

7 7 15 15 31 31 63

63

Page 82: The Rust Reference

The IEEE 754-2008 binary32 and binary64 floating-point types: f32 andf64, respectively.

8.1.1.2 Machine-dependent integer types

The usize type is an unsigned integer type with the same number of bits as theplatform'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 theplatform's pointer type. The theoretical upper bound on object and array size is themaximum isize value. This ensures that isize can be used to calculatedifferences between pointers into an object or array and can address every bytewithin an object along with one byte past the end.

8.1.2 Textual types

The types char and str hold textual data.

A value of type char is a Unicode scalar value(http://www.unicode.org/glossary/#unicode_scalar_value) (i.e. a code point that is nota surrogate), represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or0xE000 to 0x10FFFF range. A [char] array is effectively an UCS-4 / UTF-32 string.

A value of type str is a Unicode string, represented as an array of 8-bit unsignedbytes holding a sequence of UTF-8 code points. Since str is of unknown size, it isnot a first-class type, but can only be instantiated through a pointer type, such as&str.

8.1.3 Tuple types

A tuple type is a heterogeneous product of other types, called the elements of thetuple. 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 Nth element.

Page 83: The Rust Reference

An example of a tuple type and its use:

For historical reasons and convenience, the tuple type with no elements (()) is o�encalled ‘unit’ or ‘the unit type’.

8.1.4 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.

An example of each kind:

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 anarray or slice is always bounds-checked.

8.1.5 Structure types

A struct type is a heterogeneous product of other types, called the fields of thetype.

type Pair<'a> = (i32, &'a str);let p: Pair<'static> = (10, "hello");let (a, b) = p;assert!(b != "world");assert!(p.0 == 10);

let vec: Vec<i32> = vec![1, 2, 3];let arr: [i32; 3] = [1, 2, 3];let s: &[i32] = &vec[..];

5 (#fn5)

Page 84: The Rust Reference

New instances of a struct can be constructed with a struct expression (#structure-expressions).

The memory layout of a struct is undefined by default to allow for compileroptimizations 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 structexpression; the resulting struct value will always have the same memory layout.

The fields of a struct may be qualified by visibility modifiers (#visibility-and-privacy), to allow access to data in a structure outside a module.

A tuple struct type is just like a structure type, except that the fields are anonymous.

A unit-like struct type is like a structure type, except that it has no fields. The onevalue constructed by the associated structure expression (#structure-expressions) isthe only value that inhabits such a type.

8.1.6 Enumerated types

An enumerated type is a nominal, heterogeneous disjoint union type, denoted by thename of an enum item (#enumerations).

An enum item (#enumerations) declares both the type and a number of variantconstructors, each of which is independently named and takes an optional tuple ofarguments.

New instances of an enum can be constructed by calling one of the variantconstructors, in a call expression (#call-expressions).

Any enum value consumes as much memory as the largest variant constructor for itscorresponding enum type.

Enum types cannot be denoted structurally as types, but must be denoted by namedreference to an enum item (#enumerations).

8.1.7 Recursive types

6 (#fn6)

Page 85: The Rust Reference

Nominal types — enumerations (#enumerated-types) and structures (#structure-types) — may be recursive. That is, each enum constructor or struct field mayrefer, directly or indirectly, to the enclosing enum or struct type itself. Suchrecursion has restrictions:

Recursive types must include a nominal type in the recursion (not mere typedefinitions, or other structural types such as arrays or tuples).A recursive enum item must have at least one non-recursive constructor (in orderto give the recursion a basis case).The size of a recursive type must be finite; in other words the recursive fields ofthe type must be pointer types.Recursive type definitions can cross module boundaries, but not module visibilityboundaries, or crate boundaries (in order to simplify the module system and typechecker).

An example of a recursive type and its use:

8.1.8 Pointer types

All pointers in Rust are explicit first-class values. They can be copied, stored into datastructures, and returned from functions. There are two varieties of pointer in Rust:

References (&) : These point to memory owned by some other value. A referencetype is written &type, or &'a type when you need to specify an explicitlifetime. Copying a reference is a "shallow" operation: it involves only copying thepointer itself. Releasing a reference has no effect on the value it points to, but areference of a temporary value will keep it alive during the scope of the referenceitself.

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))));

Page 86: The Rust Reference

Raw pointers (*) : Raw pointers are pointers without safety or livenessguarantees. 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 rawpointer has no effect on the lifecycle of any other value. Dereferencing a rawpointer or converting it to any other pointer type is an unsafe operation(#unsafe-functions). Raw pointers are generally discouraged in Rust code; theyexist to support interoperability with foreign code, and writing performance-critical or low-level functions.

The standard library contains additional 'smart pointer' types beyond references andraw pointers.

8.1.9 Function types

The function type constructor fn forms new function types. A function type consistsof a possibly-empty set of function-type modifiers (such as unsafe or extern), asequence of input types and an output type.

An example of a fn type:

8.1.9.1 Function types for speci�c items

Internally to the compiler, there are also function types that are specific to aparticular function item. In the following snippet, for example, the internal types ofthe functions foo and bar are different, despite the fact that they have the samesignature:

fn add(x: i32, y: i32) -> i32 { return x + y;}

let mut x = add(5,7);

type Binop = fn(i32, i32) -> i32;let bo: Binop = add;x = bo(5,7);

Page 87: The Rust Reference

The types of foo and bar can both be implicitly coerced to the fn pointer typefn(). There is currently no syntax for unique fn types, though the compiler willemit a type like fn() {foo} in error messages to indicate "the unique fn type forthe function foo".

8.1.10 Closure types

A lambda expression (#lambda-expressions) 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 ofthe closure traits:

FnOnce : The closure can be called once. A closure called as FnOnce can moveout 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 implies FnOnce.

Fn : The closure can be called multiple times through a shared reference. Aclosure called as Fn can neither move out from nor mutate values from itsenvironment. Fn implies FnMut and FnOnce.

8.1.11 Trait objects

In Rust, a type like &SomeTrait or Box<SomeTrait> is called a trait object. Eachinstance of a trait object includes:

a pointer to an instance of a type T that implements SomeTraita virtual method table, o�en just called a vtable, which contains, for each methodof SomeTrait that T implements, a pointer to T's implementation (i.e. afunction pointer).

fn foo() { }fn bar() { }

Page 88: The Rust Reference

The purpose of trait objects is to permit "late binding" of methods. A call to a methodon a trait object is only resolved to a vtable entry at compile time. The actualimplementation 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. Objectsafety rules are defined in RFC 255 (https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md).

Given a pointer-typed expression E of type &T or Box<T>, where T implementstrait R, casting E to the corresponding pointer type &R or Box<R> results in a valueof the trait object R. This result is represented as a pair of pointers: the vtablepointer for the T implementation of R, and the pointer value of E.

An example of a trait object:

In this example, the trait Printable occurs as a trait object in both the typesignature of print, and the cast expression in main.

8.1.12 Type parameters

Within the body of an item that has type parameter declarations, the names of itstype parameters are types:

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>);}

Page 89: The Rust Reference

Here, first has type A, referring to to_vec's A type parameter; and rest hastype Vec<A>, a vector with element type A.

8.1.13 Self types

The special type Self has a meaning within traits and impls. In a trait definition, itrefers to an implicit type parameter representing the "implementing" type. In animpl, it is an alias for the implementing type. For example, in:

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 methodmake_string.

8.2 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 tolifetimes and between types with higher ranked lifetimes. If we were to eraselifetimes from types, then the only subtyping would be due to type equality.

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}

trait Printable { fn make_string(&self) -> String;}

impl Printable for String { fn make_string(&self) -> String { (*self).clone() }}

Page 90: The Rust Reference

Consider the following example: string literals always have 'static lifetime.Nevertheless, we can assign s to t:

Since 'static "lives longer" than 'a, &'static str is a subtype of &'a str.

8.3 Type coercions

Coercions are defined in RFC401 (https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md). A coercion is implicit and has nosyntax.

8.3.1 Coercion sites

A coercion can only occur at certain coercion sites in a program; these are typicallyplaces where the desired type is explicit or can be dervied by propagation fromexplicit types (without type inference). Possible coercion sites are:

let statements where an explicit type is given.

In let _: U = e;, e is coerced to have type U.

static and const statements (similar to let statements).

arguments for function calls.

The value being coerced is the actual parameter and it is coerced to the type ofthe formal parameter. For example, let foo be defined as fn foo(x: U) {... } and call it as foo(e);. Then e is coerced to have type U;

instantiations of struct or variant fields.

Assume we have a struct Foo { x: U } and instantiate it as Foo { x: e}. Then e is coerced to have type U.

fn bar<'a>() { let s: &'static str = "hi"; let t: &'a str = s;}

Page 91: The Rust Reference

function results (either the final line of a block if it is not semicolon terminated orany expression in a return statement).

In fn foo() -> U { e }, e is coerced to to have type U.

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 andtheir relevant sub-expressions are:

array literals, where the array has type [U; n]. Each sub-expression in the arrayliteral is a coercion site for coercion to type U.

array literals with repeating syntax, where the array has type [U; n]. Therepeated sub-expression is a coercion site for coercion to type U.

tuples, where a tuple is a coercion site to type (U_0, U_1, ..., U_n). Eachsub-expression is a coercion site to the respective type, e.g. the zeroth sub-expression is a coercion site to type U_0.

parenthesised sub-expressions ((e)). If the expression has type U, then the sub-expression is a coercion site to U.

blocks. If a block has type U, then the last expression in the block (if it is notsemicolon-terminated) is a coercion site to U. This includes blocks which are partof control flow statements, such as if/else, if the block has a known type.

8.3.2 Coercion types

Coercion is allowed between the following types:

T to U if T is a subtype of U (reflexive case).

T_1 to T_3 where T_1 coerces to T_2 and T_2 coerces to T_3 (transitive case).

Note that this is not fully supported yet

&mut T to &T.

Page 92: The Rust Reference

*mut T to *const T.

&T to *const T.

&mut T to *mut T.

&T to &U if T implements Deref<Target = U>. For example:

&mut T to &mut U if T implements DerefMut<Target = U>.

TyCtor(T) to TyCtor(coerce_inner(T)), where TyCtor(T) is one of

&T&mut T*const T*mut TBox<T>

and where - coerce_inner([T, ..n]) = [T] - coerce_inner(T) = U where T is aconcrete type which implements the trait U.

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.}

Page 93: The Rust Reference

In the future, coerce_inner will be recursively extended to tuples and structs. Inaddition, coercions from sub-traits to super-traits will be added. See RFC401(https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md) for moredetails.

9 Special traitsSeveral traits define special evaluation behavior.

9.1 The Copy trait

The Copy trait changes the semantics of a type implementing it. Values whose typeimplements Copy are copied rather than moved upon assignment.

9.2 The Sized trait

The Sized trait indicates that the size of this type is known at compile-time.

9.3 The Drop trait

The Drop trait provides a destructor, to be run whenever a value of this type is to bedestroyed.

9.4 The Deref trait

The Deref<Target = U> trait allows a type to implicitly implement all themethods of the type U. When attempting to resolve a method call, the compiler willsearch the top-level type for the implementation of the called method. If no suchmethod is found, .deref() is called and the compiler continues to search for themethod implementation in the returned type U.

10 Memory model

Page 94: The Rust Reference

A Rust program's memory consists of a static set of items and a heap. Immutableportions of the heap may be safely shared between threads, mutable portions maynot be safely shared, but several mechanisms for effectively-safe sharing of mutablevalues, built on unsafe code but enforcing a safe locking discipline, exist in thestandard library.

Allocations in the stack consist of variables, and allocations in the heap consist ofboxes.

10.0.1 Memory allocation and lifetime

The items of a program are those functions, modules and types that have their valuecalculated at compile-time and stored uniquely in the memory image of the rustprocess. Items are neither dynamically allocated nor freed.

The heap is a general term that describes boxes. The lifetime of an allocation in theheap depends on the lifetime of the box values pointing to it. Since box values maythemselves be passed in and out of frames, or stored in the heap, heap allocationsmay outlive the frame they are allocated within.

10.0.2 Memory ownership

When a stack frame is exited, its local allocations are all released, and its referencesto boxes are dropped.

10.0.3 Variables

A variable is a component of a stack frame, either a named function parameter, ananonymous temporary (#lvalues,-rvalues-and-temporaries), or a named localvariable.

A local variable (or stack-local allocation) holds a value directly, allocated within thestack's memory. The value is a part of the stack frame.

Local variables are immutable unless declared otherwise like: let mut x = ....

Page 95: The Rust Reference

Function parameters are immutable unless declared with mut. The mut keywordapplies only to the following parameter (so |mut x, y| and fn f(mut x:Box<i32>, y: Box<i32>) declare one mutable variable x and one immutablevariable y).

Methods that take either self or Box<Self> can optionally place them in amutable variable by prefixing them with mut (similar to regular arguments):

Local variables are not initialized when allocated; the entire frame worth of localvariables are allocated at once, on frame-entry, in an uninitialized state. Subsequentstatements within a function may or may not initialize the local variables. Localvariables can be used only a�er they have been initialized; this is enforced by thecompiler.

11 LinkageThe Rust compiler supports various methods to link crates together both staticallyand dynamically. This section will explore the various methods to link Rust cratestogether, and more information about native libraries can be found in the ffi sectionof the book (book/ffi.html).

In one session of compilation, the compiler can generate multiple artifacts throughthe usage of either command line flags or the crate_type attribute. If one or morecommand line flag is specified, all crate_type attributes will be ignored in favorof only building the artifacts specified by command line.

--crate-type=bin, #[crate_type = "bin"] - A runnable executable willbe produced. This requires that there is a main function in the crate which willbe run when the program begins executing. This will link in all Rust and nativedependencies, producing a distributable binary.

trait Changer { fn change(mut self) -> Self; fn modify(mut self: Box<Self>) -> Box<Self>;}

Page 96: The Rust Reference

--crate-type=lib, #[crate_type = "lib"] - A Rust library will beproduced. This is an ambiguous concept as to what exactly is produced because alibrary can manifest itself in several forms. The purpose of this generic liboption is to generate the "compiler recommended" style of library. The outputlibrary will always be usable by rustc, but the actual type of library may changefrom time-to-time. The remaining output types are all different flavors oflibraries, and the lib type can be seen as an alias for one of them (but the actualone is compiler-defined).

--crate-type=dylib, #[crate_type = "dylib"] - A dynamic Rustlibrary will be produced. This is different from the lib output type in that thisforces dynamic library generation. The resulting dynamic library can be used as adependency 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 staticsystem library will be produced. This is different from other library outputs inthat the Rust compiler will never attempt to link to staticlib outputs. Thepurpose of this output type is to create a static library containing all of the localcrate'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 isrecommended for use in situations such as linking Rust code into an existing non-Rust application because it will not have dynamic dependencies on other Rustcode.

--crate-type=rlib, #[crate_type = "rlib"] - A "Rust library" file willbe produced. This is used as an intermediate artifact and can be thought of as a"static Rust library". These rlib files, unlike staticlib files, are interpreted bythe Rust compiler in future linkage. This essentially means that rustc will lookfor metadata in rlib files like it looks for metadata in dynamic libraries. Thisform of output is used to produce statically linked executables as well asstaticlib outputs.

Note that these outputs are stackable in the sense that if multiple are specified, thenthe 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

Page 97: The Rust Reference

crate_type attributes are specified, then they will all be built, but if one or more --crate-type command line flag is specified, then only those outputs will be built.

With all these different kinds of outputs, if crate A depends on crate B, then thecompiler could find B in various different forms throughout the system. The onlyforms looked for by the compiler, however, are the rlib format and the dynamiclibrary format. With these two options for a dependent library, the compiler must atsome point make a choice between these two formats. With this in mind, thecompiler follows these rules when determining what format of dependencies will beused:

1. If a static library is being produced, all upstream dependencies are required to beavailable in rlib formats. This requirement stems from the reason that adynamic library cannot be converted into a static format.

Note that it is impossible to link in native dynamic dependencies to a staticlibrary, and in this case warnings will be printed about all unlinked nativedynamic dependencies.

2. If an rlib file is being produced, then there are no restrictions on what formatthe upstream dependencies are available in. It is simply required that allupstream dependencies be available for reading metadata from.

The reason for this is that rlib files do not contain any of their upstreamdependencies. It wouldn't be very efficient for all rlib files to contain a copy oflibstd.rlib!

3. If an executable is being produced and the -C prefer-dynamic flag is notspecified, then dependencies are first attempted to be found in the rlib format.If some dependencies are not available in an rlib format, then dynamic linking isattempted (see below).

4. If a dynamic library or an executable that is being dynamically linked is beingproduced, then the compiler will attempt to reconcile the available dependenciesin either the rlib or dylib format to create a final product.

Page 98: The Rust Reference

A major goal of the compiler is to ensure that a library never appears more thanonce in any artifact. For example, if dynamic libraries B and C were eachstatically linked to library A, then a crate could not link to B and C togetherbecause there would be two copies of A. The compiler allows mixing the rlib anddylib formats, but this restriction must be satisfied.

The compiler currently implements no method of hinting what format a libraryshould be linked with. When dynamically linking, the compiler will attempt tomaximize dynamic dependencies while still allowing some dependencies to belinked in via an rlib.

For most situations, having all libraries available as a dylib is recommended ifdynamically linking. For other situations, the compiler will emit a warning if it isunable to determine which formats to link each library with.

In general, --crate-type=bin or --crate-type=lib should be sufficient forall compilation needs, and the other options are just available if more fine-grainedcontrol is desired over the output format of a Rust crate.

12 Appendix: Rationales and design tradeoffsTODO.

13 Appendix: In�uencesRust is not a particularly original language, with design elements coming from awide range of sources. Some of these are listed below (including elements that havesince been removed):

SML, OCaml: algebraic datatypes, pattern matching, type inference, semicolonstatement separationC++: references, RAII, smart pointers, move semantics, monomorphisation,memory modelML Kit, Cyclone: region based memory managementHaskell (GHC): typeclasses, type familiesNewsqueak, Alef, Limbo: channels, concurrencyErlang: message passing, thread failure, linked thread failure, lightweight

Page 99: The Rust Reference

concurrencySwi�: optional bindingsScheme: hygienic macrosC#: attributesRuby: block syntaxNIL, Hermes: typestateUnicode Annex #31: identifier and pattern syntax

1. Substitute definitions for the special Unicode productions are provided to thegrammar verifier, restricted to ASCII range, when verifying the grammar in thisdocument. ↩ (#fnref1)

2. Non-ASCII characters in identifiers are currently feature gated. This is expected toimprove soon. ↩ (#fnref2)

3. This distinction would also exist in an interpreter. Static checks like syntacticanalysis, type checking, and lints should happen before the program is executedregardless of when it is executed. ↩ (#fnref3)

4. A crate is somewhat analogous to an assembly in the ECMA-335 CLI model, alibrary in the SML/NJ Compilation Manager, a unit in the Owens and Flatt modulesystem, or a configuration in Mesa. ↩ (#fnref4)

5. struct types are analogous to struct types in C, the record types of the MLfamily, or the structure types of the Lisp family. ↩ (#fnref5)

6. The enum type is analogous to a data constructor declaration in ML, or a pickADT in Limbo. ↩ (#fnref6)

Copyright © 2011-2015 The Rust Project Developers. Licensed under the Apache License, Version 2.0 or theMIT license, at your option.

This file may not be copied, modified, or distributed except according to those terms.