]> git.lizzy.rs Git - rust.git/blob - src/doc/tutorial.md
6ae8c1d704d6a89f41f3e8e074b71f789d57ef72
[rust.git] / src / doc / tutorial.md
1 % The Rust Language Tutorial
2
3 # Introduction
4
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
12 time.
13
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:
17
18 * **Type inference.** Type annotations on local variable declarations
19   are optional.
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.
30
31 ## Scope
32
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
37 depth.
38
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.
42
43 ## Conventions
44
45 Throughout the tutorial, language keywords and identifiers defined in
46 example code are displayed in `code font`.
47
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.
53
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.
57
58 # Getting started
59
60 > **WARNING**: The tarball and installer links are for the most recent
61 > release, not master. To use master, you **must** build from [git].
62
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].
67
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.
72
73 Snapshot binaries are currently built and tested on several platforms:
74
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
78
79 You may find that other platforms work, but these are our "tier 1"
80 supported build environments that are most likely to work.
81
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
87 > know.
88
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
92
93 To build from source you will also need the following prerequisite
94 packages:
95
96 * g++ 4.4 or clang++ 3.x
97 * python 2.6 or later (but not 3.x)
98 * perl 5.0 or later
99 * gnu make 3.81 or later
100 * curl
101
102 If you've fulfilled those prerequisites, something along these lines
103 should work.
104
105 ~~~~ {.notrust}
106 $ curl -O http://static.rust-lang.org/dist/rust-0.9.tar.gz
107 $ tar -xzf rust-0.9.tar.gz
108 $ cd rust-0.9
109 $ ./configure
110 $ make && make install
111 ~~~~
112
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.
118
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.
122
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
125
126 ## Compiling your first program
127
128 Rust program files are, by convention, given the extension `.rs`. Say
129 we have a file `hello.rs` containing this program:
130
131 ~~~~
132 fn main() {
133     println!("hello?");
134 }
135 ~~~~
136
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.
140
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:
145
146 ~~~~ {.notrust}
147 hello.rs:2:5: 2:24 error: macro undefined: 'print_with_unicorns'
148 hello.rs:2     print_with_unicorns!("hello?");
149                ^~~~~~~~~~~~~~~~~~~
150 ~~~~
151
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.
158
159 ## Editing Rust code
160
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`.
170
171 A community-maintained list of available Rust tooling is [on the
172 wiki][wiki-packages].
173
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.
177
178 [sublime]: http://github.com/dbp/sublime-rust
179 [sublime-pkg]: http://wbond.net/sublime_packages/package_control
180
181 # Syntax basics
182
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++.
190
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.
195
196 ~~~~
197 # mod universe { pub fn recalibrate() -> bool { true } }
198 fn main() {
199     /* A simple loop */
200     loop {
201         // A tricky calculation
202         if universe::recalibrate() {
203             return;
204         }
205     }
206 }
207 ~~~~
208
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
211 mut` instead.
212
213 ~~~~
214 let hi = "hi";
215 let mut count = 0;
216
217 while count < 10 {
218     println!("count is {}", count);
219     count += 1;
220 }
221 ~~~~
222
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.
226
227
228 ~~~~
229 static MONSTER_FACTOR: f64 = 57.8;
230 let monster_size = MONSTER_FACTOR * 10.0;
231 let monster_size: int = 50;
232 ~~~~
233
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;`.
242
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.
248
249 ~~~
250 let my_variable = 100;
251 type MyType = int;     // primitive types are _not_ camel case
252 ~~~
253
254 ## Expressions and semicolons
255
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:
261
262 ~~~~
263 # let item = "salad";
264 let price;
265 if item == "salad" {
266     price = 3.50;
267 } else if item == "muffin" {
268     price = 2.25;
269 } else {
270     price = 2.00;
271 }
272 ~~~~
273
274 But, in Rust, you don't have to repeat the name `price`:
275
276 ~~~~
277 # let item = "salad";
278 let price =
279     if item == "salad" {
280         3.50
281     } else if item == "muffin" {
282         2.25
283     } else {
284         2.00
285     };
286 ~~~~
287
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.
293
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
298 was taken.
299
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.
304
305 ~~~~
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.
309    x == 4
310 }
311 ~~~~
312
313 ## Primitive types and literals
314
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.
321
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
326 `int`.
327
328 ~~~~
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`
333 ~~~~
334
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.
339
340 The keywords `true` and `false` produce literals of type `bool`.
341
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.
348
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).
354
355 The unit type, written `()`, has a single value, also written `()`.
356
357 ## Operators
358
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.
363
364 Note that, if applied to an integer value, `!` flips all the bits (bitwise
365 NOT, like `~` in C).
366
367 The comparison operators are the traditional `==`, `!=`, `<`, `>`,
368 `<=`, and `>=`. Short-circuiting (lazy) boolean operators are written
369 `&&` (and) and `||` (or).
370
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.
377
378 ~~~~
379 let x: f64 = 4.0;
380 let y: uint = x as uint;
381 assert!(y == 4u);
382 ~~~~
383
384 [transmute]: http://static.rust-lang.org/doc/master/std/cast/fn.transmute.html
385
386 ## Syntax extensions
387
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!`.
395
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.
399
400 ~~~~
401 # let mystery_object = ();
402
403 // `{}` will print the "default format" of a type
404 println!("{} is {}", "the answer", 43);
405
406 // `{:?}` will conveniently print any type
407 println!("what is this thing: {:?}", mystery_object);
408 ~~~~
409
410 [pf]: http://en.cppreference.com/w/cpp/io/c/fprintf
411 [fmt]: http://static.rust-lang.org/doc/master/std/fmt/index.html
412
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.
416
417 # Control structures
418
419 ## Conditionals
420
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:
424
425 ~~~~
426 if false {
427     println!("that's odd");
428 } else if true {
429     println!("right");
430 } else {
431     println!("neither true nor false");
432 }
433 ~~~~
434
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:
439
440 ~~~~
441 fn signum(x: int) -> int {
442     if x < 0 { -1 }
443     else if x > 0 { 1 }
444     else { 0 }
445 }
446 ~~~~
447
448 ## Pattern matching
449
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.
455
456 ~~~~
457 # let my_number = 1;
458 match my_number {
459   0     => println!("zero"),
460   1 | 2 => println!("one or two"),
461   3..10 => println!("three to ten"),
462   _     => println!("something else")
463 }
464 ~~~~
465
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.
469
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.
478
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
482 commas are optional.
483
484 ~~~
485 # let my_number = 1;
486 match my_number {
487   0 => { println!("zero") }
488   _ => { println!("something else") }
489 }
490 ~~~
491
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
495 omitted.
496
497 A powerful application of pattern matching is *destructuring*:
498 matching in order to bind names to the contents of data
499 types.
500
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
503 > items.
504
505 ~~~~
506 use std::f64;
507 use std::num::atan;
508 fn angle(vector: (f64, f64)) -> f64 {
509     let pi = f64::consts::PI;
510     match vector {
511       (0.0, y) if y < 0.0 => 1.5 * pi,
512       (0.0, _) => 0.5 * pi,
513       (x, y) => atan(y / x)
514     }
515 }
516 ~~~~
517
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.
524
525 A subpattern can also be bound to a variable, using `variable @ pattern`. For
526 example:
527
528 ~~~~
529 # let age = 23;
530 match age {
531     a @ 0..20 => println!("{} years old", a),
532     _ => println!("older than 21")
533 }
534 ~~~~
535
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.
542
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`.
547
548 ~~~~
549 # fn get_tuple_of_two_ints() -> (int, int) { (1, 1) }
550 let (a, b) = get_tuple_of_two_ints();
551 ~~~~
552
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.
556
557 ## Loops
558
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.
563
564 ~~~~
565 let mut cake_amount = 8;
566 while cake_amount > 0 {
567     cake_amount -= 1;
568 }
569 ~~~~
570
571 `loop` denotes an infinite loop, and is the preferred way of writing `while true`:
572
573 ~~~~
574 let mut x = 5u;
575 loop {
576     x += x - 3;
577     if x % 5 == 0 { break; }
578     println!("{}", x);
579 }
580 ~~~~
581
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.
584
585 There is also a for-loop that can be used to iterate over a range of numbers:
586
587 ~~~~
588 for n in range(0, 5) {
589     println!("{}", n);
590 }
591 ~~~~
592
593 The snippet above prints integer numbers under 5 starting at 0.
594
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
598 various ways:
599
600 ~~~~
601 let s = "Hello";
602 for c in s.chars() {
603     println!("{}", c);
604 }
605 ~~~~
606
607 The snippet above prints the characters in "Hello" vertically, adding a new
608 line after each character.
609
610
611 # Data structures
612
613 ## Structs
614
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 }`.
619
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`.
623
624 ~~~~
625 struct Point {
626     x: f64,
627     y: f64
628 }
629 ~~~~
630
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.
633
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.
637
638 ~~~~ {.ignore}
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 };
642
643 mypoint.y += 1.0; // `mypoint` is mutable, and its fields as well
644 origin.y += 1.0; // ERROR: assigning to immutable field
645 ~~~~
646
647 `match` patterns destructure structs. The basic syntax is
648 `Name { fieldname: pattern, ... }`:
649
650 ~~~~
651 # struct Point { x: f64, y: f64 }
652 # let mypoint = Point { x: 0.0, y: 0.0 };
653 match mypoint {
654     Point { x: 0.0, y: yy } => println!("{}", yy),
655     Point { x: xx,  y: yy } => println!("{} {}", xx, yy)
656 }
657 ~~~~
658
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.
665
666 ~~~
667 # struct Point { x: f64, y: f64 }
668 # let mypoint = Point { x: 0.0, y: 0.0 };
669 match mypoint {
670     Point { x, .. } => println!("{}", x)
671 }
672 ~~~
673
674 ## Enums
675
676 Enums are datatypes with several alternate representations. A simple `enum`
677 defines one or more constants, all of which have the same type:
678
679 ~~~~
680 enum Direction {
681     North,
682     East,
683     South,
684     West
685 }
686 ~~~~
687
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.
693
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`:
696
697 ~~~~
698 # enum Direction { North }
699 println!( "{:?} => {}", North, North as int );
700 ~~~~
701
702 It is possible to set the discriminator values to chosen constant values:
703
704 ~~~~
705 enum Color {
706   Red = 0xff0000,
707   Green = 0x00ff00,
708   Blue = 0x0000ff
709 }
710 ~~~~
711
712 Variants do not have to be simple values; they may be more complex:
713
714 ~~~~
715 # struct Point { x: f64, y: f64 }
716 enum Shape {
717     Circle(Point, f64),
718     Rectangle(Point, Point)
719 }
720 ~~~~
721
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.
727
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 },
731 10.0)`.
732
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
735 example:
736
737 ~~~~
738 use std::f64;
739 # struct Point {x: f64, y: f64}
740 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
741 fn area(sh: Shape) -> f64 {
742     match sh {
743         Circle(_, size) => f64::consts::PI * size * size,
744         Rectangle(Point { x, y }, Point { x: x2, y: y2 }) => (x2 - x) * (y2 - y)
745     }
746 }
747 ~~~~
748
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:
751
752 ~~~~
753 # struct Point { x: f64, y: f64 }
754 # enum Direction { North, East, South, West }
755 fn point_from_direction(dir: Direction) -> Point {
756     match dir {
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 }
761     }
762 }
763 ~~~~
764
765 Enum variants may also be structs. For example:
766
767 ~~~~
768 use std::f64;
769 # struct Point { x: f64, y: f64 }
770 # fn square(x: f64) -> f64 { x * x }
771 enum Shape {
772     Circle { center: Point, radius: f64 },
773     Rectangle { top_left: Point, bottom_right: Point }
774 }
775 fn area(sh: Shape) -> f64 {
776     match sh {
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)
780         }
781     }
782 }
783 ~~~~
784
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.
788
789 ## Tuples
790
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).
795
796 ~~~~
797 let mytup: (int, int, f64) = (10, 20, 30.0);
798 match mytup {
799   (a, b, c) => info!("{}", a + b + (c as int))
800 }
801 ~~~~
802
803 ## Tuple structs
804
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
808 names.
809
810 For example:
811
812 ~~~~
813 struct MyTup(int, int, f64);
814 let mytup: MyTup = MyTup(10, 20, 30.0);
815 match mytup {
816   MyTup(a, b, c) => info!("{}", a + b + (c as int))
817 }
818 ~~~~
819
820 <a name="newtype"></a>
821
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.
826
827 ~~~~
828 struct GizmoId(int);
829 ~~~~
830
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.
833
834 ~~~~
835 struct Inches(int);
836 struct Centimeters(int);
837 ~~~~
838
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:
842
843 ~~~
844 # struct Inches(int);
845
846 let length_with_unit = Inches(10);
847 let Inches(integer_length) = length_with_unit;
848 println!("length is {} inches", integer_length);
849 ~~~
850
851 # Functions
852
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.
860
861 ~~~~
862 fn line(a: int, b: int, x: int) -> int {
863     return a * x + b;
864 }
865 ~~~~
866
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
870 expression.
871
872 ~~~~
873 fn line(a: int, b: int, x: int) -> int {
874     a * x + b
875 }
876 ~~~~
877
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
883 are equivalent.
884
885 ~~~~
886 fn do_nothing_the_hard_way() -> () { return (); }
887
888 fn do_nothing_the_easy_way() { }
889 ~~~~
890
891 Ending the function with a semicolon like so is equivalent to returning `()`.
892
893 ~~~~
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; }
896
897 assert!(8 == line(5, 3, 1));
898 assert!(() == oops(5, 3, 1));
899 ~~~~
900
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.
904
905 ~~~
906 fn first((value, _): (int, f64)) -> int { value }
907 ~~~
908
909 # Destructors
910
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.
914
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.
918
919 The `~` sigil represents a unique handle for a memory allocation on the heap:
920
921 ~~~~
922 {
923     // an integer allocated on the heap
924     let y = ~10;
925 }
926 // the destructor frees the heap memory as soon as `y` goes out of scope
927 ~~~~
928
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
931 custom destructor.
932
933 # Ownership
934
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.
939
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.
943
944 ~~~~
945 // the struct owns the objects contained in the `x` and `y` fields
946 struct Foo { x: int, y: ~int }
947
948 {
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 };
951 }
952 // when `a` goes out of scope, the destructor for the `~int` in the struct's
953 // field is called
954
955 // `b` is mutable, and the mutability is inherited by the objects it owns
956 let mut b = Foo { x: 5, y: ~10 };
957 b.x = 10;
958 ~~~~
959
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.
966
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
969
970 # Implementing a linked list
971
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.
975
976 ~~~ {.ignore}
977 enum List {
978     Cons(...), // an incomplete definition of the next element in a List
979     Nil        // the end of a List
980 }
981 ~~~
982
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.
985
986 ~~~ {.ignore}
987 // error: illegal recursive enum type; wrap the inner value in a box to make it representable
988 enum List {
989     Cons(u32, List), // an element (`u32`) and the next node in the list
990     Nil
991 }
992 ~~~
993
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*.
996
997 ## Boxes
998
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`.
1001
1002 ~~~
1003 use std::mem::size_of; // bring `size_of` into the current scope, for convenience
1004
1005 struct Foo {
1006     a: u32,
1007     b: u32,
1008     c: u32,
1009     d: u32
1010 }
1011
1012 assert_eq!(size_of::<Foo>(), size_of::<u32>() * 4);
1013
1014 struct Bar {
1015     a: Foo,
1016     b: Foo,
1017     c: Foo,
1018     d: Foo
1019 }
1020
1021 assert_eq!(size_of::<Bar>(), size_of::<u32>() * 16);
1022 ~~~
1023
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!
1027
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:
1031
1032 ~~~
1033 enum List {
1034     Cons(u32, ~List),
1035     Nil
1036 }
1037 ~~~
1038
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.
1042
1043 Consider an instance of our `List` type:
1044
1045 ~~~
1046 # enum List {
1047 #     Cons(u32, ~List),
1048 #     Nil
1049 # }
1050 let list = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1051 ~~~
1052
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:
1057
1058               List box             List box           List box            List box
1059             +--------------+    +--------------+    +--------------+    +--------------+
1060     list -> | Cons | 1 | ~ | -> | Cons | 2 | ~ | -> | Cons | 3 | ~ | -> | Nil          |
1061             +--------------+    +--------------+    +--------------+    +--------------+
1062
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.
1067
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.
1070
1071 ## Move semantics
1072
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.
1076
1077 ~~~
1078 # enum List {
1079 #     Cons(u32, ~List),
1080 #     Nil
1081 # }
1082 let xs = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1083 let ys = xs; // copies `Cons(u32, pointer)` shallowly
1084 ~~~
1085
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.
1089
1090 ~~~
1091 # enum List {
1092 #     Cons(u32, ~List),
1093 #     Nil
1094 # }
1095 let mut xs = Nil;
1096 let ys = xs;
1097
1098 // attempting to use `xs` will result in an error here
1099
1100 xs = Nil;
1101
1102 // `xs` can be used again
1103 ~~~
1104
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.
1107
1108
1109 Avoiding a move can be done with the library-defined `clone` method:
1110
1111 ~~~~
1112 let x = ~5;
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
1115 ~~~~
1116
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.
1119
1120 ~~~{.ignore}
1121 #[deriving(Clone)]
1122 enum List {
1123     Cons(u32, ~List),
1124     Nil
1125 }
1126
1127 let x = Cons(5, ~Nil);
1128 let y = x.clone();
1129
1130 // `x` can still be used!
1131
1132 let z = x;
1133
1134 // and now, it can no longer be used since it has been moved
1135 ~~~
1136
1137 The mutability of a value may be changed by moving it to a new owner:
1138
1139 ~~~~
1140 let r = ~13;
1141 let mut s = r; // box becomes mutable
1142 *s += 1;
1143 let t = s; // box becomes immutable
1144 ~~~~
1145
1146 A simple way to define a function prepending to the `List` type is to take
1147 advantage of moves:
1148
1149 ~~~
1150 enum List {
1151     Cons(u32, ~List),
1152     Nil
1153 }
1154
1155 fn prepend(xs: List, value: u32) -> List {
1156     Cons(value, ~xs)
1157 }
1158
1159 let mut xs = Nil;
1160 xs = prepend(xs, 1);
1161 xs = prepend(xs, 2);
1162 xs = prepend(xs, 3);
1163 ~~~
1164
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.
1167
1168 ## References
1169
1170 The obvious signature for a `List` equality comparison is the following:
1171
1172 ~~~{.ignore}
1173 fn eq(xs: List, ys: List) -> bool { ... }
1174 ~~~
1175
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*
1178 (&T) instead.
1179
1180 ~~~{.ignore}
1181 fn eq(xs: &List, ys: &List) -> bool { ... }
1182 ~~~
1183
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:
1188
1189 ~~~
1190 # enum List {
1191 #     Cons(u32, ~List),
1192 #     Nil
1193 # }
1194 fn eq(xs: &List, ys: &List) -> bool {
1195     // Match on the next node in both lists.
1196     match (xs, ys) {
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.
1202         _ => false
1203     }
1204 }
1205
1206 let xs = Cons(5, ~Cons(10, ~Nil));
1207 let ys = Cons(5, ~Cons(10, ~Nil));
1208 assert!(eq(&xs, &ys));
1209 ~~~
1210
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.
1213
1214 ## Lists of other types
1215
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
1218 element type.
1219
1220 The `u32` in the previous definition can be substituted with a type parameter:
1221
1222 ~~~
1223 enum List<T> {
1224     Cons(T, ~List<T>),
1225     Nil
1226 }
1227 ~~~
1228
1229 The old `List` of `u32` is now available as `List<u32>`. The `prepend`
1230 definition has to be updated too:
1231
1232 ~~~
1233 # enum List<T> {
1234 #     Cons(T, ~List<T>),
1235 #     Nil
1236 # }
1237 fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1238     Cons(value, ~xs)
1239 }
1240 ~~~
1241
1242 Generic functions and types like this are equivalent to defining specialized
1243 versions for each set of type parameters.
1244
1245 Using the generic `List<T>` works much like before, thanks to type inference:
1246
1247 ~~~
1248 # enum List<T> {
1249 #     Cons(T, ~List<T>),
1250 #     Nil
1251 # }
1252 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1253 #     Cons(value, ~xs)
1254 # }
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);
1259 ~~~
1260
1261 The code sample above demonstrates type inference making most type annotations optional. It is
1262 equivalent to the following type-annotated code:
1263
1264 ~~~
1265 # enum List<T> {
1266 #     Cons(T, ~List<T>),
1267 #     Nil
1268 # }
1269 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1270 #     Cons(value, ~xs)
1271 # }
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);
1276 ~~~
1277
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
1280 `<` operator.
1281
1282 ## Defining list equality with generics
1283
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.
1288
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:
1291
1292 ~~~
1293 # enum List<T> {
1294 #     Cons(T, ~List<T>),
1295 #     Nil
1296 # }
1297 fn eq<T: Eq>(xs: &List<T>, ys: &List<T>) -> bool {
1298     // Match on the next node in both lists.
1299     match (xs, ys) {
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.
1305         _ => false
1306     }
1307 }
1308
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));
1312 ~~~
1313
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
1317 on.
1318
1319 ~~~
1320 # enum List<T> {
1321 #     Cons(T, ~List<T>),
1322 #     Nil
1323 # }
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.
1327         match (self, ys) {
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.
1333             _ => false
1334         }
1335     }
1336 }
1337
1338 let xs = Cons(5, ~Cons(10, ~Nil));
1339 let ys = Cons(5, ~Cons(10, ~Nil));
1340 assert!(xs.eq(&ys));
1341 assert!(xs == ys);
1342 assert!(!xs.ne(&ys));
1343 assert!(!(xs != ys));
1344 ~~~
1345
1346 # More on boxes
1347
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
1353 provide.
1354
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.
1358
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:
1362
1363 ~~~~
1364 fn foo() -> (u64, u64, u64, u64, u64, u64) {
1365     (5, 5, 5, 5, 5, 5)
1366 }
1367
1368 let x = ~foo(); // allocates a `~` box, and writes the integers directly to it
1369 ~~~~
1370
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:
1373
1374 ~~~~
1375 let x = 5; // immutable
1376 let mut y = 5; // mutable
1377 y += 2;
1378
1379 let x = ~5; // immutable
1380 let mut y = ~5; // mutable
1381 *y += 2; // the `*` operator is needed to access the contained value
1382 ~~~~
1383
1384 # References
1385
1386 In contrast with
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
1391 the object.
1392
1393 As an example, consider a simple struct type, `Point`:
1394
1395 ~~~
1396 struct Point {
1397     x: f64,
1398     y: f64
1399 }
1400 ~~~~
1401
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:
1405
1406 ~~~
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 };
1411 ~~~
1412
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:
1422
1423 ~~~
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)
1430 }
1431 ~~~
1432
1433 Now we can call `compute_distance()` in various ways:
1434
1435 ~~~
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);
1443 ~~~
1444
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.
1451
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.
1457
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.
1466
1467 For a more in-depth explanation of references and lifetimes, read the
1468 [references and lifetimes guide][lifetimes].
1469
1470 ## Freezing
1471
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].
1475
1476 ~~~~
1477 let mut x = 5;
1478 {
1479     let y = &x; // `x` is now frozen, it cannot be modified
1480 }
1481 // `x` is now unfrozen again
1482 # x = 3;
1483 ~~~~
1484
1485 [refcell]: http://static.rust-lang.org/doc/master/std/cell/struct.RefCell.html
1486
1487 # Dereferencing pointers
1488
1489 Rust uses the unary star operator (`*`) to access the contents of a
1490 box or pointer, similarly to C.
1491
1492 ~~~
1493 let managed = @10;
1494 let owned = ~20;
1495 let borrowed = &30;
1496
1497 let sum = *managed + *owned + *borrowed;
1498 ~~~
1499
1500 Dereferenced mutable pointers may appear on the left hand side of
1501 assignments. Such an assignment modifies the value that the pointer
1502 points to.
1503
1504 ~~~
1505 let managed = @10;
1506 let mut owned = ~20;
1507
1508 let mut value = 30;
1509 let borrowed = &mut value;
1510
1511 *owned = *borrowed + 100;
1512 *borrowed = *managed + 1000;
1513 ~~~
1514
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.
1518
1519 ~~~
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();
1527 ~~~
1528
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.
1532
1533 ~~~
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();
1541 ~~~
1542
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
1546
1547 ~~~
1548 # struct Point { x: f64, y: f64 }
1549 let point = &@~Point { x: 10.0, y: 20.0 };
1550 println!("{:f}", point.x);
1551 ~~~
1552
1553 The indexing operator (`[]`) also auto-dereferences.
1554
1555 # Vectors and strings
1556
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.
1560
1561 Strings are represented as vectors of `u8`, with the guarantee of containing a
1562 valid UTF-8 sequence.
1563
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.
1567
1568 ~~~
1569 // A fixed-size vector
1570 let numbers = [1, 2, 3];
1571 let more_numbers = numbers;
1572
1573 // The type of a fixed-size vector is written as `[Type, ..length]`
1574 let five_zeroes: [int, ..5] = [0, ..5];
1575 ~~~
1576
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.
1580
1581 ~~~
1582 // A dynamically sized vector (unique vector)
1583 let mut numbers = ~[1, 2, 3];
1584 numbers.push(4);
1585 numbers.push(5);
1586
1587 // The type of a unique vector is written as `~[int]`
1588 let more_numbers: ~[int] = numbers;
1589
1590 // The original `numbers` value can no longer be used, due to move semantics.
1591
1592 let mut string = ~"fo";
1593 string.push_char('o');
1594 ~~~
1595
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
1598 the elements.
1599
1600 ~~~
1601 // A slice
1602 let xs = &[1, 2, 3];
1603
1604 // Slices have their type written as `&[int]`
1605 let ys: &[int] = xs;
1606
1607 // Other vector types coerce to slices
1608 let three = [1, 2, 3];
1609 let zs: &[int] = three;
1610
1611 // An unadorned string literal is an immutable string slice
1612 let string = "foobar";
1613
1614 // A string slice type is written as `&str`
1615 let view: &str = string.slice(0, 3);
1616 ~~~
1617
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
1621 alter the length.
1622
1623 ~~~
1624 let mut xs = [1, 2, 3];
1625 let view = xs.mut_slice(0, 2);
1626 view[0] = 5;
1627
1628 // The type of a mutable slice is written as `&mut [T]`
1629 let ys: &mut [int] = &mut [1, 2, 3];
1630 ~~~
1631
1632 Square brackets denote indexing into a vector:
1633
1634 ~~~~
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];
1640 match crayons[0] {
1641     Bittersweet => draw_scene(crayons[0]),
1642     _ => ()
1643 }
1644 ~~~~
1645
1646 A vector can be destructured using pattern matching:
1647
1648 ~~~~
1649 let numbers: &[int] = &[1, 2, 3];
1650 let score = match numbers {
1651     [] => 0,
1652     [a] => a * 10,
1653     [a, b] => a * 6 + b * 4,
1654     [a, b, c, ..rest] => a * 5 + b * 3 + c * 2 + rest.len() as int
1655 };
1656 ~~~~
1657
1658 Both vectors and strings support a number of useful [methods](#methods),
1659 defined in [`std::vec`] and [`std::str`].
1660
1661 [`std::vec`]: std/vec/index.html
1662 [`std::str`]: std/str/index.html
1663
1664 # Ownership escape hatches
1665
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.
1668
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.
1672
1673 ~~~
1674 use std::rc::Rc;
1675
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
1680
1681 assert_eq!(*z.borrow(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1682
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]);
1685 a = z;
1686 ~~~
1687
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.
1691
1692 ~~~
1693 use std::gc::Gc;
1694
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`
1698 let z = x;
1699
1700 assert_eq!(*z.borrow(), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1701 ~~~
1702
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.
1706
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.
1709
1710 # Closures
1711
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:
1716
1717 ~~~~ {.ignore}
1718 let foo = 10;
1719
1720 fn bar() -> int {
1721    return foo; // `bar` cannot refer to `foo`
1722 }
1723 ~~~~
1724
1725 Rust also supports _closures_, functions that can access variables in
1726 the enclosing scope.
1727
1728 ~~~~
1729 fn call_closure_with_ten(b: |int|) { b(10); }
1730
1731 let captured_var = 20;
1732 let closure = |arg| println!("captured_var={}, arg={}", captured_var, arg);
1733
1734 call_closure_with_ten(closure);
1735 ~~~~
1736
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 `()`.
1742
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
1746 annotated.
1747
1748 ~~~~
1749 let square = |x: int| -> uint { (x * x) as uint };
1750 ~~~~
1751
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.
1755
1756 ~~~~
1757 let mut max = 0;
1758 [1, 2, 3].map(|x| if *x > max { max = *x });
1759 ~~~~
1760
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.
1769
1770 ## Owned closures
1771
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].
1778
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.
1782
1783 ~~~~
1784 use std::task::spawn;
1785
1786 // proc is the closure which will be spawned.
1787 spawn(proc() {
1788     debug!("I'm a new task")
1789 });
1790 ~~~~
1791
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`).
1796
1797 ## Closure compatibility
1798
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.
1805
1806 ~~~~
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);
1812 ~~~~
1813
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.
1817
1818 # Methods
1819
1820 Methods are like functions except that they always begin with a special argument,
1821 called `self`,
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()`.
1825
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.
1829
1830 ~~~
1831 # fn draw_circle(p: Point, f: f64) { }
1832 # fn draw_rectangle(p: Point, p: Point) { }
1833 struct Point {
1834     x: f64,
1835     y: f64
1836 }
1837
1838 enum Shape {
1839     Circle(Point, f64),
1840     Rectangle(Point, Point)
1841 }
1842
1843 impl Shape {
1844     fn draw(&self) {
1845         match *self {
1846             Circle(p, f) => draw_circle(p, f),
1847             Rectangle(p1, p2) => draw_rectangle(p1, p2)
1848         }
1849     }
1850 }
1851
1852 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1853 s.draw();
1854 ~~~
1855
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`.
1859
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.
1864
1865 ~~~
1866 # fn draw_circle(p: Point, f: f64) { }
1867 # fn draw_rectangle(p: Point, p: Point) { }
1868 # struct Point { x: f64, y: f64 }
1869 # enum Shape {
1870 #     Circle(Point, f64),
1871 #     Rectangle(Point, Point)
1872 # }
1873 impl Shape {
1874     fn draw_reference(&self) { ... }
1875     fn draw_owned(~self) { ... }
1876     fn draw_value(self) { ... }
1877 }
1878
1879 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1880
1881 (~s).draw_owned();
1882 (&s).draw_reference();
1883 s.draw_value();
1884 ~~~
1885
1886 Methods typically take a reference self type,
1887 so the compiler will go to great lengths to convert a callee
1888 to a reference.
1889
1890 ~~~
1891 # fn draw_circle(p: Point, f: f64) { }
1892 # fn draw_rectangle(p: Point, p: Point) { }
1893 # struct Point { x: f64, y: f64 }
1894 # enum Shape {
1895 #     Circle(Point, f64),
1896 #     Rectangle(Point, Point)
1897 # }
1898 # impl Shape {
1899 #    fn draw_reference(&self) { ... }
1900 #    fn draw_owned(~self) { ... }
1901 #    fn draw_value(self) { ... }
1902 # }
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
1906
1907 (@s).draw_reference();
1908 (~s).draw_reference();
1909
1910 // Unlike typical function arguments, the self value will
1911 // automatically be referenced ...
1912 s.draw_reference();
1913
1914 // ... and dereferenced
1915 (& &s).draw_reference();
1916
1917 // ... and dereferenced and borrowed
1918 (&@~s).draw_reference();
1919 ~~~
1920
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.
1924
1925 ~~~~ {.ignore}
1926 impl Circle {
1927     fn area(&self) -> f64 { ... }
1928     fn new(area: f64) -> Circle { ... }
1929 }
1930 ~~~~
1931
1932 To call such a method, just prefix it with the type name and a double colon:
1933
1934 ~~~~
1935 use std::f64::consts::PI;
1936 struct Circle { radius: f64 }
1937 impl Circle {
1938     fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
1939 }
1940 let c = Circle::new(42.5);
1941 ~~~~
1942
1943 # Generics
1944
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
1951 of `vector`:
1952
1953 ~~~~
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));
1958     }
1959     return accumulator;
1960 }
1961 ~~~~
1962
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
1966 each other.
1967
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.
1977
1978 Generic `type`, `struct`, and `enum` declarations follow the same pattern:
1979
1980 ~~~~
1981 use std::hashmap::HashMap;
1982 type Set<T> = HashMap<T, ()>;
1983
1984 struct Stack<T> {
1985     elements: ~[T]
1986 }
1987
1988 enum Option<T> {
1989     Some(T),
1990     None
1991 }
1992 ~~~~
1993
1994 These declarations can be instantiated to valid types like `Set<int>`,
1995 `Stack<int>`, and `Option<int>`.
1996
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`.
2002
2003 ~~~~
2004 # struct Point { x: f64, y: f64 }
2005 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
2006 fn radius(shape: Shape) -> Option<f64> {
2007     match shape {
2008         Circle(_, radius) => Some(radius),
2009         Rectangle(..)      => None
2010     }
2011 }
2012 ~~~~
2013
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
2020 C++ templates.
2021
2022 ## Traits
2023
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.
2035
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.
2042
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?
2046 In Rust, we can't,
2047 and if we try to run the following code the compiler will complain.
2048
2049 ~~~~ {.ignore}
2050 // This does not compile
2051 fn head_bad<T>(v: &[T]) -> T {
2052     v[0] // error: copying a non-copyable value
2053 }
2054 ~~~~
2055
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:
2061
2062 ~~~~
2063 // This does
2064 fn head<T: Clone>(v: &[T]) -> T {
2065     v[0].clone()
2066 }
2067 ~~~~
2068
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`.
2078
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:
2083
2084 * `Send` - Sendable types.
2085 Types are sendable
2086 unless they contain managed boxes, managed closures, or references.
2087
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.
2091
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.
2097
2098 > ***Note:*** These two traits were referred to as 'kinds' in earlier
2099 > iterations of the language, and often still are.
2100
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.
2106
2107 ~~~
2108 struct TimeBomb {
2109     explosivity: uint
2110 }
2111
2112 impl Drop for TimeBomb {
2113     fn drop(&mut self) {
2114         for _ in range(0, self.explosivity) {
2115             println!("blam!");
2116         }
2117     }
2118 }
2119 ~~~
2120
2121 It is illegal to call `drop` directly. Only code inserted by the compiler
2122 may call it.
2123
2124 ## Declaring and implementing traits
2125
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:
2130
2131 ~~~~
2132 trait Printable {
2133     fn print(&self);
2134 }
2135 ~~~~
2136
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.
2140
2141 Rust's built-in `Send` and `Freeze` types are examples of traits that
2142 don't provide any methods.
2143
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`
2148 method.
2149
2150 [impls]: #methods
2151
2152 ~~~~
2153 # trait Printable { fn print(&self); }
2154 impl Printable for int {
2155     fn print(&self) { println!("{:?}", *self) }
2156 }
2157
2158 impl Printable for ~str {
2159     fn print(&self) { println!("{}", *self) }
2160 }
2161
2162 # 1.print();
2163 # (~"foo").print();
2164 ~~~~
2165
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()`.
2168
2169 ## Default method implementations in trait definitions
2170
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:
2176
2177 ~~~~
2178 # trait Printable { fn print(&self); }
2179 impl Printable for f32 {
2180     fn print(&self) { println!("{:?}", *self) }
2181 }
2182
2183 impl Printable for bool {
2184     fn print(&self) { println!("{:?}", *self) }
2185 }
2186
2187 # true.print();
2188 # 3.14159.print();
2189 ~~~~
2190
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:
2195
2196 ~~~~
2197 trait Printable {
2198         // Default method implementation
2199     fn print(&self) { println!("{:?}", *self) }
2200 }
2201
2202 impl Printable for int {}
2203
2204 impl Printable for ~str {
2205     fn print(&self) { println!("{}", *self) }
2206 }
2207
2208 impl Printable for bool {}
2209
2210 impl Printable for f32 {}
2211
2212 # 1.print();
2213 # (~"foo").print();
2214 # true.print();
2215 # 3.14159.print();
2216 ~~~~
2217
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
2225 `~str`.
2226
2227 ## Type-parameterized traits
2228
2229 Traits may be parameterized by type variables.  For example, a trait
2230 for generalized sequence types might look like the following:
2231
2232 ~~~~
2233 trait Seq<T> {
2234     fn length(&self) -> uint;
2235 }
2236
2237 impl<T> Seq<T> for ~[T] {
2238     fn length(&self) -> uint { self.len() }
2239 }
2240 ~~~~
2241
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
2247 defining one.
2248
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.
2253
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:
2258
2259 ~~~~
2260 // In a trait, `self` refers to the self argument.
2261 // `Self` refers to the type implementing the trait.
2262 trait Eq {
2263     fn equals(&self, other: &Self) -> bool;
2264 }
2265
2266 // In an impl, `self` refers just to the value of the receiver
2267 impl Eq for int {
2268     fn equals(&self, other: &int) -> bool { *other == *self }
2269 }
2270 ~~~~
2271
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.
2276
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.
2281
2282 ~~~~
2283 use std::f64::consts::PI;
2284 trait Shape { fn new(area: f64) -> Self; }
2285 struct Circle { radius: f64 }
2286 struct Square { length: f64 }
2287
2288 impl Shape for Circle {
2289     fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
2290 }
2291 impl Shape for Square {
2292     fn new(area: f64) -> Square { Square { length: (area).sqrt() } }
2293 }
2294
2295 let area = 42.5;
2296 let c: Circle = Shape::new(area);
2297 let s: Square = Shape::new(area);
2298 ~~~~
2299
2300 ## Bounded type parameters and static method dispatch
2301
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
2305 generic types.
2306
2307 ~~~~
2308 # trait Printable { fn print(&self); }
2309 fn print_all<T: Printable>(printable_things: ~[T]) {
2310     for thing in printable_things.iter() {
2311         thing.print();
2312     }
2313 }
2314 ~~~~
2315
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.
2321
2322 Type parameters can have multiple bounds by separating them with `+`,
2323 as in this version of `print_all` that copies elements.
2324
2325 ~~~
2326 # trait Printable { fn print(&self); }
2327 fn print_all<T: Printable + Clone>(printable_things: ~[T]) {
2328     let mut i = 0;
2329     while i < printable_things.len() {
2330         let copy_of_thing = printable_things[i].clone();
2331         copy_of_thing.print();
2332         i += 1;
2333     }
2334 }
2335 ~~~
2336
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.
2340
2341 This usage of traits is similar to Haskell type classes.
2342
2343 ## Trait objects and dynamic method dispatch
2344
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:
2348
2349 ~~~~
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); }
2354
2355 fn draw_all<T: Drawable>(shapes: ~[T]) {
2356     for shape in shapes.iter() { shape.draw(); }
2357 }
2358 # let c: Circle = new_circle();
2359 # draw_all(~[c]);
2360 ~~~~
2361
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
2366 an _object_.
2367
2368 ~~~~
2369 # trait Drawable { fn draw(&self); }
2370 fn draw_all(shapes: &[~Drawable]) {
2371     for shape in shapes.iter() { shape.draw(); }
2372 }
2373 ~~~~
2374
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
2378 to an object:
2379
2380 ~~~~
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]) {}
2386
2387 impl Drawable for Circle { fn draw(&self) { ... } }
2388 impl Drawable for Rectangle { fn draw(&self) { ... } }
2389
2390 let c: ~Circle = ~new_circle();
2391 let r: ~Rectangle = ~new_rectangle();
2392 draw_all([c as ~Drawable, r as ~Drawable]);
2393 ~~~~
2394
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`.
2402
2403 ~~~
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 }
2409 // An owned object
2410 let owny: ~Drawable = ~new_circle() as ~Drawable;
2411 // A borrowed object
2412 let stacky: &Drawable = &new_circle() as &Drawable;
2413 ~~~
2414
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.
2419
2420 This usage of traits is similar to Java interfaces.
2421
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.
2425
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.
2428
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`.
2436
2437 * `~Trait:Send` is equivalent to `~Trait`.
2438 * `&Trait:` is equivalent to `&Trait`.
2439
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.
2443
2444 ## Trait inheritance
2445
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.
2448 For example,
2449 we can define a `Circle` trait that inherits from `Shape`.
2450
2451 ~~~~
2452 trait Shape { fn area(&self) -> f64; }
2453 trait Circle : Shape { fn radius(&self) -> f64; }
2454 ~~~~
2455
2456 Now, we can implement `Circle` on a type only if we also implement `Shape`.
2457
2458 ~~~~
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() }
2467 }
2468 impl Shape for CircleStruct {
2469     fn area(&self) -> f64 { PI * square(self.radius) }
2470 }
2471 ~~~~
2472
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.
2477
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`:
2481
2482 ~~~
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()
2488 }
2489 ~~~
2490
2491 Likewise, supertrait methods may also be called on trait objects.
2492
2493 ~~~ {.ignore}
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) } }
2501
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();
2505 ~~~
2506
2507 > ***Note:*** Trait inheritance does not actually work with objects yet
2508
2509 ## Deriving implementations for traits
2510
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:
2517
2518 ~~~
2519 #[deriving(Eq)]
2520 struct Circle { radius: f64 }
2521
2522 #[deriving(Rand, ToStr)]
2523 enum ABC { A, B, C }
2524 ~~~
2525
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`.
2529
2530 # Crates and the module system
2531
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.
2534
2535 ## Crates
2536
2537 In order to speak about the module system, we first need to define the medium it exists in:
2538
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'.
2542
2543 For example, for a simple hello world program your crate only consists of this code:
2544
2545 ~~~~
2546 // `main.rs`
2547 fn main() {
2548     println!("Hello world!");
2549 }
2550 ~~~~
2551
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.
2554
2555 Note that merely using an already compiled library in your code does not make it part of your crate.
2556
2557 ## The module hierarchy
2558
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'.
2561
2562 All modules in a crate below the crate root are declared with the `mod` keyword:
2563
2564 ~~~~
2565 // This is the crate root
2566
2567 mod farm {
2568     // This is the body of module 'farm' declared in the crate root.
2569
2570     fn chicken() { println!("cluck cluck"); }
2571     fn cow() { println!("mooo"); }
2572
2573     mod barn {
2574         // Body of module 'barn'
2575
2576         fn hay() { println!("..."); }
2577     }
2578 }
2579
2580 fn main() {
2581     println!("Hello farm!");
2582 }
2583 ~~~~
2584
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`.
2588
2589 (In case you already stumbled over `extern crate`: It isn't directly related to a bare `mod`, we'll get to it later. )
2590
2591 ## Paths and visibility
2592
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:
2595
2596 ~~~~ {.ignore}
2597 mod farm {
2598     fn chicken() { println!("cluck cluck"); }
2599     // ...
2600 }
2601
2602 fn main() {
2603     println!("Hello chicken!");
2604
2605     ::farm::chicken(); // Won't compile yet, see further down
2606 }
2607 ~~~~
2608
2609 The `::farm::chicken` construct is what we call a 'path'.
2610
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.
2613
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.
2616
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.
2620
2621 To make them visible outside their containing modules, you need to mark them
2622 _public_ with `pub`:
2623
2624 ~~~~
2625 mod farm {
2626     pub fn chicken() { println!("cluck cluck"); }
2627     pub fn cow() { println!("mooo"); }
2628     // ...
2629 }
2630
2631 fn main() {
2632     println!("Hello chicken!");
2633     ::farm::chicken(); // This compiles now
2634 }
2635 ~~~~
2636
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
2642 struct level.
2643
2644 For convenience, fields are _public_ by default, and can be made _private_ with
2645 the `priv` keyword:
2646
2647 ~~~
2648 mod farm {
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) } }
2653     pub struct Farm {
2654         priv chickens: ~[Chicken],
2655         farmer: Human
2656     }
2657
2658     impl Farm {
2659         fn feed_chickens(&self) { ... }
2660         pub fn add_chicken(&self, c: Chicken) { ... }
2661     }
2662
2663     pub fn feed_animals(farm: &Farm) {
2664         farm.feed_chickens();
2665     }
2666 }
2667
2668 fn main() {
2669     let f = make_me_a_farm();
2670     f.add_chicken(make_me_a_chicken());
2671     farm::feed_animals(&f);
2672     f.farmer.rest();
2673
2674     // This wouldn't compile because both are private:
2675     // `f.feed_chickens();`
2676     // `let chicken_counter = f.chickens.len();`
2677 }
2678 # fn make_me_a_farm() -> farm::Farm { farm::make_me_a_farm() }
2679 # fn make_me_a_chicken() -> farm::Chicken { 0 }
2680 ~~~
2681
2682 Exact details and specifications about visibility rules can be found in the Rust
2683 manual.
2684
2685 ## Files and modules
2686
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.
2688
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.
2692
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.
2695
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.
2703
2704 To move the content of `mod farm` into its own file, you can write:
2705
2706 ~~~~ {.ignore}
2707 // `main.rs` - contains body of the crate root
2708 mod farm; // Compiler will look for `farm.rs` and `farm/mod.rs`
2709
2710 fn main() {
2711     println!("Hello farm!");
2712     ::farm::cow();
2713 }
2714 ~~~~
2715
2716 ~~~~
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"); }
2720
2721 pub mod barn {
2722     pub fn hay() { println!("..."); }
2723 }
2724 # fn main() { }
2725 ~~~~
2726
2727 In short, `mod foo;` is just syntactic sugar for `mod foo { /* content of <...>/foo.rs or <...>/foo/mod.rs */ }`.
2728
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.
2732
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:
2736
2737 ~~~ {.ignore}
2738 // `src/main.rs`
2739 mod plants;
2740 mod animals {
2741     mod fish;
2742     mod mammals {
2743         mod humans;
2744     }
2745 }
2746 ~~~
2747
2748 The compiler will look for these files, in this order:
2749
2750 ~~~ {.notrust}
2751 src/plants.rs
2752 src/plants/mod.rs
2753
2754 src/animals/fish.rs
2755 src/animals/fish/mod.rs
2756
2757 src/animals/mammals/humans.rs
2758 src/animals/mammals/humans/mod.rs
2759 ~~~
2760
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:
2764
2765 ~~~ {.ignore}
2766 // `src/main.rs`
2767 mod plants;
2768 mod animals;
2769 ~~~
2770
2771 ~~~ {.ignore}
2772 // `src/animals.rs` or `src/animals/mod.rs`
2773 mod fish;
2774 mod mammals {
2775     mod humans;
2776 }
2777 ~~~
2778
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:
2780
2781 ~~~ {.notrust}
2782 src/animals.rs
2783     src/fish.rs
2784     src/fish/mod.rs
2785
2786     src/mammals/humans.rs
2787     src/mammals/humans/mod.rs
2788 ~~
2789
2790 If the animals file is `src/animals/mod.rs`, `rustc` will look for:
2791
2792 ~~ {.notrust}
2793 src/animals/mod.rs
2794     src/animals/fish.rs
2795     src/animals/fish/mod.rs
2796
2797     src/animals/mammals/humans.rs
2798     src/animals/mammals/humans/mod.rs
2799
2800 ~~~
2801
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.
2803
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:
2807
2808 ~~~ {.ignore}
2809 #[path="../../area51/alien.rs"]
2810 mod classified;
2811 ~~~
2812
2813 ## Importing names into the local scope
2814
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.
2818
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:
2822
2823 ~~~
2824 use farm::cow;
2825 # mod farm { pub fn cow() { println!("I'm a hidden ninja cow!") } }
2826 # fn main() { cow() }
2827 ~~~
2828
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).
2832
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.
2836
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:
2840
2841 ~~~
2842 # mod workaround {
2843 # pub fn some_parent_item(){ println!("...") }
2844 # mod foo {
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() {} }
2849 # }
2850 # }
2851 ~~~
2852
2853 Again - relative to the module, not to the file.
2854
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.
2860
2861 ~~~ {.ignore}
2862 # // FIXME: Allow unused import in doc test
2863 use farm::cow;
2864 // ...
2865 # mod farm { pub fn cow() { println!("Hidden ninja cow is hidden.") } }
2866 fn cow() { println!("Mooo!") }
2867
2868 fn main() {
2869     cow() // resolves to the locally defined `cow()` function
2870 }
2871 ~~~
2872
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.
2877
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:
2880
2881 ~~~
2882 use farm::cow;
2883 mod farm {
2884     pub fn cow() { println!("Moooooo?") }
2885 }
2886
2887 fn main() { cow() }
2888 ~~~
2889
2890 This is what our `farm` example looks like with `use` statements:
2891
2892 ~~~~
2893 use farm::chicken;
2894 use farm::cow;
2895 use farm::barn;
2896
2897 mod farm {
2898     pub fn chicken() { println!("cluck cluck"); }
2899     pub fn cow() { println!("mooo"); }
2900
2901     pub mod barn {
2902         pub fn hay() { println!("..."); }
2903     }
2904 }
2905
2906 fn main() {
2907     println!("Hello farm!");
2908
2909     // Can now refer to those names directly:
2910     chicken();
2911     cow();
2912     barn::hay();
2913 }
2914 ~~~~
2915
2916 And here an example with multiple files:
2917
2918 ~~~{.ignore}
2919 // `a.rs` - crate root
2920 use b::foo;
2921 mod b;
2922 fn main() { foo(); }
2923 ~~~
2924
2925 ~~~{.ignore}
2926 // `b.rs`
2927 use b::c::bar;
2928 pub mod c;
2929 pub fn foo() { bar(); }
2930 ~~~
2931
2932 ~~~
2933 // `c.rs`
2934 pub fn bar() { println!("Baz!"); }
2935 # fn main() {}
2936 ~~~
2937
2938 There also exist two short forms for importing multiple names at once:
2939
2940 1. Explicit mention multiple names as the last element of an `use` path:
2941
2942 ~~~
2943 use farm::{chicken, cow};
2944 # mod farm {
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.") }
2947 # }
2948 # fn main() { cow(); chicken() }
2949 ~~~
2950
2951 2. Import everything in a module with a wildcard:
2952
2953 ~~~
2954 use farm::*;
2955 # mod farm {
2956 #     pub fn cow() { println!("Bat-chicken? What a stupid name!") }
2957 #     pub fn chicken() { println!("Says the 'hidden ninja' cow.") }
2958 # }
2959 # fn main() { cow(); chicken() }
2960 ~~~
2961
2962 > ***Note:*** This feature of the compiler is currently gated behind the
2963 > `#[feature(globs)]` directive. More about these directives can be found in
2964 > the manual.
2965
2966 However, that's not all. You can also rename an item while you're bringing it into scope:
2967
2968 ~~~
2969 use egg_layer = farm::chicken;
2970 # mod farm { pub fn chicken() { println!("Laying eggs is fun!")  } }
2971 // ...
2972
2973 fn main() {
2974     egg_layer();
2975 }
2976 ~~~
2977
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.
2981
2982 ## Reexporting names
2983
2984 It is also possible to reexport items to be accessible under your module.
2985
2986 For that, you write `pub use`:
2987
2988 ~~~
2989 mod farm {
2990     pub use self::barn::hay;
2991
2992     pub fn chicken() { println!("cluck cluck"); }
2993     pub fn cow() { println!("mooo"); }
2994
2995     mod barn {
2996         pub fn hay() { println!("..."); }
2997     }
2998 }
2999
3000 fn main() {
3001     farm::chicken();
3002     farm::cow();
3003     farm::hay();
3004 }
3005 ~~~
3006
3007 Just like in normal `use` statements, the exported names
3008 merely represent an alias to the same thing and can also be renamed.
3009
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.
3014
3015 In other words, you can use them to decouple an public api from their internal implementation.
3016
3017 ## Using libraries
3018
3019 So far we've only talked about how to define and structure your own crate.
3020
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.
3023
3024 In Rust terminology, we need a way to refer to other crates.
3025
3026 For that, Rust offers you the `extern crate` declaration:
3027
3028 ~~~
3029 extern crate num;
3030 // `num` ships with Rust (much like `extra`; more details further down).
3031
3032 fn main() {
3033     // The rational number '1/2':
3034     let one_half = ::num::rational::Ratio::new(1, 2);
3035 }
3036 ~~~
3037
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.
3041
3042 The effect it has on your module hierarchy mirrors aspects of both `mod` and `use`:
3043
3044 - Like `mod`, it causes `rustc` to actually emit code:
3045   The linkage information the binary needs to use the library `foo`.
3046
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).
3050
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.
3055
3056 Which can result in something like this:
3057
3058 ~~~
3059 extern crate num;
3060
3061 use farm::dog;
3062 use num::rational::Ratio;
3063
3064 mod farm {
3065     pub fn dog() { println!("woof"); }
3066 }
3067
3068 fn main() {
3069     farm::dog();
3070     let a_third = Ratio::new(1, 3);
3071 }
3072 ~~~
3073
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.
3076
3077 ## Package ids
3078
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).
3081
3082 ## Crate metadata and settings
3083
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.
3087
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
3091 without conflict.
3092
3093 Therefore, if you plan to compile your crate as a library, you should annotate it with that information:
3094
3095 ~~~~
3096 // `lib.rs`
3097
3098 # #[crate_type = "lib"];
3099 // Package ID
3100 #[crate_id = "farm#2.5"];
3101
3102 // ...
3103 # fn farm() {}
3104 ~~~~
3105
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
3108 crate define above:
3109
3110 ~~~~ {.ignore}
3111 extern crate farm;
3112 extern crate farm = "farm#2.5";
3113 extern crate my_farm = "farm";
3114 ~~~~
3115
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:
3118
3119 ~~~~
3120 // `lib.rs`
3121 // ...
3122
3123 // This crate is a library ("bin" is the default)
3124 #[crate_id = "farm#2.5"];
3125 #[crate_type = "lib"];
3126
3127 // Turn on a warning
3128 #[warn(non_camel_case_types)]
3129 # fn farm() {}
3130 ~~~~
3131
3132 ## A minimal example
3133
3134 Now for something that you can actually compile yourself.
3135
3136 We define two crates, and use one of them as a library in the other.
3137
3138 ~~~~
3139 // `world.rs`
3140 #[crate_id = "world#0.42"];
3141 # extern crate extra;
3142 pub fn explore() -> &'static str { "world" }
3143 # fn main() {}
3144 ~~~~
3145
3146 ~~~~ {.ignore}
3147 // `main.rs`
3148 extern crate world;
3149 fn main() { println!("hello {}", world::explore()); }
3150 ~~~~
3151
3152 Now compile and run like this (adjust to your platform if necessary):
3153
3154 ~~~~ {.notrust}
3155 > rustc --crate-type=lib world.rs  # compiles libworld-<HASH>-0.42.so
3156 > rustc main.rs -L .               # compiles main
3157 > ./main
3158 "hello world"
3159 ~~~~
3160
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.
3165
3166 ## The standard library and the prelude
3167
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.
3170
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.
3173
3174 The only magical thing that happens is that `rustc` automatically inserts this line into your crate root:
3175
3176 ~~~ {.ignore}
3177 extern crate std;
3178 ~~~
3179
3180 As well as this line into every module body:
3181
3182 ~~~ {.ignore}
3183 use std::prelude::*;
3184 ~~~
3185
3186 The role of the `prelude` module is to re-export common definitions from `std`.
3187
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.
3191
3192 For example, it re-exports `range` which is defined in `std::iter::range`:
3193
3194 ~~~
3195 use iter_range = std::iter::range;
3196
3197 fn main() {
3198     // `range` is imported by default
3199     for _ in range(0, 10) {}
3200
3201     // Doesn't hinder you from importing it under a different name yourself
3202     for _ in iter_range(0, 10) {}
3203
3204     // Or from not using the automatic import.
3205     for _ in ::std::iter::range(0, 10) {}
3206 }
3207 ~~~
3208
3209 Both auto-insertions can be disabled with an attribute if necessary:
3210
3211 ~~~
3212 // In the crate root:
3213 #[no_std];
3214 ~~~
3215
3216 ~~~
3217 // In any module:
3218 #[no_implicit_prelude];
3219 ~~~
3220
3221 See the [API documentation][stddoc] for details.
3222
3223 [stddoc]: std/index.html
3224
3225 ## The extra library
3226
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;`.
3230
3231 [extra library]: extra/index.html
3232
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
3235 package manager.
3236
3237 # What next?
3238
3239 Now that you know the essentials, check out any of the additional
3240 guides on individual topics.
3241
3242 * [Pointers][pointers]
3243 * [Lifetimes][lifetimes]
3244 * [Tasks and communication][tasks]
3245 * [Macros][macros]
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]
3251
3252 There is further documentation on the [wiki], however those tend to be even more out of date as this document.
3253
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
3264
3265 [wiki-packages]: https://github.com/mozilla/rust/wiki/Doc-packages,-editors,-and-other-tools