1 % The Rust Language Tutorial
5 Rust is a programming language with a focus on type safety, memory
6 safety, concurrency and performance. It is intended for writing
7 large-scale, high-performance software that is free from several
8 classes of common errors. Rust has a sophisticated memory model that
9 encourages efficient data structures and safe concurrency patterns,
10 forbidding invalid memory accesses that would otherwise cause
11 segmentation faults. It is statically typed and compiled ahead of
14 As a multi-paradigm language, Rust supports writing code in
15 procedural, functional and object-oriented styles. Some of its
16 pleasant high-level features include:
18 * **Type inference.** Type annotations on local variable declarations
20 * **Safe task-based concurrency.** Rust's lightweight tasks do not share
21 memory, instead communicating through messages.
22 * **Higher-order functions.** Efficient and flexible closures provide
23 iteration and other control structures
24 * **Pattern matching and algebraic data types.** Pattern matching on
25 Rust's enumeration types (a more powerful version of C's enums,
26 similar to algebraic data types in functional languages) is a
27 compact and expressive way to encode program logic.
28 * **Polymorphism.** Rust has type-parametric functions and
29 types, type classes and OO-style interfaces.
33 This is an introductory tutorial for the Rust programming language. It
34 covers the fundamentals of the language, including the syntax, the
35 type system and memory model, generics, and modules. [Additional
36 tutorials](#what-next) cover specific language features in greater
39 This tutorial assumes that the reader is already familiar with one or
40 more languages in the C family. Understanding of pointers and general
41 memory management techniques will help.
45 Throughout the tutorial, language keywords and identifiers defined in
46 example code are displayed in `code font`.
48 Code snippets are indented, and also shown in a monospaced font. Not
49 all snippets constitute whole programs. For brevity, we'll often show
50 fragments of programs that don't compile on their own. To try them
51 out, you might have to wrap them in `fn main() { ... }`, and make sure
52 they don't contain references to names that aren't actually defined.
54 > ***Warning:*** Rust is a language under ongoing development. Notes
55 > about potential changes to the language, implementation
56 > deficiencies, and other caveats appear offset in blockquotes.
60 > **WARNING**: The tarball and installer links are for the most recent
61 > release, not master. To use master, you **must** build from [git].
63 The Rust compiler currently must be built from a [tarball] or [git], unless
64 you are on Windows, in which case using the [installer][win-exe] is
65 recommended. There is a list of community-maintained nightly builds and
66 packages [on the wiki][wiki-packages].
68 Since the Rust compiler is written in Rust, it must be built by
69 a precompiled "snapshot" version of itself (made in an earlier state
70 of development). The source build automatically fetches these snapshots
71 from the Internet on our supported platforms.
73 Snapshot binaries are currently built and tested on several platforms:
75 * Windows (7, 8, Server 2008 R2), x86 only
76 * Linux (2.6.18 or later, various distributions), x86 and x86-64
77 * OSX 10.7 (Lion) or greater, x86 and x86-64
79 You may find that other platforms work, but these are our "tier 1"
80 supported build environments that are most likely to work.
82 > ***Note:*** Windows users should read the detailed
83 > "[getting started][wiki-start]" notes on the wiki. Even when using
84 > the binary installer, the Windows build requires a MinGW installation,
85 > the precise details of which are not discussed here. Finally, `rustc` may
86 > need to be [referred to as `rustc.exe`][bug-3319]. It's a bummer, we
89 [bug-3319]: https://github.com/mozilla/rust/issues/3319
90 [wiki-start]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust
91 [git]: https://github.com/mozilla/rust.git
93 To build from source you will also need the following prerequisite
96 * g++ 4.4 or clang++ 3.x
97 * python 2.6 or later (but not 3.x)
99 * gnu make 3.81 or later
102 If you've fulfilled those prerequisites, something along these lines
106 $ curl -O http://static.rust-lang.org/dist/rust-0.9.tar.gz
107 $ tar -xzf rust-0.9.tar.gz
110 $ make && make install
113 You may need to use `sudo make install` if you do not normally have
114 permission to modify the destination directory. The install locations
115 can be adjusted by passing a `--prefix` argument to
116 `configure`. Various other options are also supported: pass `--help`
117 for more information on them.
119 When complete, `make install` will place several programs into
120 `/usr/local/bin`: `rustc`, the Rust compiler, and `rustdoc`, the
121 API-documentation tool.
123 [tarball]: http://static.rust-lang.org/dist/rust-0.9.tar.gz
124 [win-exe]: http://static.rust-lang.org/dist/rust-0.9-install.exe
126 ## Compiling your first program
128 Rust program files are, by convention, given the extension `.rs`. Say
129 we have a file `hello.rs` containing this program:
137 If the Rust compiler was installed successfully, running `rustc
138 hello.rs` will produce an executable called `hello` (or `hello.exe` on
139 Windows) which, upon running, will likely do exactly what you expect.
141 The Rust compiler tries to provide useful information when it encounters an
142 error. If you introduce an error into the program (for example, by changing
143 `println!` to some nonexistent macro), and then compile it, you'll see
144 an error message like this:
147 hello.rs:2:5: 2:24 error: macro undefined: 'print_with_unicorns'
148 hello.rs:2 print_with_unicorns!("hello?");
152 In its simplest form, a Rust program is a `.rs` file with some types
153 and functions defined in it. If it has a `main` function, it can be
154 compiled to an executable. Rust does not allow code that's not a
155 declaration to appear at the top level of the file: all statements must
156 live inside a function. Rust programs can also be compiled as
157 libraries, and included in other programs, even ones not written in Rust.
161 There are vim highlighting and indentation scripts in the Rust source
162 distribution under `src/etc/vim/`. There is an emacs mode under
163 `src/etc/emacs/` called `rust-mode`, but do read the instructions
164 included in that directory. In particular, if you are running emacs
165 24, then using emacs's internal package manager to install `rust-mode`
166 is the easiest way to keep it up to date. There is also a package for
167 Sublime Text 2, available both [standalone][sublime] and through
168 [Sublime Package Control][sublime-pkg], and support for Kate
169 under `src/etc/kate`.
171 A community-maintained list of available Rust tooling is [on the
172 wiki][wiki-packages].
174 There is ctags support via `src/etc/ctags.rust`, but many other
175 tools and editors are not yet supported. If you end up writing a Rust
176 mode for your favorite editor, let us know so that we can link to it.
178 [sublime]: http://github.com/dbp/sublime-rust
179 [sublime-pkg]: http://wbond.net/sublime_packages/package_control
183 Assuming you've programmed in any C-family language (C++, Java,
184 JavaScript, C#, or PHP), Rust will feel familiar. Code is arranged
185 in blocks delineated by curly braces; there are control structures
186 for branching and looping, like the familiar `if` and `while`; function
187 calls are written `myfunc(arg1, arg2)`; operators are written the same
188 and mostly have the same precedence as in C; comments are again like C;
189 module names are separated with double-colon (`::`) as with C++.
191 The main surface difference to be aware of is that the condition at
192 the head of control structures like `if` and `while` does not require
193 parentheses, while their bodies *must* be wrapped in
194 braces. Single-statement, unbraced bodies are not allowed.
197 # mod universe { pub fn recalibrate() -> bool { true } }
201 // A tricky calculation
202 if universe::recalibrate() {
209 The `let` keyword introduces a local variable. Variables are immutable by
210 default. To introduce a local variable that you can re-assign later, use `let
218 println!("count is {}", count);
223 Although Rust can almost always infer the types of local variables, you can
224 specify a variable's type by following it in the `let` with a colon, then the
225 type name. Static items, on the other hand, always require a type annotation.
229 static MONSTER_FACTOR: f64 = 57.8;
230 let monster_size = MONSTER_FACTOR * 10.0;
231 let monster_size: int = 50;
234 Local variables may shadow earlier declarations, as in the previous example:
235 `monster_size` was first declared as a `f64`, and then a second
236 `monster_size` was declared as an `int`. If you were to actually compile this
237 example, though, the compiler would determine that the first `monster_size` is
238 unused and issue a warning (because this situation is likely to indicate a
239 programmer error). For occasions where unused variables are intentional, their
240 names may be prefixed with an underscore to silence the warning, like `let
241 _monster_size = 50;`.
243 Rust identifiers start with an alphabetic
244 character or an underscore, and after that may contain any sequence of
245 alphabetic characters, numbers, or underscores. The preferred style is to
246 write function, variable, and module names with lowercase letters, using
247 underscores where they help readability, while writing types in camel case.
250 let my_variable = 100;
251 type MyType = int; // primitive types are _not_ camel case
254 ## Expressions and semicolons
256 Though it isn't apparent in all code, there is a fundamental
257 difference between Rust's syntax and predecessors like C.
258 Many constructs that are statements in C are expressions
259 in Rust, allowing code to be more concise. For example, you might
260 write a piece of code like this:
263 # let item = "salad";
267 } else if item == "muffin" {
274 But, in Rust, you don't have to repeat the name `price`:
277 # let item = "salad";
281 } else if item == "muffin" {
288 Both pieces of code are exactly equivalent: they assign a value to
289 `price` depending on the condition that holds. Note that there
290 are no semicolons in the blocks of the second snippet. This is
291 important: the lack of a semicolon after the last statement in a
292 braced block gives the whole block the value of that last expression.
294 Put another way, the semicolon in Rust *ignores the value of an expression*.
295 Thus, if the branches of the `if` had looked like `{ 4; }`, the above example
296 would simply assign `()` (unit or void) to `price`. But without the semicolon, each
297 branch has a different value, and `price` gets the value of the branch that
300 In short, everything that's not a declaration (declarations are `let` for
301 variables; `fn` for functions; and any top-level named items such as
302 [traits](#traits), [enum types](#enums), and static items) is an
303 expression, including function bodies.
306 fn is_four(x: int) -> bool {
307 // No need for a return statement. The result of the expression
308 // is used as the return value.
313 ## Primitive types and literals
315 There are general signed and unsigned integer types, `int` and `uint`,
316 as well as 8-, 16-, 32-, and 64-bit variants, `i8`, `u16`, etc.
317 Integers can be written in decimal (`144`), hexadecimal (`0x90`), octal (`0o70`), or
318 binary (`0b10010000`) base. Each integral type has a corresponding literal
319 suffix that can be used to indicate the type of a literal: `i` for `int`,
320 `u` for `uint`, `i8` for the `i8` type.
322 In the absence of an integer literal suffix, Rust will infer the
323 integer type based on type annotations and function signatures in the
324 surrounding program. In the absence of any type information at all,
325 Rust will assume that an unsuffixed integer literal has type
329 let a = 1; // `a` is an `int`
330 let b = 10i; // `b` is an `int`, due to the `i` suffix
331 let c = 100u; // `c` is a `uint`
332 let d = 1000i32; // `d` is an `i32`
335 There are two floating-point types: `f32`, and `f64`.
336 Floating-point numbers are written `0.0`, `1e6`, or `2.1e-4`.
337 Like integers, floating-point literals are inferred to the correct type.
338 Suffixes `f32`, and `f64` can be used to create literals of a specific type.
340 The keywords `true` and `false` produce literals of type `bool`.
342 Characters, the `char` type, are four-byte Unicode codepoints,
343 whose literals are written between single quotes, as in `'x'`.
344 Just like C, Rust understands a number of character escapes, using the backslash
345 character, such as `\n`, `\r`, and `\t`. String literals,
346 written between double quotes, allow the same escape sequences, and do no
347 other processing, unlike languages such as PHP or shell.
349 On the other hand, raw string literals do not process any escape sequences.
350 They are written as `r##"blah"##`, with a matching number of zero or more `#`
351 before the opening and after the closing quote, and can contain any sequence of
352 characters except their closing delimiter. More on strings
353 [later](#vectors-and-strings).
355 The unit type, written `()`, has a single value, also written `()`.
359 Rust's set of operators contains very few surprises. Arithmetic is done with
360 `*`, `/`, `%`, `+`, and `-` (multiply, quotient, remainder, add, and subtract). `-` is
361 also a unary prefix operator that negates numbers. As in C, the bitwise operators
362 `>>`, `<<`, `&`, `|`, and `^` are also supported.
364 Note that, if applied to an integer value, `!` flips all the bits (bitwise
367 The comparison operators are the traditional `==`, `!=`, `<`, `>`,
368 `<=`, and `>=`. Short-circuiting (lazy) boolean operators are written
369 `&&` (and) and `||` (or).
371 For compile-time type casting, Rust uses the binary `as` operator. It takes
372 an expression on the left side and a type on the right side and will, if a
373 meaningful conversion exists, convert the result of the expression to the
374 given type. Generally, `as` is only used with the primitive numeric types or
375 pointers, and is not overloadable. [`transmute`][transmute] can be used for
376 unsafe C-like casting of same-sized types.
380 let y: uint = x as uint;
384 [transmute]: http://static.rust-lang.org/doc/master/std/cast/fn.transmute.html
388 *Syntax extensions* are special forms that are not built into the language,
389 but are instead provided by the libraries. To make it clear to the reader when
390 a name refers to a syntax extension, the names of all syntax extensions end
391 with `!`. The standard library defines a few syntax extensions, the most
392 useful of which is [`format!`][fmt], a `sprintf`-like text formatter that you
393 will often see in examples, and its related family of macros: `print!`,
394 `println!`, and `write!`.
396 `format!` draws syntax from Python, but contains many of the same principles
397 that [printf][pf] has. Unlike printf, `format!` will give you a compile-time
398 error when the types of the directives don't match the types of the arguments.
401 # let mystery_object = ();
403 // `{}` will print the "default format" of a type
404 println!("{} is {}", "the answer", 43);
406 // `{:?}` will conveniently print any type
407 println!("what is this thing: {:?}", mystery_object);
410 [pf]: http://en.cppreference.com/w/cpp/io/c/fprintf
411 [fmt]: http://static.rust-lang.org/doc/master/std/fmt/index.html
413 You can define your own syntax extensions with the macro system. For details,
414 see the [macro tutorial][macros]. Note that macro definition is currently
415 considered an unstable feature.
421 We've seen `if` expressions a few times already. To recap, braces are
422 compulsory, an `if` can have an optional `else` clause, and multiple
423 `if`/`else` constructs can be chained together:
427 println!("that's odd");
431 println!("neither true nor false");
435 The condition given to an `if` construct *must* be of type `bool` (no
436 implicit conversion happens). If the arms are blocks that have a
437 value, this value must be of the same type for every arm in which
438 control reaches the end of the block:
441 fn signum(x: int) -> int {
450 Rust's `match` construct is a generalized, cleaned-up version of C's
451 `switch` construct. You provide it with a value and a number of
452 *arms*, each labelled with a pattern, and the code compares the value
453 against each pattern in order until one matches. The matching pattern
454 executes its corresponding arm.
459 0 => println!("zero"),
460 1 | 2 => println!("one or two"),
461 3..10 => println!("three to ten"),
462 _ => println!("something else")
466 Unlike in C, there is no "falling through" between arms: only one arm
467 executes, and it doesn't have to explicitly `break` out of the
468 construct when it is finished.
470 A `match` arm consists of a *pattern*, then an arrow `=>`, followed by
471 an *action* (expression). Literals are valid patterns and match only
472 their own value. A single arm may match multiple different patterns by
473 combining them with the pipe operator (`|`), so long as every pattern
474 binds the same set of variables. Ranges of numeric literal patterns
475 can be expressed with two dots, as in `M..N`. The underscore (`_`) is
476 a wildcard pattern that matches any single value. (`..`) is a different
477 wildcard that can match one or more fields in an `enum` variant.
479 The patterns in a match arm are followed by a fat arrow, `=>`, then an
480 expression to evaluate. Each case is separated by commas. It's often
481 convenient to use a block expression for each case, in which case the
487 0 => { println!("zero") }
488 _ => { println!("something else") }
492 `match` constructs must be *exhaustive*: they must have an arm
493 covering every possible case. For example, the typechecker would
494 reject the previous example if the arm with the wildcard pattern was
497 A powerful application of pattern matching is *destructuring*:
498 matching in order to bind names to the contents of data
501 > ***Note:*** The following code makes use of tuples (`(f64, f64)`) which
502 > are explained in section 5.3. For now you can think of tuples as a list of
508 fn angle(vector: (f64, f64)) -> f64 {
509 let pi = f64::consts::PI;
511 (0.0, y) if y < 0.0 => 1.5 * pi,
512 (0.0, _) => 0.5 * pi,
513 (x, y) => atan(y / x)
518 A variable name in a pattern matches any value, *and* binds that name
519 to the value of the matched value inside of the arm's action. Thus, `(0.0,
520 y)` matches any tuple whose first element is zero, and binds `y` to
521 the second element. `(x, y)` matches any two-element tuple, and binds both
522 elements to variables. `(0.0,_)` matches any tuple whose first element is zero
523 and does not bind anything to the second element.
525 A subpattern can also be bound to a variable, using `variable @ pattern`. For
531 a @ 0..20 => println!("{} years old", a),
532 _ => println!("older than 21")
536 Any `match` arm can have a guard clause (written `if EXPR`), called a
537 *pattern guard*, which is an expression of type `bool` that
538 determines, after the pattern is found to match, whether the arm is
539 taken or not. The variables bound by the pattern are in scope in this
540 guard expression. The first arm in the `angle` example shows an
541 example of a pattern guard.
543 You've already seen simple `let` bindings, but `let` is a little
544 fancier than you've been led to believe. It, too, supports destructuring
545 patterns. For example, you can write this to extract the fields from a
546 tuple, introducing two variables at once: `a` and `b`.
549 # fn get_tuple_of_two_ints() -> (int, int) { (1, 1) }
550 let (a, b) = get_tuple_of_two_ints();
553 Let bindings only work with _irrefutable_ patterns: that is, patterns
554 that can never fail to match. This excludes `let` from matching
555 literals and most `enum` variants.
559 `while` denotes a loop that iterates as long as its given condition
560 (which must have type `bool`) evaluates to `true`. Inside a loop, the
561 keyword `break` aborts the loop, and `continue` aborts the current
562 iteration and continues with the next.
565 let mut cake_amount = 8;
566 while cake_amount > 0 {
571 `loop` denotes an infinite loop, and is the preferred way of writing `while true`:
577 if x % 5 == 0 { break; }
582 This code prints out a weird sequence of numbers and stops as soon as
583 it finds one that can be divided by five.
585 There is also a for-loop that can be used to iterate over a range of numbers:
588 for n in range(0, 5) {
593 The snippet above prints integer numbers under 5 starting at 0.
595 More generally, a for loop works with anything implementing the `Iterator` trait.
596 Data structures can provide one or more methods that return iterators over
597 their contents. For example, strings support iteration over their contents in
607 The snippet above prints the characters in "Hello" vertically, adding a new
608 line after each character.
615 Rust struct types must be declared before they are used using the `struct`
616 syntax: `struct Name { field1: T1, field2: T2 [, ...] }`, where `T1`, `T2`,
617 ... denote types. To construct a struct, use the same syntax, but leave off
618 the `struct`: for example: `Point { x: 1.0, y: 2.0 }`.
620 Structs are quite similar to C structs and are even laid out the same way in
621 memory (so you can read from a Rust struct in C, and vice-versa). Use the dot
622 operator to access struct fields, as in `mypoint.x`.
631 Structs have "inherited mutability", which means that any field of a struct
632 may be mutable, if the struct is in a mutable slot.
634 With a value (say, `mypoint`) of such a type in a mutable location, you can do
635 `mypoint.y += 1.0`. But in an immutable location, such an assignment to a
636 struct without inherited mutability would result in a type error.
639 # struct Point { x: f64, y: f64 }
640 let mut mypoint = Point { x: 1.0, y: 1.0 };
641 let origin = Point { x: 0.0, y: 0.0 };
643 mypoint.y += 1.0; // `mypoint` is mutable, and its fields as well
644 origin.y += 1.0; // ERROR: assigning to immutable field
647 `match` patterns destructure structs. The basic syntax is
648 `Name { fieldname: pattern, ... }`:
651 # struct Point { x: f64, y: f64 }
652 # let mypoint = Point { x: 0.0, y: 0.0 };
654 Point { x: 0.0, y: yy } => println!("{}", yy),
655 Point { x: xx, y: yy } => println!("{} {}", xx, yy)
659 In general, the field names of a struct do not have to appear in the same
660 order they appear in the type. When you are not interested in all
661 the fields of a struct, a struct pattern may end with `, ..` (as in
662 `Name { field1, .. }`) to indicate that you're ignoring all other fields.
663 Additionally, struct fields have a shorthand matching form that simply
664 reuses the field name as the binding name.
667 # struct Point { x: f64, y: f64 }
668 # let mypoint = Point { x: 0.0, y: 0.0 };
670 Point { x, .. } => println!("{}", x)
676 Enums are datatypes with several alternate representations. A simple `enum`
677 defines one or more constants, all of which have the same type:
688 Each variant of this enum has a unique and constant integral discriminator
689 value. If no explicit discriminator is specified for a variant, the value
690 defaults to the value of the previous variant plus one. If the first variant
691 does not have a discriminator, it defaults to 0. For example, the value of
692 `North` is 0, `East` is 1, `South` is 2, and `West` is 3.
694 When an enum has simple integer discriminators, you can apply the `as` cast
695 operator to convert a variant to its discriminator value as an `int`:
698 # enum Direction { North }
699 println!( "{:?} => {}", North, North as int );
702 It is possible to set the discriminator values to chosen constant values:
712 Variants do not have to be simple values; they may be more complex:
715 # struct Point { x: f64, y: f64 }
718 Rectangle(Point, Point)
722 A value of this type is either a `Circle`, in which case it contains a
723 `Point` struct and a f64, or a `Rectangle`, in which case it contains
724 two `Point` structs. The run-time representation of such a value
725 includes an identifier of the actual form that it holds, much like the
726 "tagged union" pattern in C, but with better static guarantees.
728 This declaration defines a type `Shape` that can refer to such shapes, and two
729 functions, `Circle` and `Rectangle`, which can be used to construct values of
730 the type. To create a new Circle, write `Circle(Point { x: 0.0, y: 0.0 },
733 All of these variant constructors may be used as patterns. The only way to
734 access the contents of an enum instance is the destructuring of a match. For
739 # struct Point {x: f64, y: f64}
740 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
741 fn area(sh: Shape) -> f64 {
743 Circle(_, size) => f64::consts::PI * size * size,
744 Rectangle(Point { x, y }, Point { x: x2, y: y2 }) => (x2 - x) * (y2 - y)
749 Use a lone `_` to ignore an individual field. Ignore all fields of a variant
750 like: `Circle(..)`. Nullary enum patterns are written without parentheses:
753 # struct Point { x: f64, y: f64 }
754 # enum Direction { North, East, South, West }
755 fn point_from_direction(dir: Direction) -> Point {
757 North => Point { x: 0.0, y: 1.0 },
758 East => Point { x: 1.0, y: 0.0 },
759 South => Point { x: 0.0, y: -1.0 },
760 West => Point { x: -1.0, y: 0.0 }
765 Enum variants may also be structs. For example:
769 # struct Point { x: f64, y: f64 }
770 # fn square(x: f64) -> f64 { x * x }
772 Circle { center: Point, radius: f64 },
773 Rectangle { top_left: Point, bottom_right: Point }
775 fn area(sh: Shape) -> f64 {
777 Circle { radius: radius, .. } => f64::consts::PI * square(radius),
778 Rectangle { top_left: top_left, bottom_right: bottom_right } => {
779 (bottom_right.x - top_left.x) * (top_left.y - bottom_right.y)
785 > ***Note:*** This feature of the compiler is currently gated behind the
786 > `#[feature(struct_variant)]` directive. More about these directives can be
787 > found in the manual.
791 Tuples in Rust behave exactly like structs, except that their fields do not
792 have names. Thus, you cannot access their fields with dot notation. Tuples
793 can have any arity (number of elements) except for 0 (though you may consider
794 unit, `()`, as the empty tuple if you like).
797 let mytup: (int, int, f64) = (10, 20, 30.0);
799 (a, b, c) => info!("{}", a + b + (c as int))
805 Rust also has _tuple structs_, which behave like both structs and tuples,
806 except that, unlike tuples, tuple structs have names (so `Foo(1, 2)` has a
807 different type from `Bar(1, 2)`), and tuple structs' _fields_ do not have
813 struct MyTup(int, int, f64);
814 let mytup: MyTup = MyTup(10, 20, 30.0);
816 MyTup(a, b, c) => info!("{}", a + b + (c as int))
820 <a name="newtype"></a>
822 There is a special case for tuple structs with a single field, which are
823 sometimes called "newtypes" (after Haskell's "newtype" feature). These are
824 used to define new types in such a way that the new name is not just a
825 synonym for an existing type but is rather its own distinct type.
831 Types like this can be useful to differentiate between data that have
832 the same underlying type but must be used in different ways.
836 struct Centimeters(int);
839 The above definitions allow for a simple way for programs to avoid
840 confusing numbers that correspond to different units. Their integer
841 values can be extracted with pattern matching:
844 # struct Inches(int);
846 let length_with_unit = Inches(10);
847 let Inches(integer_length) = length_with_unit;
848 println!("length is {} inches", integer_length);
853 We've already seen several function definitions. Like all other static
854 declarations, such as `type`, functions can be declared both at the
855 top level and inside other functions (or in modules, which we'll come
856 back to [later](#crates-and-the-module-system)). The `fn` keyword introduces a
857 function. A function has an argument list, which is a parenthesized
858 list of `name: type` pairs separated by commas. An arrow `->`
859 separates the argument list and the function's return type.
862 fn line(a: int, b: int, x: int) -> int {
867 The `return` keyword immediately returns from the body of a function. It
868 is optionally followed by an expression to return. A function can
869 also return a value by having its top-level block produce an
873 fn line(a: int, b: int, x: int) -> int {
878 It's better Rust style to write a return value this way instead of
879 writing an explicit `return`. The utility of `return` comes in when
880 returning early from a function. Functions that do not return a value
881 are said to return unit, `()`, and both the return type and the return
882 value may be omitted from the definition. The following two functions
886 fn do_nothing_the_hard_way() -> () { return (); }
888 fn do_nothing_the_easy_way() { }
891 Ending the function with a semicolon like so is equivalent to returning `()`.
894 fn line(a: int, b: int, x: int) -> int { a * x + b }
895 fn oops(a: int, b: int, x: int) -> () { a * x + b; }
897 assert!(8 == line(5, 3, 1));
898 assert!(() == oops(5, 3, 1));
901 As with `match` expressions and `let` bindings, function arguments support
902 pattern destructuring. Like `let`, argument patterns must be irrefutable,
903 as in this example that unpacks the first value from a tuple and returns it.
906 fn first((value, _): (int, f64)) -> int { value }
911 A *destructor* is a function responsible for cleaning up the resources used by
912 an object when it is no longer accessible. Destructors can be defined to handle
913 the release of resources like files, sockets and heap memory.
915 Objects are never accessible after their destructor has been called, so no
916 dynamic failures are possible from accessing freed resources. When a task
917 fails, destructors of all objects in the task are called.
919 The `~` sigil represents a unique handle for a memory allocation on the heap:
923 // an integer allocated on the heap
926 // the destructor frees the heap memory as soon as `y` goes out of scope
929 Rust includes syntax for heap memory allocation in the language since it's
930 commonly used, but the same semantics can be implemented by a type with a
935 Rust formalizes the concept of object ownership to delegate management of an
936 object's lifetime to either a variable or a task-local garbage collector. An
937 object's owner is responsible for managing the lifetime of the object by
938 calling the destructor, and the owner determines whether the object is mutable.
940 Ownership is recursive, so mutability is inherited recursively and a destructor
941 destroys the contained tree of owned objects. Variables are top-level owners
942 and destroy the contained object when they go out of scope.
945 // the struct owns the objects contained in the `x` and `y` fields
946 struct Foo { x: int, y: ~int }
949 // `a` is the owner of the struct, and thus the owner of the struct's fields
950 let a = Foo { x: 5, y: ~10 };
952 // when `a` goes out of scope, the destructor for the `~int` in the struct's
955 // `b` is mutable, and the mutability is inherited by the objects it owns
956 let mut b = Foo { x: 5, y: ~10 };
960 If an object doesn't contain any non-Send types, it consists of a single
961 ownership tree and is itself given the `Send` trait which allows it to be sent
962 between tasks. Custom destructors can only be implemented directly on types
963 that are `Send`, but non-`Send` types can still *contain* types with custom
964 destructors. Example of types which are not `Send` are [`Gc<T>`][gc] and
965 [`Rc<T>`][rc], the shared-ownership types.
967 [gc]: http://static.rust-lang.org/doc/master/std/gc/struct.Gc.html
968 [rc]: http://static.rust-lang.org/doc/master/std/rc/struct.Rc.html
970 # Implementing a linked list
972 An `enum` is a natural fit for describing a linked list, because it can express
973 a `List` type as being *either* the end of the list (`Nil`) or another node
974 (`Cons`). The full definition of the `Cons` variant will require some thought.
978 Cons(...), // an incomplete definition of the next element in a List
979 Nil // the end of a List
983 The obvious approach is to define `Cons` as containing an element in the list
984 along with the next `List` node. However, this will generate a compiler error.
987 // error: illegal recursive enum type; wrap the inner value in a box to make it representable
989 Cons(u32, List), // an element (`u32`) and the next node in the list
994 This error message is related to Rust's precise control over memory layout, and
995 solving it will require introducing the concept of *boxing*.
999 A value in Rust is stored directly inside the owner. If a `struct` contains
1000 four `u32` fields, it will be four times as large as a single `u32`.
1003 use std::mem::size_of; // bring `size_of` into the current scope, for convenience
1012 assert_eq!(size_of::<Foo>(), size_of::<u32>() * 4);
1021 assert_eq!(size_of::<Bar>(), size_of::<u32>() * 16);
1024 Our previous attempt at defining the `List` type included an `u32` and a `List`
1025 directly inside `Cons`, making it at least as big as the sum of both types. The
1026 type was invalid because the size was infinite!
1028 An *owned box* (`~`) uses a dynamic memory allocation to provide the invariant
1029 of always being the size of a pointer, regardless of the contained type. This
1030 can be leverage to create a valid `List` definition:
1039 Defining a recursive data structure like this is the canonical example of an
1040 owned box. Much like an unboxed value, an owned box has a single owner and is
1041 therefore limited to expressing a tree-like data structure.
1043 Consider an instance of our `List` type:
1050 let list = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1053 It represents an owned tree of values, inheriting mutability down the tree and
1054 being destroyed along with the owner. Since the `list` variable above is
1055 immutable, the whole list is immutable. The memory allocation itself is the
1056 box, while the owner holds onto a pointer to it:
1058 List box List box List box List box
1059 +--------------+ +--------------+ +--------------+ +--------------+
1060 list -> | Cons | 1 | ~ | -> | Cons | 2 | ~ | -> | Cons | 3 | ~ | -> | Nil |
1061 +--------------+ +--------------+ +--------------+ +--------------+
1063 > Note: the above diagram shows the logical contents of the enum. The actual
1064 > memory layout of the enum may vary. For example, for the `List` enum shown
1065 > above, Rust guarantees that there will be no enum tag field in the actual
1066 > structure. See the language reference for more details.
1068 An owned box is a common example of a type with a destructor. The allocated
1069 memory is cleaned up when the box is destroyed.
1073 Rust uses a shallow copy for parameter passing, assignment and returning from
1074 functions. Passing around the `List` will copy only as deep as the pointer to
1075 the box rather than doing an implicit heap allocation.
1082 let xs = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1083 let ys = xs; // copies `Cons(u32, pointer)` shallowly
1086 Rust will consider a shallow copy of a type with a destructor like `List` to
1087 *move ownership* of the value. After a value has been moved, the source
1088 location cannot be used unless it is reinitialized.
1098 // attempting to use `xs` will result in an error here
1102 // `xs` can be used again
1105 A destructor call will only occur for a variable that has not been moved from,
1106 as it is only called a single time.
1109 Avoiding a move can be done with the library-defined `clone` method:
1113 let y = x.clone(); // `y` is a newly allocated box
1114 let z = x; // no new memory allocated, `x` can no longer be used
1117 The `clone` method is provided by the `Clone` trait, and can be derived for
1118 our `List` type. Traits will be explained in detail later.
1127 let x = Cons(5, ~Nil);
1130 // `x` can still be used!
1134 // and now, it can no longer be used since it has been moved
1137 The mutability of a value may be changed by moving it to a new owner:
1141 let mut s = r; // box becomes mutable
1143 let t = s; // box becomes immutable
1146 A simple way to define a function prepending to the `List` type is to take
1155 fn prepend(xs: List, value: u32) -> List {
1160 xs = prepend(xs, 1);
1161 xs = prepend(xs, 2);
1162 xs = prepend(xs, 3);
1165 However, this is not a very flexible definition of `prepend` as it requires
1166 ownership of a list to be passed in rather than just mutating it in-place.
1170 The obvious signature for a `List` equality comparison is the following:
1173 fn eq(xs: List, ys: List) -> bool { ... }
1176 However, this will cause both lists to be moved into the function. Ownership
1177 isn't required to compare the lists, so the function should take *references*
1181 fn eq(xs: &List, ys: &List) -> bool { ... }
1184 A reference is a *non-owning* view of a value. A reference can be obtained with the `&` (address-of)
1185 operator. It can be dereferenced by using the `*` operator. In a pattern, such as `match` expression
1186 branches, the `ref` keyword can be used to bind to a variable name by-reference rather than
1187 by-value. A recursive definition of equality using references is as follows:
1194 fn eq(xs: &List, ys: &List) -> bool {
1195 // Match on the next node in both lists.
1197 // If we have reached the end of both lists, they are equal.
1198 (&Nil, &Nil) => true,
1199 // If the current element in both lists is equal, keep going.
1200 (&Cons(x, ~ref next_xs), &Cons(y, ~ref next_ys)) if x == y => eq(next_xs, next_ys),
1201 // If the current elements are not equal, the lists are not equal.
1206 let xs = Cons(5, ~Cons(10, ~Nil));
1207 let ys = Cons(5, ~Cons(10, ~Nil));
1208 assert!(eq(&xs, &ys));
1211 Note that Rust doesn't guarantee [tail-call](http://en.wikipedia.org/wiki/Tail_call) optimization,
1212 but LLVM is able to handle a simple case like this with optimizations enabled.
1214 ## Lists of other types
1216 Our `List` type is currently always a list of 32-bit unsigned integers. By
1217 leveraging Rust's support for generics, it can be extended to work for any
1220 The `u32` in the previous definition can be substituted with a type parameter:
1229 The old `List` of `u32` is now available as `List<u32>`. The `prepend`
1230 definition has to be updated too:
1234 # Cons(T, ~List<T>),
1237 fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1242 Generic functions and types like this are equivalent to defining specialized
1243 versions for each set of type parameters.
1245 Using the generic `List<T>` works much like before, thanks to type inference:
1249 # Cons(T, ~List<T>),
1252 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1255 let mut xs = Nil; // Unknown type! This is a `List<T>`, but `T` can be anything.
1256 xs = prepend(xs, 10); // The compiler infers the type of `xs` as `List<int>` from this.
1257 xs = prepend(xs, 15);
1258 xs = prepend(xs, 20);
1261 The code sample above demonstrates type inference making most type annotations optional. It is
1262 equivalent to the following type-annotated code:
1266 # Cons(T, ~List<T>),
1269 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1272 let mut xs: List<int> = Nil::<int>;
1273 xs = prepend::<int>(xs, 10);
1274 xs = prepend::<int>(xs, 15);
1275 xs = prepend::<int>(xs, 20);
1278 In declarations, the language uses `Type<T, U, V>` to describe a list of type
1279 parameters, but expressions use `identifier::<T, U, V>`, to disambiguate the
1282 ## Defining list equality with generics
1284 Generic functions are type-checked from the definition, so any necessary properties of the type must
1285 be specified up-front. Our previous definition of list equality relied on the element type having
1286 the `==` operator available, and took advantage of the lack of a destructor on `u32` to copy it
1287 without a move of ownership.
1289 We can add a *trait bound* on the `Eq` trait to require that the type implement the `==` operator.
1290 Two more `ref` annotations need to be added to avoid attempting to move out the element types:
1294 # Cons(T, ~List<T>),
1297 fn eq<T: Eq>(xs: &List<T>, ys: &List<T>) -> bool {
1298 // Match on the next node in both lists.
1300 // If we have reached the end of both lists, they are equal.
1301 (&Nil, &Nil) => true,
1302 // If the current element in both lists is equal, keep going.
1303 (&Cons(ref x, ~ref next_xs), &Cons(ref y, ~ref next_ys)) if x == y => eq(next_xs, next_ys),
1304 // If the current elements are not equal, the lists are not equal.
1309 let xs = Cons('c', ~Cons('a', ~Cons('t', ~Nil)));
1310 let ys = Cons('c', ~Cons('a', ~Cons('t', ~Nil)));
1311 assert!(eq(&xs, &ys));
1314 This would be a good opportunity to implement the `Eq` trait for our list type, making the `==` and
1315 `!=` operators available. We'll need to provide an `impl` for the `Eq` trait and a definition of the
1316 `eq` method. In a method, the `self` parameter refers to an instance of the type we're implementing
1321 # Cons(T, ~List<T>),
1324 impl<T: Eq> Eq for List<T> {
1325 fn eq(&self, ys: &List<T>) -> bool {
1326 // Match on the next node in both lists.
1328 // If we have reached the end of both lists, they are equal.
1329 (&Nil, &Nil) => true,
1330 // If the current element in both lists is equal, keep going.
1331 (&Cons(ref x, ~ref next_xs), &Cons(ref y, ~ref next_ys)) if x == y => next_xs == next_ys,
1332 // If the current elements are not equal, the lists are not equal.
1338 let xs = Cons(5, ~Cons(10, ~Nil));
1339 let ys = Cons(5, ~Cons(10, ~Nil));
1340 assert!(xs.eq(&ys));
1342 assert!(!xs.ne(&ys));
1343 assert!(!(xs != ys));
1348 The most common use case for owned boxes is creating recursive data structures
1349 like a binary search tree. Rust's trait-based generics system (covered later in
1350 the tutorial) is usually used for static dispatch, but also provides dynamic
1351 dispatch via boxing. Values of different types may have different sizes, but a
1352 box is able to *erase* the difference via the layer of indirection they
1355 In uncommon cases, the indirection can provide a performance gain or memory
1356 reduction by making values smaller. However, unboxed values should almost
1357 always be preferred when they are usable.
1359 Note that returning large unboxed values via boxes is unnecessary. A large
1360 value is returned via a hidden output parameter, and the decision on where to
1361 place the return value should be left to the caller:
1364 fn foo() -> (u64, u64, u64, u64, u64, u64) {
1368 let x = ~foo(); // allocates a `~` box, and writes the integers directly to it
1371 Beyond the properties granted by the size, an owned box behaves as a regular
1372 value by inheriting the mutability and lifetime of the owner:
1375 let x = 5; // immutable
1376 let mut y = 5; // mutable
1379 let x = ~5; // immutable
1380 let mut y = ~5; // mutable
1381 *y += 2; // the `*` operator is needed to access the contained value
1387 owned boxes, where the holder of an owned box is the owner of the pointed-to
1388 memory, references never imply ownership - they are "borrowed".
1389 A reference can be borrowed to
1390 any object, and the compiler verifies that it cannot outlive the lifetime of
1393 As an example, consider a simple struct type, `Point`:
1402 We can use this simple definition to allocate points in many different
1403 ways. For example, in this code, each of these three local variables
1404 contains a point, but allocated in a different location:
1407 # struct Point { x: f64, y: f64 }
1408 let on_the_stack : Point = Point { x: 3.0, y: 4.0 };
1409 let managed_box : @Point = @Point { x: 5.0, y: 1.0 };
1410 let owned_box : ~Point = ~Point { x: 7.0, y: 9.0 };
1413 Suppose we want to write a procedure that computes the distance
1414 between any two points, no matter where they are stored. For example,
1415 we might like to compute the distance between `on_the_stack` and
1416 `managed_box`, or between `managed_box` and `owned_box`. One option is
1417 to define a function that takes two arguments of type point—that is,
1418 it takes the points by value. But this will cause the points to be
1419 copied when we call the function. For points, this is probably not so
1420 bad, but often copies are expensive. So we’d like to define a function
1421 that takes the points by pointer. We can use references to do this:
1424 # struct Point { x: f64, y: f64 }
1425 # fn sqrt(f: f64) -> f64 { 0.0 }
1426 fn compute_distance(p1: &Point, p2: &Point) -> f64 {
1427 let x_d = p1.x - p2.x;
1428 let y_d = p1.y - p2.y;
1429 sqrt(x_d * x_d + y_d * y_d)
1433 Now we can call `compute_distance()` in various ways:
1436 # struct Point{ x: f64, y: f64 };
1437 # let on_the_stack : Point = Point { x: 3.0, y: 4.0 };
1438 # let managed_box : @Point = @Point { x: 5.0, y: 1.0 };
1439 # let owned_box : ~Point = ~Point { x: 7.0, y: 9.0 };
1440 # fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
1441 compute_distance(&on_the_stack, managed_box);
1442 compute_distance(managed_box, owned_box);
1445 Here the `&` operator is used to take the address of the variable
1446 `on_the_stack`; this is because `on_the_stack` has the type `Point`
1447 (that is, a struct value) and we have to take its address to get a
1448 reference. We also call this _borrowing_ the local variable
1449 `on_the_stack`, because we are creating an alias: that is, another
1450 route to the same data.
1452 In the case of the boxes `managed_box` and `owned_box`, however, no
1453 explicit action is necessary. The compiler will automatically convert
1454 a box like `@point` or `~point` to a reference like
1455 `&point`. This is another form of borrowing; in this case, the
1456 contents of the managed/owned box are being lent out.
1458 Whenever a value is borrowed, there are some limitations on what you
1459 can do with the original. For example, if the contents of a variable
1460 have been lent out, you cannot send that variable to another task, nor
1461 will you be permitted to take actions that might cause the borrowed
1462 value to be freed or to change its type. This rule should make
1463 intuitive sense: you must wait for a borrowed value to be returned
1464 (that is, for the reference to go out of scope) before you can
1465 make full use of it again.
1467 For a more in-depth explanation of references and lifetimes, read the
1468 [references and lifetimes guide][lifetimes].
1472 Lending an immutable pointer to an object freezes it and prevents mutation.
1473 `Freeze` objects have freezing enforced statically at compile-time. An example
1474 of a non-`Freeze` type is [`RefCell<T>`][refcell].
1479 let y = &x; // `x` is now frozen, it cannot be modified
1481 // `x` is now unfrozen again
1485 [refcell]: http://static.rust-lang.org/doc/master/std/cell/struct.RefCell.html
1487 # Dereferencing pointers
1489 Rust uses the unary star operator (`*`) to access the contents of a
1490 box or pointer, similarly to C.
1497 let sum = *managed + *owned + *borrowed;
1500 Dereferenced mutable pointers may appear on the left hand side of
1501 assignments. Such an assignment modifies the value that the pointer
1506 let mut owned = ~20;
1509 let borrowed = &mut value;
1511 *owned = *borrowed + 100;
1512 *borrowed = *managed + 1000;
1515 Pointers have high operator precedence, but lower precedence than the
1516 dot operator used for field and method access. This precedence order
1517 can sometimes make code awkward and parenthesis-filled.
1520 # struct Point { x: f64, y: f64 }
1521 # enum Shape { Rectangle(Point, Point) }
1522 # impl Shape { fn area(&self) -> int { 0 } }
1523 let start = @Point { x: 10.0, y: 20.0 };
1524 let end = ~Point { x: (*start).x + 100.0, y: (*start).y + 100.0 };
1525 let rect = &Rectangle(*start, *end);
1526 let area = (*rect).area();
1529 To combat this ugliness the dot operator applies _automatic pointer
1530 dereferencing_ to the receiver (the value on the left-hand side of the
1531 dot), so in most cases, explicitly dereferencing the receiver is not necessary.
1534 # struct Point { x: f64, y: f64 }
1535 # enum Shape { Rectangle(Point, Point) }
1536 # impl Shape { fn area(&self) -> int { 0 } }
1537 let start = @Point { x: 10.0, y: 20.0 };
1538 let end = ~Point { x: start.x + 100.0, y: start.y + 100.0 };
1539 let rect = &Rectangle(*start, *end);
1540 let area = rect.area();
1543 You can write an expression that dereferences any number of pointers
1544 automatically. For example, if you feel inclined, you could write
1545 something silly like
1548 # struct Point { x: f64, y: f64 }
1549 let point = &@~Point { x: 10.0, y: 20.0 };
1550 println!("{:f}", point.x);
1553 The indexing operator (`[]`) also auto-dereferences.
1555 # Vectors and strings
1557 A vector is a contiguous block of memory containing zero or more values of the
1558 same type. Rust also supports vector reference types, called slices, which are
1559 a view into a block of memory represented as a pointer and a length.
1561 Strings are represented as vectors of `u8`, with the guarantee of containing a
1562 valid UTF-8 sequence.
1564 Fixed-size vectors are an unboxed block of memory, with the element length as
1565 part of the type. A fixed-size vector owns the elements it contains, so the
1566 elements are mutable if the vector is mutable. Fixed-size strings do not exist.
1569 // A fixed-size vector
1570 let numbers = [1, 2, 3];
1571 let more_numbers = numbers;
1573 // The type of a fixed-size vector is written as `[Type, ..length]`
1574 let five_zeroes: [int, ..5] = [0, ..5];
1577 A unique vector is dynamically sized, and has a destructor to clean up
1578 allocated memory on the heap. A unique vector owns the elements it contains, so
1579 the elements are mutable if the vector is mutable.
1582 // A dynamically sized vector (unique vector)
1583 let mut numbers = ~[1, 2, 3];
1587 // The type of a unique vector is written as `~[int]`
1588 let more_numbers: ~[int] = numbers;
1590 // The original `numbers` value can no longer be used, due to move semantics.
1592 let mut string = ~"fo";
1593 string.push_char('o');
1596 Slices are similar to fixed-size vectors, but the length is not part of the
1597 type. They simply point into a block of memory and do not have ownership over
1602 let xs = &[1, 2, 3];
1604 // Slices have their type written as `&[int]`
1605 let ys: &[int] = xs;
1607 // Other vector types coerce to slices
1608 let three = [1, 2, 3];
1609 let zs: &[int] = three;
1611 // An unadorned string literal is an immutable string slice
1612 let string = "foobar";
1614 // A string slice type is written as `&str`
1615 let view: &str = string.slice(0, 3);
1618 Mutable slices also exist, just as there are mutable references. However, there
1619 are no mutable string slices. Strings are a multi-byte encoding (UTF-8) of
1620 Unicode code points, so they cannot be freely mutated without the ability to
1624 let mut xs = [1, 2, 3];
1625 let view = xs.mut_slice(0, 2);
1628 // The type of a mutable slice is written as `&mut [T]`
1629 let ys: &mut [int] = &mut [1, 2, 3];
1632 Square brackets denote indexing into a vector:
1635 # enum Crayon { Almond, AntiqueBrass, Apricot,
1636 # Aquamarine, Asparagus, AtomicTangerine,
1637 # BananaMania, Beaver, Bittersweet };
1638 # fn draw_scene(c: Crayon) { }
1639 let crayons: [Crayon, ..3] = [BananaMania, Beaver, Bittersweet];
1641 Bittersweet => draw_scene(crayons[0]),
1646 A vector can be destructured using pattern matching:
1649 let numbers: &[int] = &[1, 2, 3];
1650 let score = match numbers {
1653 [a, b] => a * 6 + b * 4,
1654 [a, b, c, ..rest] => a * 5 + b * 3 + c * 2 + rest.len() as int
1658 Both vectors and strings support a number of useful [methods](#methods),
1659 defined in [`std::vec`] and [`std::str`].
1661 [`std::vec`]: std/vec/index.html
1662 [`std::str`]: std/str/index.html
1664 # Ownership escape hatches
1666 Ownership can cleanly describe tree-like data structures, and references provide non-owning pointers. However, more flexibility is often desired and Rust provides ways to escape from strict
1667 single parent ownership.
1669 The standard library provides the `std::rc::Rc` pointer type to express *shared ownership* over a
1670 reference counted box. As soon as all of the `Rc` pointers go out of scope, the box and the
1671 contained value are destroyed.
1676 // A fixed-size array allocated in a reference-counted box
1677 let x = Rc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1678 let y = x.clone(); // a new owner
1679 let z = x; // this moves `x` into `z`, rather than creating a new owner
1681 assert_eq!(*z.borrow(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1683 // the variable is mutable, but not the contents of the box
1684 let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
1688 A garbage collected pointer is provided via `std::gc::Gc`, with a task-local garbage collector
1689 having ownership of the box. It allows the creation of cycles, and the individual `Gc` pointers do
1690 not have a destructor.
1695 // A fixed-size array allocated in a garbage-collected box
1696 let x = Gc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1697 let y = x; // does not perform a move, unlike with `Rc`
1700 assert_eq!(*z.borrow(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1703 With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
1704 it's possible to use *dynamic* mutability via types like `std::cell::Cell` where freezing is handled
1705 via dynamic checks and can fail at runtime.
1707 The `Rc` and `Gc` types are not sendable, so they cannot be used to share memory between tasks. Safe
1708 immutable and mutable shared memory is provided by the `extra::arc` module.
1712 Named functions, like those we've seen so far, may not refer to local
1713 variables declared outside the function: they do not close over their
1714 environment (sometimes referred to as "capturing" variables in their
1715 environment). For example, you couldn't write the following:
1721 return foo; // `bar` cannot refer to `foo`
1725 Rust also supports _closures_, functions that can access variables in
1726 the enclosing scope.
1729 fn call_closure_with_ten(b: |int|) { b(10); }
1731 let captured_var = 20;
1732 let closure = |arg| println!("captured_var={}, arg={}", captured_var, arg);
1734 call_closure_with_ten(closure);
1737 Closures begin with the argument list between vertical bars and are followed by
1738 a single expression. Remember that a block, `{ <expr1>; <expr2>; ... }`, is
1739 considered a single expression: it evaluates to the result of the last
1740 expression it contains if that expression is not followed by a semicolon,
1741 otherwise the block evaluates to `()`.
1743 The types of the arguments are generally omitted, as is the return type,
1744 because the compiler can almost always infer them. In the rare case where the
1745 compiler needs assistance, though, the arguments and return types may be
1749 let square = |x: int| -> uint { (x * x) as uint };
1752 There are several forms of closure, each with its own role. The most
1753 common, called a _stack closure_, has type `||` and can directly
1754 access local variables in the enclosing scope.
1758 [1, 2, 3].map(|x| if *x > max { max = *x });
1761 Stack closures are very efficient because their environment is
1762 allocated on the call stack and refers by pointer to captured
1763 locals. To ensure that stack closures never outlive the local
1764 variables to which they refer, stack closures are not
1765 first-class. That is, they can only be used in argument position; they
1766 cannot be stored in data structures or returned from
1767 functions. Despite these limitations, stack closures are used
1768 pervasively in Rust code.
1772 Owned closures, written `proc`,
1773 hold on to things that can safely be sent between
1774 processes. They copy the values they close over, much like managed
1775 closures, but they also own them: that is, no other code can access
1776 them. Owned closures are used in concurrent code, particularly
1777 for spawning [tasks][tasks].
1779 Closures can be used to spawn tasks.
1780 A practical example of this pattern is found when using the `spawn` function,
1781 which starts a new task.
1784 use std::task::spawn;
1786 // proc is the closure which will be spawned.
1788 debug!("I'm a new task")
1792 > ***Note:*** If you want to see the output of `debug!` statements, you will need to turn on
1793 > `debug!` logging. To enable `debug!` logging, set the RUST_LOG environment
1794 > variable to the name of your crate, which, for a file named `foo.rs`, will be
1795 > `foo` (e.g., with bash, `export RUST_LOG=foo`).
1797 ## Closure compatibility
1799 Rust closures have a convenient subtyping property: you can pass any kind of
1800 closure (as long as the arguments and return types match) to functions
1801 that expect a `||`. Thus, when writing a higher-order function that
1802 only calls its function argument, and does nothing else with it, you
1803 should almost always declare the type of that argument as `||`. That way,
1804 callers may pass any kind of closure.
1807 fn call_twice(f: ||) { f(); f(); }
1808 let closure = || { "I'm a closure, and it doesn't matter what type I am"; };
1809 fn function() { "I'm a normal function"; }
1810 call_twice(closure);
1811 call_twice(function);
1814 > ***Note:*** Both the syntax and the semantics will be changing
1815 > in small ways. At the moment they can be unsound in some
1816 > scenarios, particularly with non-copyable types.
1820 Methods are like functions except that they always begin with a special argument,
1822 which has the type of the method's receiver. The
1823 `self` argument is like `this` in C++ and many other languages.
1824 Methods are called with dot notation, as in `my_vec.len()`.
1826 _Implementations_, written with the `impl` keyword, can define
1827 methods on most Rust types, including structs and enums.
1828 As an example, let's define a `draw` method on our `Shape` enum.
1831 # fn draw_circle(p: Point, f: f64) { }
1832 # fn draw_rectangle(p: Point, p: Point) { }
1840 Rectangle(Point, Point)
1846 Circle(p, f) => draw_circle(p, f),
1847 Rectangle(p1, p2) => draw_rectangle(p1, p2)
1852 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1856 This defines an _implementation_ for `Shape` containing a single
1857 method, `draw`. In most respects the `draw` method is defined
1858 like any other function, except for the name `self`.
1860 The type of `self` is the type on which the method is implemented,
1861 or a pointer thereof. As an argument it is written either `self`,
1862 `&self`, or `~self`.
1863 A caller must in turn have a compatible pointer type to call the method.
1866 # fn draw_circle(p: Point, f: f64) { }
1867 # fn draw_rectangle(p: Point, p: Point) { }
1868 # struct Point { x: f64, y: f64 }
1870 # Circle(Point, f64),
1871 # Rectangle(Point, Point)
1874 fn draw_reference(&self) { ... }
1875 fn draw_owned(~self) { ... }
1876 fn draw_value(self) { ... }
1879 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1882 (&s).draw_reference();
1886 Methods typically take a reference self type,
1887 so the compiler will go to great lengths to convert a callee
1891 # fn draw_circle(p: Point, f: f64) { }
1892 # fn draw_rectangle(p: Point, p: Point) { }
1893 # struct Point { x: f64, y: f64 }
1895 # Circle(Point, f64),
1896 # Rectangle(Point, Point)
1899 # fn draw_reference(&self) { ... }
1900 # fn draw_owned(~self) { ... }
1901 # fn draw_value(self) { ... }
1903 # let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1904 // As with typical function arguments, managed and owned pointers
1905 // are automatically converted to references
1907 (@s).draw_reference();
1908 (~s).draw_reference();
1910 // Unlike typical function arguments, the self value will
1911 // automatically be referenced ...
1914 // ... and dereferenced
1915 (& &s).draw_reference();
1917 // ... and dereferenced and borrowed
1918 (&@~s).draw_reference();
1921 Implementations may also define standalone (sometimes called "static")
1922 methods. The absence of a `self` parameter distinguishes such methods.
1923 These methods are the preferred way to define constructor functions.
1927 fn area(&self) -> f64 { ... }
1928 fn new(area: f64) -> Circle { ... }
1932 To call such a method, just prefix it with the type name and a double colon:
1935 use std::f64::consts::PI;
1936 struct Circle { radius: f64 }
1938 fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
1940 let c = Circle::new(42.5);
1945 Throughout this tutorial, we've been defining functions that act only
1946 on specific data types. With type parameters we can also define
1947 functions whose arguments have generic types, and which can be invoked
1948 with a variety of types. Consider a generic `map` function, which
1949 takes a function `function` and a vector `vector` and returns a new
1950 vector consisting of the result of applying `function` to each element
1954 fn map<T, U>(vector: &[T], function: |v: &T| -> U) -> ~[U] {
1955 let mut accumulator = ~[];
1956 for element in vector.iter() {
1957 accumulator.push(function(element));
1963 When defined with type parameters, as denoted by `<T, U>`, this
1964 function can be applied to any type of vector, as long as the type of
1965 `function`'s argument and the type of the vector's contents agree with
1968 Inside a generic function, the names of the type parameters
1969 (capitalized by convention) stand for opaque types. All you can do
1970 with instances of these types is pass them around: you can't apply any
1971 operations to them or pattern-match on them. Note that instances of
1972 generic types are often passed by pointer. For example, the parameter
1973 `function()` is supplied with a pointer to a value of type `T` and not
1974 a value of type `T` itself. This ensures that the function works with
1975 the broadest set of types possible, since some types are expensive or
1976 illegal to copy and pass by value.
1978 Generic `type`, `struct`, and `enum` declarations follow the same pattern:
1981 use std::hashmap::HashMap;
1982 type Set<T> = HashMap<T, ()>;
1994 These declarations can be instantiated to valid types like `Set<int>`,
1995 `Stack<int>`, and `Option<int>`.
1997 The last type in that example, `Option`, appears frequently in Rust code.
1998 Because Rust does not have null pointers (except in unsafe code), we need
1999 another way to write a function whose result isn't defined on every possible
2000 combination of arguments of the appropriate types. The usual way is to write
2001 a function that returns `Option<T>` instead of `T`.
2004 # struct Point { x: f64, y: f64 }
2005 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
2006 fn radius(shape: Shape) -> Option<f64> {
2008 Circle(_, radius) => Some(radius),
2009 Rectangle(..) => None
2014 The Rust compiler compiles generic functions very efficiently by
2015 *monomorphizing* them. *Monomorphization* is a fancy name for a simple
2016 idea: generate a separate copy of each generic function at each call site,
2017 a copy that is specialized to the argument
2018 types and can thus be optimized specifically for them. In this
2019 respect, Rust's generics have similar performance characteristics to
2024 Within a generic function -- that is, a function parameterized by a
2025 type parameter, say, `T` -- the operations we can do on arguments of
2026 type `T` are quite limited. After all, since we don't know what type
2027 `T` will be instantiated with, we can't safely modify or query values
2028 of type `T`. This is where _traits_ come into play. Traits are Rust's
2029 most powerful tool for writing polymorphic code. Java developers will
2030 see them as similar to Java interfaces, and Haskellers will notice
2031 their similarities to type classes. Rust's traits give us a way to
2032 express *bounded polymorphism*: by limiting the set of possible types
2033 that a type parameter could refer to, they expand the number of
2034 operations we can safely perform on arguments of that type.
2036 As motivation, let us consider copying of values in Rust. The `clone`
2037 method is not defined for values of every type. One reason is
2038 user-defined destructors: copying a value of a type that has a
2039 destructor could result in the destructor running multiple times.
2040 Therefore, values of types that have destructors cannot be copied
2041 unless we explicitly implement `clone` for them.
2043 This complicates handling of generic functions.
2044 If we have a function with a type parameter `T`,
2045 can we copy values of type `T` inside that function?
2047 and if we try to run the following code the compiler will complain.
2050 // This does not compile
2051 fn head_bad<T>(v: &[T]) -> T {
2052 v[0] // error: copying a non-copyable value
2056 However, we can tell the compiler
2057 that the `head` function is only for copyable types.
2058 In Rust, copyable types are those that _implement the `Clone` trait_.
2059 We can then explicitly create a second copy of the value we are returning
2060 by calling the `clone` method:
2064 fn head<T: Clone>(v: &[T]) -> T {
2069 The bounded type parameter `T: Clone` says that `head`
2070 can be called on an argument of type `&[T]` for any `T`,
2071 so long as there is an implementation of the
2072 `Clone` trait for `T`.
2073 When instantiating a generic function,
2074 we can only instantiate it with types
2075 that implement the correct trait,
2076 so we could not apply `head` to a vector whose elements are of some type
2077 that does not implement `Clone`.
2079 While most traits can be defined and implemented by user code,
2080 three traits are automatically derived and implemented
2081 for all applicable types by the compiler,
2082 and may not be overridden:
2084 * `Send` - Sendable types.
2086 unless they contain managed boxes, managed closures, or references.
2088 * `Freeze` - Constant (immutable) types.
2089 These are types that do not contain anything intrinsically mutable.
2090 Intrinsically mutable values include `Cell` in the standard library.
2092 * `'static` - Non-borrowed types.
2093 These are types that do not contain any data whose lifetime is bound to
2094 a particular stack frame. These are types that do not contain any
2095 references, or types where the only contained references
2096 have the `'static` lifetime.
2098 > ***Note:*** These two traits were referred to as 'kinds' in earlier
2099 > iterations of the language, and often still are.
2101 Additionally, the `Drop` trait is used to define destructors. This
2102 trait provides one method called `drop`, which is automatically
2103 called when a value of the type that implements this trait is
2104 destroyed, either because the value went out of scope or because the
2105 garbage collector reclaimed it.
2112 impl Drop for TimeBomb {
2113 fn drop(&mut self) {
2114 for _ in range(0, self.explosivity) {
2121 It is illegal to call `drop` directly. Only code inserted by the compiler
2124 ## Declaring and implementing traits
2126 At its simplest, a trait is a set of zero or more _method signatures_.
2127 For example, we could declare the trait
2128 `Printable` for things that can be printed to the console,
2129 with a single method signature:
2137 We say that the `Printable` trait _provides_ a `print` method with the
2138 given signature. This means that we can call `print` on an argument
2139 of any type that implements the `Printable` trait.
2141 Rust's built-in `Send` and `Freeze` types are examples of traits that
2142 don't provide any methods.
2144 Traits may be implemented for specific types with [impls]. An impl for
2145 a particular trait gives an implementation of the methods that
2146 trait provides. For instance, the following impls of
2147 `Printable` for `int` and `~str` give implementations of the `print`
2153 # trait Printable { fn print(&self); }
2154 impl Printable for int {
2155 fn print(&self) { println!("{:?}", *self) }
2158 impl Printable for ~str {
2159 fn print(&self) { println!("{}", *self) }
2166 Methods defined in an impl for a trait may be called just like
2167 any other method, using dot notation, as in `1.print()`.
2169 ## Default method implementations in trait definitions
2171 Sometimes, a method that a trait provides will have the same
2172 implementation for most or all of the types that implement that trait.
2173 For instance, suppose that we wanted `bool`s and `f32`s to be
2174 printable, and that we wanted the implementation of `print` for those
2175 types to be exactly as it is for `int`, above:
2178 # trait Printable { fn print(&self); }
2179 impl Printable for f32 {
2180 fn print(&self) { println!("{:?}", *self) }
2183 impl Printable for bool {
2184 fn print(&self) { println!("{:?}", *self) }
2191 This works fine, but we've now repeated the same definition of `print`
2192 in three places. Instead of doing that, we can simply include the
2193 definition of `print` right in the trait definition, instead of just
2194 giving its signature. That is, we can write the following:
2198 // Default method implementation
2199 fn print(&self) { println!("{:?}", *self) }
2202 impl Printable for int {}
2204 impl Printable for ~str {
2205 fn print(&self) { println!("{}", *self) }
2208 impl Printable for bool {}
2210 impl Printable for f32 {}
2218 Here, the impls of `Printable` for `int`, `bool`, and `f32` don't
2219 need to provide an implementation of `print`, because in the absence
2220 of a specific implementation, Rust just uses the _default method_
2221 provided in the trait definition. Depending on the trait, default
2222 methods can save a great deal of boilerplate code from having to be
2223 written in impls. Of course, individual impls can still override the
2224 default method for `print`, as is being done above in the impl for
2227 ## Type-parameterized traits
2229 Traits may be parameterized by type variables. For example, a trait
2230 for generalized sequence types might look like the following:
2234 fn length(&self) -> uint;
2237 impl<T> Seq<T> for ~[T] {
2238 fn length(&self) -> uint { self.len() }
2242 The implementation has to explicitly declare the type parameter that
2243 it binds, `T`, before using it to specify its trait type. Rust
2244 requires this declaration because the `impl` could also, for example,
2245 specify an implementation of `Seq<int>`. The trait type (appearing
2246 between `impl` and `for`) *refers* to a type, rather than
2249 The type parameters bound by a trait are in scope in each of the
2250 method declarations. So, re-declaring the type parameter
2251 `T` as an explicit type parameter for `len`, in either the trait or
2252 the impl, would be a compile-time error.
2254 Within a trait definition, `Self` is a special type that you can think
2255 of as a type parameter. An implementation of the trait for any given
2256 type `T` replaces the `Self` type parameter with `T`. The following
2257 trait describes types that support an equality operation:
2260 // In a trait, `self` refers to the self argument.
2261 // `Self` refers to the type implementing the trait.
2263 fn equals(&self, other: &Self) -> bool;
2266 // In an impl, `self` refers just to the value of the receiver
2268 fn equals(&self, other: &int) -> bool { *other == *self }
2272 Notice that in the trait definition, `equals` takes a
2273 second parameter of type `Self`.
2274 In contrast, in the `impl`, `equals` takes a second parameter of
2275 type `int`, only using `self` as the name of the receiver.
2277 Just as in type implementations, traits can define standalone (static)
2278 methods. These methods are called by prefixing the method name with the trait
2279 name and a double colon. The compiler uses type inference to decide which
2280 implementation to use.
2283 use std::f64::consts::PI;
2284 trait Shape { fn new(area: f64) -> Self; }
2285 struct Circle { radius: f64 }
2286 struct Square { length: f64 }
2288 impl Shape for Circle {
2289 fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
2291 impl Shape for Square {
2292 fn new(area: f64) -> Square { Square { length: (area).sqrt() } }
2296 let c: Circle = Shape::new(area);
2297 let s: Square = Shape::new(area);
2300 ## Bounded type parameters and static method dispatch
2302 Traits give us a language for defining predicates on types, or
2303 abstract properties that types can have. We can use this language to
2304 define _bounds_ on type parameters, so that we can then operate on
2308 # trait Printable { fn print(&self); }
2309 fn print_all<T: Printable>(printable_things: ~[T]) {
2310 for thing in printable_things.iter() {
2316 Declaring `T` as conforming to the `Printable` trait (as we earlier
2317 did with `Clone`) makes it possible to call methods from that trait
2318 on values of type `T` inside the function. It will also cause a
2319 compile-time error when anyone tries to call `print_all` on an array
2320 whose element type does not have a `Printable` implementation.
2322 Type parameters can have multiple bounds by separating them with `+`,
2323 as in this version of `print_all` that copies elements.
2326 # trait Printable { fn print(&self); }
2327 fn print_all<T: Printable + Clone>(printable_things: ~[T]) {
2329 while i < printable_things.len() {
2330 let copy_of_thing = printable_things[i].clone();
2331 copy_of_thing.print();
2337 Method calls to bounded type parameters are _statically dispatched_,
2338 imposing no more overhead than normal function invocation, so are
2339 the preferred way to use traits polymorphically.
2341 This usage of traits is similar to Haskell type classes.
2343 ## Trait objects and dynamic method dispatch
2345 The above allows us to define functions that polymorphically act on
2346 values of a single unknown type that conforms to a given trait.
2347 However, consider this function:
2350 # type Circle = int; type Rectangle = int;
2351 # impl Drawable for int { fn draw(&self) {} }
2352 # fn new_circle() -> int { 1 }
2353 trait Drawable { fn draw(&self); }
2355 fn draw_all<T: Drawable>(shapes: ~[T]) {
2356 for shape in shapes.iter() { shape.draw(); }
2358 # let c: Circle = new_circle();
2362 You can call that on an array of circles, or an array of rectangles
2363 (assuming those have suitable `Drawable` traits defined), but not on
2364 an array containing both circles and rectangles. When such behavior is
2365 needed, a trait name can alternately be used as a type, called
2369 # trait Drawable { fn draw(&self); }
2370 fn draw_all(shapes: &[~Drawable]) {
2371 for shape in shapes.iter() { shape.draw(); }
2375 In this example, there is no type parameter. Instead, the `~Drawable`
2376 type denotes any owned box value that implements the `Drawable` trait.
2377 To construct such a value, you use the `as` operator to cast a value
2381 # type Circle = int; type Rectangle = bool;
2382 # trait Drawable { fn draw(&self); }
2383 # fn new_circle() -> Circle { 1 }
2384 # fn new_rectangle() -> Rectangle { true }
2385 # fn draw_all(shapes: &[~Drawable]) {}
2387 impl Drawable for Circle { fn draw(&self) { ... } }
2388 impl Drawable for Rectangle { fn draw(&self) { ... } }
2390 let c: ~Circle = ~new_circle();
2391 let r: ~Rectangle = ~new_rectangle();
2392 draw_all([c as ~Drawable, r as ~Drawable]);
2395 We omit the code for `new_circle` and `new_rectangle`; imagine that
2396 these just return `Circle`s and `Rectangle`s with a default size. Note
2397 that, like strings and vectors, objects have dynamic size and may
2398 only be referred to via one of the pointer types.
2399 Other pointer types work as well.
2400 Casts to traits may only be done with compatible pointers so,
2401 for example, an `@Circle` may not be cast to an `~Drawable`.
2404 # type Circle = int; type Rectangle = int;
2405 # trait Drawable { fn draw(&self); }
2406 # impl Drawable for int { fn draw(&self) {} }
2407 # fn new_circle() -> int { 1 }
2408 # fn new_rectangle() -> int { 2 }
2410 let owny: ~Drawable = ~new_circle() as ~Drawable;
2411 // A borrowed object
2412 let stacky: &Drawable = &new_circle() as &Drawable;
2415 Method calls to trait types are _dynamically dispatched_. Since the
2416 compiler doesn't know specifically which functions to call at compile
2417 time, it uses a lookup table (also known as a vtable or dictionary) to
2418 select the method to call at runtime.
2420 This usage of traits is similar to Java interfaces.
2422 By default, each of the three storage classes for traits enforce a
2423 particular set of built-in kinds that their contents must fulfill in
2424 order to be packaged up in a trait object of that storage class.
2426 * The contents of owned traits (`~Trait`) must fulfill the `Send` bound.
2427 * The contents of reference traits (`&Trait`) are not constrained by any bound.
2429 Consequently, the trait objects themselves automatically fulfill their
2430 respective kind bounds. However, this default behavior can be overridden by
2431 specifying a list of bounds on the trait type, for example, by writing `~Trait:`
2432 (which indicates that the contents of the owned trait need not fulfill any
2433 bounds), or by writing `~Trait:Send+Freeze`, which indicates that in addition
2434 to fulfilling `Send`, contents must also fulfill `Freeze`, and as a consequence,
2435 the trait itself fulfills `Freeze`.
2437 * `~Trait:Send` is equivalent to `~Trait`.
2438 * `&Trait:` is equivalent to `&Trait`.
2440 Builtin kind bounds can also be specified on closure types in the same way (for
2441 example, by writing `fn:Freeze()`), and the default behaviours are the same as
2442 for traits of the same storage class.
2444 ## Trait inheritance
2446 We can write a trait declaration that _inherits_ from other traits, called _supertraits_.
2447 Types that implement a trait must also implement its supertraits.
2449 we can define a `Circle` trait that inherits from `Shape`.
2452 trait Shape { fn area(&self) -> f64; }
2453 trait Circle : Shape { fn radius(&self) -> f64; }
2456 Now, we can implement `Circle` on a type only if we also implement `Shape`.
2459 use std::f64::consts::PI;
2460 # trait Shape { fn area(&self) -> f64; }
2461 # trait Circle : Shape { fn radius(&self) -> f64; }
2462 # struct Point { x: f64, y: f64 }
2463 # fn square(x: f64) -> f64 { x * x }
2464 struct CircleStruct { center: Point, radius: f64 }
2465 impl Circle for CircleStruct {
2466 fn radius(&self) -> f64 { (self.area() / PI).sqrt() }
2468 impl Shape for CircleStruct {
2469 fn area(&self) -> f64 { PI * square(self.radius) }
2473 Notice that methods of `Circle` can call methods on `Shape`, as our
2474 `radius` implementation calls the `area` method.
2475 This is a silly way to compute the radius of a circle
2476 (since we could just return the `radius` field), but you get the idea.
2478 In type-parameterized functions,
2479 methods of the supertrait may be called on values of subtrait-bound type parameters.
2480 Refering to the previous example of `trait Circle : Shape`:
2483 # trait Shape { fn area(&self) -> f64; }
2484 # trait Circle : Shape { fn radius(&self) -> f64; }
2485 fn radius_times_area<T: Circle>(c: T) -> f64 {
2486 // `c` is both a Circle and a Shape
2487 c.radius() * c.area()
2491 Likewise, supertrait methods may also be called on trait objects.
2494 use std::f64::consts::PI;
2495 # trait Shape { fn area(&self) -> f64; }
2496 # trait Circle : Shape { fn radius(&self) -> f64; }
2497 # struct Point { x: f64, y: f64 }
2498 # struct CircleStruct { center: Point, radius: f64 }
2499 # impl Circle for CircleStruct { fn radius(&self) -> f64 { (self.area() / PI).sqrt() } }
2500 # impl Shape for CircleStruct { fn area(&self) -> f64 { PI * square(self.radius) } }
2502 let concrete = @CircleStruct{center:Point{x:3f,y:4f},radius:5f};
2503 let mycircle: @Circle = concrete as @Circle;
2504 let nonsense = mycircle.radius() * mycircle.area();
2507 > ***Note:*** Trait inheritance does not actually work with objects yet
2509 ## Deriving implementations for traits
2511 A small number of traits in `std` and `extra` can have implementations
2512 that can be automatically derived. These instances are specified by
2513 placing the `deriving` attribute on a data type declaration. For
2514 example, the following will mean that `Circle` has an implementation
2515 for `Eq` and can be used with the equality operators, and that a value
2516 of type `ABC` can be randomly generated and converted to a string:
2520 struct Circle { radius: f64 }
2522 #[deriving(Rand, ToStr)]
2523 enum ABC { A, B, C }
2526 The full list of derivable traits is `Eq`, `TotalEq`, `Ord`,
2527 `TotalOrd`, `Encodable` `Decodable`, `Clone`, `DeepClone`,
2528 `IterBytes`, `Rand`, `Default`, `Zero`, `FromPrimitive` and `Show`.
2530 # Crates and the module system
2532 Rust's module system is very powerful, but because of that also somewhat complex.
2533 Nevertheless, this section will try to explain every important aspect of it.
2537 In order to speak about the module system, we first need to define the medium it exists in:
2539 Let's say you've written a program or a library, compiled it, and got the resulting binary.
2540 In Rust, the content of all source code that the compiler directly had to compile in order to end up with
2541 that binary is collectively called a 'crate'.
2543 For example, for a simple hello world program your crate only consists of this code:
2548 println!("Hello world!");
2552 A crate is also the unit of independent compilation in Rust: `rustc` always compiles a single crate at a time,
2553 from which it produces either a library or an executable.
2555 Note that merely using an already compiled library in your code does not make it part of your crate.
2557 ## The module hierarchy
2559 For every crate, all the code in it is arranged in a hierarchy of modules starting with a single
2560 root module. That root module is called the 'crate root'.
2562 All modules in a crate below the crate root are declared with the `mod` keyword:
2565 // This is the crate root
2568 // This is the body of module 'farm' declared in the crate root.
2570 fn chicken() { println!("cluck cluck"); }
2571 fn cow() { println!("mooo"); }
2574 // Body of module 'barn'
2576 fn hay() { println!("..."); }
2581 println!("Hello farm!");
2585 As you can see, your module hierarchy is now three modules deep: There is the crate root, which contains your `main()`
2586 function, and the module `farm`. The module `farm` also contains two functions and a third module `barn`,
2587 which contains a function `hay`.
2589 (In case you already stumbled over `extern crate`: It isn't directly related to a bare `mod`, we'll get to it later. )
2591 ## Paths and visibility
2593 We've now defined a nice module hierarchy. But how do we access the items in it from our `main` function?
2594 One way to do it is to simply fully qualifying it:
2598 fn chicken() { println!("cluck cluck"); }
2603 println!("Hello chicken!");
2605 ::farm::chicken(); // Won't compile yet, see further down
2609 The `::farm::chicken` construct is what we call a 'path'.
2611 Because it's starting with a `::`, it's also a 'global path', which qualifies
2612 an item by its full path in the module hierarchy relative to the crate root.
2614 If the path were to start with a regular identifier, like `farm::chicken`, it
2615 would be a 'local path' instead. We'll get to them later.
2617 Now, if you actually tried to compile this code example, you'll notice that you
2618 get a `function 'chicken' is private` error. That's because by default, items
2619 (`fn`, `struct`, `static`, `mod`, ...) are private.
2621 To make them visible outside their containing modules, you need to mark them
2622 _public_ with `pub`:
2626 pub fn chicken() { println!("cluck cluck"); }
2627 pub fn cow() { println!("mooo"); }
2632 println!("Hello chicken!");
2633 ::farm::chicken(); // This compiles now
2637 Visibility restrictions in Rust exist only at module boundaries. This
2638 is quite different from most object-oriented languages that also
2639 enforce restrictions on objects themselves. That's not to say that
2640 Rust doesn't support encapsulation: both struct fields and methods can
2641 be private. But this encapsulation is at the module level, not the
2644 For convenience, fields are _public_ by default, and can be made _private_ with
2649 # pub type Chicken = int;
2650 # struct Human(int);
2651 # impl Human { pub fn rest(&self) { } }
2652 # pub fn make_me_a_farm() -> Farm { Farm { chickens: ~[], farmer: Human(0) } }
2654 priv chickens: ~[Chicken],
2659 fn feed_chickens(&self) { ... }
2660 pub fn add_chicken(&self, c: Chicken) { ... }
2663 pub fn feed_animals(farm: &Farm) {
2664 farm.feed_chickens();
2669 let f = make_me_a_farm();
2670 f.add_chicken(make_me_a_chicken());
2671 farm::feed_animals(&f);
2674 // This wouldn't compile because both are private:
2675 // `f.feed_chickens();`
2676 // `let chicken_counter = f.chickens.len();`
2678 # fn make_me_a_farm() -> farm::Farm { farm::make_me_a_farm() }
2679 # fn make_me_a_chicken() -> farm::Chicken { 0 }
2682 Exact details and specifications about visibility rules can be found in the Rust
2685 ## Files and modules
2687 One important aspect of Rust's module system is that source files and modules are not the same thing. You define a module hierarchy, populate it with all your definitions, define visibility, maybe put in a `fn main()`, and that's it.
2689 The only file that's relevant when compiling is the one that contains the body
2690 of your crate root, and it's only relevant because you have to pass that file
2691 to `rustc` to compile your crate.
2693 In principle, that's all you need: You can write any Rust program as one giant source file that contains your
2694 crate root and everything else in `mod ... { ... }` declarations.
2696 However, in practice you usually want to split up your code into multiple
2697 source files to make it more manageable. Rust allows you to move the body of
2698 any module into its own source file. If you declare a module without its body,
2699 like `mod foo;`, the compiler will look for the files `foo.rs` and `foo/mod.rs`
2700 inside some directory (usually the same as of the source file containing the
2701 `mod foo;` declaration). If it finds either, it uses the content of that file
2702 as the body of the module. If it finds both, that's a compile error.
2704 To move the content of `mod farm` into its own file, you can write:
2707 // `main.rs` - contains body of the crate root
2708 mod farm; // Compiler will look for `farm.rs` and `farm/mod.rs`
2711 println!("Hello farm!");
2717 // `farm.rs` - contains body of module 'farm' in the crate root
2718 pub fn chicken() { println!("cluck cluck"); }
2719 pub fn cow() { println!("mooo"); }
2722 pub fn hay() { println!("..."); }
2727 In short, `mod foo;` is just syntactic sugar for `mod foo { /* content of <...>/foo.rs or <...>/foo/mod.rs */ }`.
2729 This also means that having two or more identical `mod foo;` declarations somewhere in your crate hierarchy is generally a bad idea,
2730 just like copy-and-paste-ing a module into multiple places is a bad idea.
2731 Both will result in duplicate and mutually incompatible definitions.
2733 When `rustc` resolves these module declarations, it starts by looking in the
2734 parent directory of the file containing the `mod foo` declaration. For example,
2735 given a file with the module body:
2748 The compiler will look for these files, in this order:
2755 src/animals/fish/mod.rs
2757 src/animals/mammals/humans.rs
2758 src/animals/mammals/humans/mod.rs
2761 Keep in mind that identical module hierarchies can still lead to different path
2762 lookups depending on how and where you've moved a module body to its own file.
2763 For example, if you move the `animals` module into its own file:
2772 // `src/animals.rs` or `src/animals/mod.rs`
2779 ...then the source files of `mod animals`'s submodules can either be in the same directory as the animals source file or in a subdirectory of its directory. If the animals file is `src/animals.rs`, `rustc` will look for:
2786 src/mammals/humans.rs
2787 src/mammals/humans/mod.rs
2790 If the animals file is `src/animals/mod.rs`, `rustc` will look for:
2795 src/animals/fish/mod.rs
2797 src/animals/mammals/humans.rs
2798 src/animals/mammals/humans/mod.rs
2802 These rules allow you to write small modules consisting of single source files which can live in the same directory as well as large modules which group submodule source files in subdirectories.
2804 If you need to override where `rustc` will look for the file containing a
2805 module's source code, use the `path` compiler directive. For example, to load a
2806 `classified` module from a different file:
2809 #[path="../../area51/alien.rs"]
2813 ## Importing names into the local scope
2815 Always referring to definitions in other modules with their global
2816 path gets old really fast, so Rust has a way to import
2817 them into the local scope of your module: `use`-statements.
2819 They work like this: At the beginning of any module body, `fn` body, or any other block
2820 you can write a list of `use`-statements, consisting of the keyword `use` and a __global path__ to an item
2821 without the `::` prefix. For example, this imports `cow` into the local scope:
2825 # mod farm { pub fn cow() { println!("I'm a hidden ninja cow!") } }
2826 # fn main() { cow() }
2829 The path you give to `use` is per default global, meaning relative to the crate root,
2830 no matter how deep the module hierarchy is, or whether the module body it's written in
2831 is contained in its own file (remember: files are irrelevant).
2833 This is different to other languages, where you often only find a single import construct that combines the semantic
2834 of `mod foo;` and `use`-statements, and which tend to work relative to the source file or use an absolute file path
2835 - Rubys `require` or C/C++'s `#include` come to mind.
2837 However, it's also possible to import things relative to the module of the `use`-statement:
2838 Adding a `super::` in front of the path will start in the parent module,
2839 while adding a `self::` prefix will start in the current module:
2843 # pub fn some_parent_item(){ println!("...") }
2845 use super::some_parent_item;
2846 use self::some_child_module::some_item;
2847 # pub fn bar() { some_parent_item(); some_item() }
2848 # pub mod some_child_module { pub fn some_item() {} }
2853 Again - relative to the module, not to the file.
2855 Imports are also shadowed by local definitions:
2856 For each name you mention in a module/block, `rust`
2857 will first look at all items that are defined locally,
2858 and only if that results in no match look at items you brought in
2859 scope with corresponding `use` statements.
2862 # // FIXME: Allow unused import in doc test
2865 # mod farm { pub fn cow() { println!("Hidden ninja cow is hidden.") } }
2866 fn cow() { println!("Mooo!") }
2869 cow() // resolves to the locally defined `cow()` function
2873 To make this behavior more obvious, the rule has been made that `use`-statement always need to be written
2874 before any declaration, like in the example above. This is a purely artificial rule introduced
2875 because people always assumed they shadowed each other based on order, despite the fact that all items in rust are
2876 mutually recursive, order independent definitions.
2878 One odd consequence of that rule is that `use` statements also go in front of any `mod` declaration,
2879 even if they refer to things inside them:
2884 pub fn cow() { println!("Moooooo?") }
2890 This is what our `farm` example looks like with `use` statements:
2898 pub fn chicken() { println!("cluck cluck"); }
2899 pub fn cow() { println!("mooo"); }
2902 pub fn hay() { println!("..."); }
2907 println!("Hello farm!");
2909 // Can now refer to those names directly:
2916 And here an example with multiple files:
2919 // `a.rs` - crate root
2922 fn main() { foo(); }
2929 pub fn foo() { bar(); }
2934 pub fn bar() { println!("Baz!"); }
2938 There also exist two short forms for importing multiple names at once:
2940 1. Explicit mention multiple names as the last element of an `use` path:
2943 use farm::{chicken, cow};
2945 # pub fn cow() { println!("Did I already mention how hidden and ninja I am?") }
2946 # pub fn chicken() { println!("I'm Bat-chicken, guardian of the hidden tutorial code.") }
2948 # fn main() { cow(); chicken() }
2951 2. Import everything in a module with a wildcard:
2956 # pub fn cow() { println!("Bat-chicken? What a stupid name!") }
2957 # pub fn chicken() { println!("Says the 'hidden ninja' cow.") }
2959 # fn main() { cow(); chicken() }
2962 > ***Note:*** This feature of the compiler is currently gated behind the
2963 > `#[feature(globs)]` directive. More about these directives can be found in
2966 However, that's not all. You can also rename an item while you're bringing it into scope:
2969 use egg_layer = farm::chicken;
2970 # mod farm { pub fn chicken() { println!("Laying eggs is fun!") } }
2978 In general, `use` creates an local alias:
2979 An alternate path and a possibly different name to access the same item,
2980 without touching the original, and with both being interchangeable.
2982 ## Reexporting names
2984 It is also possible to reexport items to be accessible under your module.
2986 For that, you write `pub use`:
2990 pub use self::barn::hay;
2992 pub fn chicken() { println!("cluck cluck"); }
2993 pub fn cow() { println!("mooo"); }
2996 pub fn hay() { println!("..."); }
3007 Just like in normal `use` statements, the exported names
3008 merely represent an alias to the same thing and can also be renamed.
3010 The above example also demonstrate what you can use `pub use` for:
3011 The nested `barn` module is private, but the `pub use` allows users
3012 of the module `farm` to access a function from `barn` without needing
3013 to know that `barn` exists.
3015 In other words, you can use them to decouple an public api from their internal implementation.
3019 So far we've only talked about how to define and structure your own crate.
3021 However, most code out there will want to use preexisting libraries,
3022 as there really is no reason to start from scratch each time you start a new project.
3024 In Rust terminology, we need a way to refer to other crates.
3026 For that, Rust offers you the `extern crate` declaration:
3030 // `num` ships with Rust (much like `extra`; more details further down).
3033 // The rational number '1/2':
3034 let one_half = ::num::rational::Ratio::new(1, 2);
3038 Despite its name, `extern crate` is a distinct construct from regular `mod` declarations:
3039 A statement of the form `extern crate foo;` will cause `rustc` to search for the crate `foo`,
3040 and if it finds a matching binary it lets you use it from inside your crate.
3042 The effect it has on your module hierarchy mirrors aspects of both `mod` and `use`:
3044 - Like `mod`, it causes `rustc` to actually emit code:
3045 The linkage information the binary needs to use the library `foo`.
3047 - But like `use`, all `extern crate` statements that refer to the same library are interchangeable,
3048 as each one really just presents an alias to an external module (the crate root of the library
3049 you're linking against).
3051 Remember how `use`-statements have to go before local declarations because the latter shadows the former?
3052 Well, `extern crate` statements also have their own rules in that regard:
3053 Both `use` and local declarations can shadow them, so the rule is that `extern crate` has to go in front
3054 of both `use` and local declarations.
3056 Which can result in something like this:
3062 use num::rational::Ratio;
3065 pub fn dog() { println!("woof"); }
3070 let a_third = Ratio::new(1, 3);
3074 It's a bit weird, but it's the result of shadowing rules that have been set that way because
3075 they model most closely what people expect to shadow.
3079 If you use `extern crate`, per default `rustc` will look for libraries in the library search path (which you can
3080 extend with the `-L` switch).
3082 ## Crate metadata and settings
3084 For every crate you can define a number of metadata items, such as link name, version or author.
3085 You can also toggle settings that have crate-global consequences. Both mechanism
3086 work by providing attributes in the crate root.
3088 For example, Rust uniquely identifies crates by their link metadata, which includes
3089 the link name and the version. It also hashes the filename and the symbols in a binary
3090 based on the link metadata, allowing you to use two different versions of the same library in a crate
3093 Therefore, if you plan to compile your crate as a library, you should annotate it with that information:
3098 # #[crate_type = "lib"];
3100 #[crate_id = "farm#2.5"];
3106 You can also specify package ID information in a `extern crate` statement. For
3107 example, these `extern crate` statements would both accept and select the
3112 extern crate farm = "farm#2.5";
3113 extern crate my_farm = "farm";
3116 Other crate settings and metadata include things like enabling/disabling certain errors or warnings,
3117 or setting the crate type (library or executable) explicitly:
3123 // This crate is a library ("bin" is the default)
3124 #[crate_id = "farm#2.5"];
3125 #[crate_type = "lib"];
3127 // Turn on a warning
3128 #[warn(non_camel_case_types)]
3132 ## A minimal example
3134 Now for something that you can actually compile yourself.
3136 We define two crates, and use one of them as a library in the other.
3140 #[crate_id = "world#0.42"];
3141 # extern crate extra;
3142 pub fn explore() -> &'static str { "world" }
3149 fn main() { println!("hello {}", world::explore()); }
3152 Now compile and run like this (adjust to your platform if necessary):
3155 > rustc --crate-type=lib world.rs # compiles libworld-<HASH>-0.42.so
3156 > rustc main.rs -L . # compiles main
3161 Notice that the library produced contains the version in the file name
3162 as well as an inscrutable string of alphanumerics. As explained in the previous paragraph,
3163 these are both part of Rust's library versioning scheme. The alphanumerics are
3164 a hash representing the crates package ID.
3166 ## The standard library and the prelude
3168 While reading the examples in this tutorial, you might have asked yourself where all
3169 those magical predefined items like `range` are coming from.
3171 The truth is, there's nothing magical about them: They are all defined normally
3172 in the `std` library, which is a crate that ships with Rust.
3174 The only magical thing that happens is that `rustc` automatically inserts this line into your crate root:
3180 As well as this line into every module body:
3183 use std::prelude::*;
3186 The role of the `prelude` module is to re-export common definitions from `std`.
3188 This allows you to use common types and functions like `Option<T>` or `range`
3189 without needing to import them. And if you need something from `std` that's not in the prelude,
3190 you just have to import it with an `use` statement.
3192 For example, it re-exports `range` which is defined in `std::iter::range`:
3195 use iter_range = std::iter::range;
3198 // `range` is imported by default
3199 for _ in range(0, 10) {}
3201 // Doesn't hinder you from importing it under a different name yourself
3202 for _ in iter_range(0, 10) {}
3204 // Or from not using the automatic import.
3205 for _ in ::std::iter::range(0, 10) {}
3209 Both auto-insertions can be disabled with an attribute if necessary:
3212 // In the crate root:
3218 #[no_implicit_prelude];
3221 See the [API documentation][stddoc] for details.
3223 [stddoc]: std/index.html
3225 ## The extra library
3227 Rust ships with crates such as the [extra library], an accumulation of useful things,
3228 that are however not important enough to deserve a place in the standard
3229 library. You can link to a library such as `extra` with an `extern crate extra;`.
3231 [extra library]: extra/index.html
3233 Right now `extra` contains those definitions directly, but in the future it will likely just
3234 re-export a bunch of 'officially blessed' crates that get managed with a
3239 Now that you know the essentials, check out any of the additional
3240 guides on individual topics.
3242 * [Pointers][pointers]
3243 * [Lifetimes][lifetimes]
3244 * [Tasks and communication][tasks]
3246 * [The foreign function interface][ffi]
3247 * [Containers and iterators][container]
3248 * [Documenting Rust code][rustdoc]
3249 * [Testing Rust code][testing]
3250 * [The Rust Runtime][runtime]
3252 There is further documentation on the [wiki], however those tend to be even more out of date as this document.
3254 [pointers]: guide-pointers.html
3255 [lifetimes]: guide-lifetimes.html
3256 [tasks]: guide-tasks.html
3257 [macros]: guide-macros.html
3258 [ffi]: guide-ffi.html
3259 [container]: guide-container.html
3260 [testing]: guide-testing.html
3261 [runtime]: guide-runtime.html
3262 [rustdoc]: rustdoc.html
3263 [wiki]: https://github.com/mozilla/rust/wiki/Docs
3265 [wiki-packages]: https://github.com/mozilla/rust/wiki/Doc-packages,-editors,-and-other-tools