]> git.lizzy.rs Git - rust.git/blob - src/doc/tutorial.md
auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw
[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.
86
87 [wiki-start]: https://github.com/mozilla/rust/wiki/Note-getting-started-developing-Rust
88 [git]: https://github.com/mozilla/rust.git
89
90 To build from source you will also need the following prerequisite
91 packages:
92
93 * g++ 4.4 or clang++ 3.x
94 * python 2.6 or later (but not 3.x)
95 * perl 5.0 or later
96 * gnu make 3.81 or later
97 * curl
98
99 If you've fulfilled those prerequisites, something along these lines
100 should work.
101
102 ~~~~ {.notrust}
103 $ curl -O http://static.rust-lang.org/dist/rust-0.9.tar.gz
104 $ tar -xzf rust-0.9.tar.gz
105 $ cd rust-0.9
106 $ ./configure
107 $ make && make install
108 ~~~~
109
110 You may need to use `sudo make install` if you do not normally have
111 permission to modify the destination directory. The install locations
112 can be adjusted by passing a `--prefix` argument to
113 `configure`. Various other options are also supported: pass `--help`
114 for more information on them.
115
116 When complete, `make install` will place several programs into
117 `/usr/local/bin`: `rustc`, the Rust compiler, and `rustdoc`, the
118 API-documentation tool.
119
120 [tarball]: http://static.rust-lang.org/dist/rust-0.9.tar.gz
121 [win-exe]: http://static.rust-lang.org/dist/rust-0.9-install.exe
122
123 ## Compiling your first program
124
125 Rust program files are, by convention, given the extension `.rs`. Say
126 we have a file `hello.rs` containing this program:
127
128 ~~~~
129 fn main() {
130     println!("hello?");
131 }
132 ~~~~
133 > ***Note:*** An identifier followed by an exclamation point, like
134 > `println!`, is a macro invocation.  Macros are explained
135 > [later](#syntax-extensions); for now just remember to include the
136 > exclamation point.
137
138 If the Rust compiler was installed successfully, running `rustc
139 hello.rs` will produce an executable called `hello` (or `hello.exe` on
140 Windows) which, upon running, will likely do exactly what you expect.
141
142 The Rust compiler tries to provide useful information when it encounters an
143 error. If you introduce an error into the program (for example, by changing
144 `println!` to some nonexistent macro), and then compile it, you'll see
145 an error message like this:
146
147 ~~~~ {.notrust}
148 hello.rs:2:5: 2:24 error: macro undefined: 'print_with_unicorns'
149 hello.rs:2     print_with_unicorns!("hello?");
150                ^~~~~~~~~~~~~~~~~~~
151 ~~~~
152
153 In its simplest form, a Rust program is a `.rs` file with some types
154 and functions defined in it. If it has a `main` function, it can be
155 compiled to an executable. Rust does not allow code that's not a
156 declaration to appear at the top level of the file: all statements must
157 live inside a function.  Rust programs can also be compiled as
158 libraries, and included in other programs, even ones not written in Rust.
159
160 ## Editing Rust code
161
162 There are vim highlighting and indentation scripts in the Rust source
163 distribution under `src/etc/vim/`. There is an emacs mode under
164 `src/etc/emacs/` called `rust-mode`, but do read the instructions
165 included in that directory. In particular, if you are running emacs
166 24, then using emacs's internal package manager to install `rust-mode`
167 is the easiest way to keep it up to date. There is also a package for
168 Sublime Text 2, available both [standalone][sublime] and through
169 [Sublime Package Control][sublime-pkg], and support for Kate
170 under `src/etc/kate`.
171
172 A community-maintained list of available Rust tooling is [on the
173 wiki][wiki-packages].
174
175 There is ctags support via `src/etc/ctags.rust`, but many other
176 tools and editors are not yet supported. If you end up writing a Rust
177 mode for your favorite editor, let us know so that we can link to it.
178
179 [sublime]: http://github.com/dbp/sublime-rust
180 [sublime-pkg]: http://wbond.net/sublime_packages/package_control
181
182 # Syntax basics
183
184 Assuming you've programmed in any C-family language (C++, Java,
185 JavaScript, C#, or PHP), Rust will feel familiar. Code is arranged
186 in blocks delineated by curly braces; there are control structures
187 for branching and looping, like the familiar `if` and `while`; function
188 calls are written `myfunc(arg1, arg2)`; operators are written the same
189 and mostly have the same precedence as in C; comments are again like C;
190 module names are separated with double-colon (`::`) as with C++.
191
192 The main surface difference to be aware of is that the condition at
193 the head of control structures like `if` and `while` does not require
194 parentheses, while their bodies *must* be wrapped in
195 braces. Single-statement, unbraced bodies are not allowed.
196
197 ~~~~
198 # mod universe { pub fn recalibrate() -> bool { true } }
199 fn main() {
200     /* A simple loop */
201     loop {
202         // A tricky calculation
203         if universe::recalibrate() {
204             return;
205         }
206     }
207 }
208 ~~~~
209
210 The `let` keyword introduces a local variable. Variables are immutable by
211 default. To introduce a local variable that you can re-assign later, use `let
212 mut` instead.
213
214 ~~~~
215 let hi = "hi";
216 let mut count = 0;
217
218 while count < 10 {
219     println!("count is {}", count);
220     count += 1;
221 }
222 ~~~~
223
224 Although Rust can almost always infer the types of local variables, you can
225 specify a variable's type by following it in the `let` with a colon, then the
226 type name. Static items, on the other hand, always require a type annotation.
227
228
229 ~~~~
230 static MONSTER_FACTOR: f64 = 57.8;
231 let monster_size = MONSTER_FACTOR * 10.0;
232 let monster_size: int = 50;
233 ~~~~
234
235 Local variables may shadow earlier declarations, as in the previous example:
236 `monster_size` was first declared as a `f64`, and then a second
237 `monster_size` was declared as an `int`. If you were to actually compile this
238 example, though, the compiler would determine that the first `monster_size` is
239 unused and issue a warning (because this situation is likely to indicate a
240 programmer error). For occasions where unused variables are intentional, their
241 names may be prefixed with an underscore to silence the warning, like `let
242 _monster_size = 50;`.
243
244 Rust identifiers start with an alphabetic
245 character or an underscore, and after that may contain any sequence of
246 alphabetic characters, numbers, or underscores. The preferred style is to
247 write function, variable, and module names with lowercase letters, using
248 underscores where they help readability, while writing types in camel case.
249
250 ~~~
251 let my_variable = 100;
252 type MyType = int;     // primitive types are _not_ camel case
253 ~~~
254
255 ## Expressions and semicolons
256
257 Though it isn't apparent in all code, there is a fundamental
258 difference between Rust's syntax and predecessors like C.
259 Many constructs that are statements in C are expressions
260 in Rust, allowing code to be more concise. For example, you might
261 write a piece of code like this:
262
263 ~~~~
264 # let item = "salad";
265 let price;
266 if item == "salad" {
267     price = 3.50;
268 } else if item == "muffin" {
269     price = 2.25;
270 } else {
271     price = 2.00;
272 }
273 ~~~~
274
275 But, in Rust, you don't have to repeat the name `price`:
276
277 ~~~~
278 # let item = "salad";
279 let price =
280     if item == "salad" {
281         3.50
282     } else if item == "muffin" {
283         2.25
284     } else {
285         2.00
286     };
287 ~~~~
288
289 Both pieces of code are exactly equivalent: they assign a value to
290 `price` depending on the condition that holds. Note that there
291 are no semicolons in the blocks of the second snippet. This is
292 important: the lack of a semicolon after the last statement in a
293 braced block gives the whole block the value of that last expression.
294
295 Put another way, the semicolon in Rust *ignores the value of an expression*.
296 Thus, if the branches of the `if` had looked like `{ 4; }`, the above example
297 would simply assign `()` (unit or void) to `price`. But without the semicolon, each
298 branch has a different value, and `price` gets the value of the branch that
299 was taken.
300
301 In short, everything that's not a declaration (declarations are `let` for
302 variables; `fn` for functions; and any top-level named items such as
303 [traits](#traits), [enum types](#enums), and static items) is an
304 expression, including function bodies.
305
306 ~~~~
307 fn is_four(x: int) -> bool {
308    // No need for a return statement. The result of the expression
309    // is used as the return value.
310    x == 4
311 }
312 ~~~~
313
314 ## Primitive types and literals
315
316 There are general signed and unsigned integer types, `int` and `uint`,
317 as well as 8-, 16-, 32-, and 64-bit variants, `i8`, `u16`, etc.
318 Integers can be written in decimal (`144`), hexadecimal (`0x90`), octal (`0o70`), or
319 binary (`0b10010000`) base. Each integral type has a corresponding literal
320 suffix that can be used to indicate the type of a literal: `i` for `int`,
321 `u` for `uint`, `i8` for the `i8` type.
322
323 In the absence of an integer literal suffix, Rust will infer the
324 integer type based on type annotations and function signatures in the
325 surrounding program. In the absence of any type information at all,
326 Rust will assume that an unsuffixed integer literal has type
327 `int`.
328
329 ~~~~
330 let a = 1;       // `a` is an `int`
331 let b = 10i;     // `b` is an `int`, due to the `i` suffix
332 let c = 100u;    // `c` is a `uint`
333 let d = 1000i32; // `d` is an `i32`
334 ~~~~
335
336 There are two floating-point types: `f32`, and `f64`.
337 Floating-point numbers are written `0.0`, `1e6`, or `2.1e-4`.
338 Like integers, floating-point literals are inferred to the correct type.
339 Suffixes `f32`, and `f64` can be used to create literals of a specific type.
340
341 The keywords `true` and `false` produce literals of type `bool`.
342
343 Characters, the `char` type, are four-byte Unicode codepoints,
344 whose literals are written between single quotes, as in `'x'`.
345 Just like C, Rust understands a number of character escapes, using the backslash
346 character, such as `\n`, `\r`, and `\t`. String literals,
347 written between double quotes, allow the same escape sequences, and do no
348 other processing, unlike languages such as PHP or shell.
349
350 On the other hand, raw string literals do not process any escape sequences.
351 They are written as `r##"blah"##`, with a matching number of zero or more `#`
352 before the opening and after the closing quote, and can contain any sequence of
353 characters except their closing delimiter.  More on strings
354 [later](#vectors-and-strings).
355
356 The unit type, written `()`, has a single value, also written `()`.
357
358 ## Operators
359
360 Rust's set of operators contains very few surprises. Arithmetic is done with
361 `*`, `/`, `%`, `+`, and `-` (multiply, quotient, remainder, add, and subtract). `-` is
362 also a unary prefix operator that negates numbers. As in C, the bitwise operators
363 `>>`, `<<`, `&`, `|`, and `^` are also supported.
364
365 Note that, if applied to an integer value, `!` flips all the bits (bitwise
366 NOT, like `~` in C).
367
368 The comparison operators are the traditional `==`, `!=`, `<`, `>`,
369 `<=`, and `>=`. Short-circuiting (lazy) boolean operators are written
370 `&&` (and) and `||` (or).
371
372 For compile-time type casting, Rust uses the binary `as` operator.  It takes
373 an expression on the left side and a type on the right side and will, if a
374 meaningful conversion exists, convert the result of the expression to the
375 given type. Generally, `as` is only used with the primitive numeric types or
376 pointers, and is not overloadable.  [`transmute`][transmute] can be used for
377 unsafe C-like casting of same-sized types.
378
379 ~~~~
380 let x: f64 = 4.0;
381 let y: uint = x as uint;
382 assert!(y == 4u);
383 ~~~~
384
385 [transmute]: http://static.rust-lang.org/doc/master/std/cast/fn.transmute.html
386
387 ## Syntax extensions
388
389 *Syntax extensions* are special forms that are not built into the language,
390 but are instead provided by the libraries. To make it clear to the reader when
391 a name refers to a syntax extension, the names of all syntax extensions end
392 with `!`. The standard library defines a few syntax extensions, the most
393 useful of which is [`format!`][fmt], a `sprintf`-like text formatter that you
394 will often see in examples, and its related family of macros: `print!`,
395 `println!`, and `write!`.
396
397 `format!` draws syntax from Python, but contains many of the same principles
398 that [printf][pf] has. Unlike printf, `format!` will give you a compile-time
399 error when the types of the directives don't match the types of the arguments.
400
401 ~~~~
402 # let mystery_object = ();
403
404 // `{}` will print the "default format" of a type
405 println!("{} is {}", "the answer", 43);
406
407 // `{:?}` will conveniently print any type
408 println!("what is this thing: {:?}", mystery_object);
409 ~~~~
410
411 [pf]: http://en.cppreference.com/w/cpp/io/c/fprintf
412 [fmt]: http://static.rust-lang.org/doc/master/std/fmt/index.html
413
414 You can define your own syntax extensions with the macro system. For details,
415 see the [macro tutorial][macros]. Note that macro definition is currently
416 considered an unstable feature.
417
418 # Control structures
419
420 ## Conditionals
421
422 We've seen `if` expressions a few times already. To recap, braces are
423 compulsory, an `if` can have an optional `else` clause, and multiple
424 `if`/`else` constructs can be chained together:
425
426 ~~~~
427 if false {
428     println!("that's odd");
429 } else if true {
430     println!("right");
431 } else {
432     println!("neither true nor false");
433 }
434 ~~~~
435
436 The condition given to an `if` construct *must* be of type `bool` (no
437 implicit conversion happens). If the arms are blocks that have a
438 value, this value must be of the same type for every arm in which
439 control reaches the end of the block:
440
441 ~~~~
442 fn signum(x: int) -> int {
443     if x < 0 { -1 }
444     else if x > 0 { 1 }
445     else { 0 }
446 }
447 ~~~~
448
449 ## Pattern matching
450
451 Rust's `match` construct is a generalized, cleaned-up version of C's
452 `switch` construct. You provide it with a value and a number of
453 *arms*, each labelled with a pattern, and the code compares the value
454 against each pattern in order until one matches. The matching pattern
455 executes its corresponding arm.
456
457 ~~~~
458 # let my_number = 1;
459 match my_number {
460   0     => println!("zero"),
461   1 | 2 => println!("one or two"),
462   3..10 => println!("three to ten"),
463   _     => println!("something else")
464 }
465 ~~~~
466
467 Unlike in C, there is no "falling through" between arms: only one arm
468 executes, and it doesn't have to explicitly `break` out of the
469 construct when it is finished.
470
471 A `match` arm consists of a *pattern*, then an arrow `=>`, followed by
472 an *action* (expression). Literals are valid patterns and match only
473 their own value. A single arm may match multiple different patterns by
474 combining them with the pipe operator (`|`), so long as every pattern
475 binds the same set of variables. Ranges of numeric literal patterns
476 can be expressed with two dots, as in `M..N`. The underscore (`_`) is
477 a wildcard pattern that matches any single value. (`..`) is a different
478 wildcard that can match one or more fields in an `enum` variant.
479
480 The patterns in a match arm are followed by a fat arrow, `=>`, then an
481 expression to evaluate. Each case is separated by commas. It's often
482 convenient to use a block expression for each case, in which case the
483 commas are optional.
484
485 ~~~
486 # let my_number = 1;
487 match my_number {
488   0 => { println!("zero") }
489   _ => { println!("something else") }
490 }
491 ~~~
492
493 `match` constructs must be *exhaustive*: they must have an arm
494 covering every possible case. For example, the typechecker would
495 reject the previous example if the arm with the wildcard pattern was
496 omitted.
497
498 A powerful application of pattern matching is *destructuring*:
499 matching in order to bind names to the contents of data 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) => println!("{}", 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) => println!("{}", 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 leveraged 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 ~~~ {.notrust}
1059           List box             List box           List box            List box
1060         +--------------+    +--------------+    +--------------+    +--------------+
1061 list -> | Cons | 1 | ~ | -> | Cons | 2 | ~ | -> | Cons | 3 | ~ | -> | Nil          |
1062         +--------------+    +--------------+    +--------------+    +--------------+
1063 ~~~
1064
1065 > ***Note:*** the above diagram shows the logical contents of the enum. The actual
1066 > memory layout of the enum may vary. For example, for the `List` enum shown
1067 > above, Rust guarantees that there will be no enum tag field in the actual
1068 > structure. See the language reference for more details.
1069
1070 An owned box is a common example of a type with a destructor. The allocated
1071 memory is cleaned up when the box is destroyed.
1072
1073 ## Move semantics
1074
1075 Rust uses a shallow copy for parameter passing, assignment and returning from
1076 functions. Passing around the `List` will copy only as deep as the pointer to
1077 the box rather than doing an implicit heap allocation.
1078
1079 ~~~
1080 # enum List {
1081 #     Cons(u32, ~List),
1082 #     Nil
1083 # }
1084 let xs = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1085 let ys = xs; // copies `Cons(u32, pointer)` shallowly
1086 ~~~
1087
1088 Rust will consider a shallow copy of a type with a destructor like `List` to
1089 *move ownership* of the value. After a value has been moved, the source
1090 location cannot be used unless it is reinitialized.
1091
1092 ~~~
1093 # enum List {
1094 #     Cons(u32, ~List),
1095 #     Nil
1096 # }
1097 let mut xs = Nil;
1098 let ys = xs;
1099
1100 // attempting to use `xs` will result in an error here
1101
1102 xs = Nil;
1103
1104 // `xs` can be used again
1105 ~~~
1106
1107 A destructor call will only occur for a variable that has not been moved from,
1108 as it is only called a single time.
1109
1110
1111 Avoiding a move can be done with the library-defined `clone` method:
1112
1113 ~~~~
1114 let x = ~5;
1115 let y = x.clone(); // `y` is a newly allocated box
1116 let z = x; // no new memory allocated, `x` can no longer be used
1117 ~~~~
1118
1119 The `clone` method is provided by the `Clone` trait, and can be derived for
1120 our `List` type. Traits will be explained in detail [later](#traits).
1121
1122 ~~~{.ignore}
1123 #[deriving(Clone)]
1124 enum List {
1125     Cons(u32, ~List),
1126     Nil
1127 }
1128
1129 let x = Cons(5, ~Nil);
1130 let y = x.clone();
1131
1132 // `x` can still be used!
1133
1134 let z = x;
1135
1136 // and now, it can no longer be used since it has been moved
1137 ~~~
1138
1139 The mutability of a value may be changed by moving it to a new owner:
1140
1141 ~~~~
1142 let r = ~13;
1143 let mut s = r; // box becomes mutable
1144 *s += 1;
1145 let t = s; // box becomes immutable
1146 ~~~~
1147
1148 A simple way to define a function prepending to the `List` type is to take
1149 advantage of moves:
1150
1151 ~~~
1152 enum List {
1153     Cons(u32, ~List),
1154     Nil
1155 }
1156
1157 fn prepend(xs: List, value: u32) -> List {
1158     Cons(value, ~xs)
1159 }
1160
1161 let mut xs = Nil;
1162 xs = prepend(xs, 1);
1163 xs = prepend(xs, 2);
1164 xs = prepend(xs, 3);
1165 ~~~
1166
1167 However, this is not a very flexible definition of `prepend` as it requires
1168 ownership of a list to be passed in rather than just mutating it in-place.
1169
1170 ## References
1171
1172 The obvious signature for a `List` equality comparison is the following:
1173
1174 ~~~{.ignore}
1175 fn eq(xs: List, ys: List) -> bool { /* ... */ }
1176 ~~~
1177
1178 However, this will cause both lists to be moved into the function. Ownership
1179 isn't required to compare the lists, so the function should take *references*
1180 (&T) instead.
1181
1182 ~~~{.ignore}
1183 fn eq(xs: &List, ys: &List) -> bool { /* ... */ }
1184 ~~~
1185
1186 A reference is a *non-owning* view of a value. A reference can be obtained with the `&` (address-of)
1187 operator. It can be dereferenced by using the `*` operator. In a pattern, such as `match` expression
1188 branches, the `ref` keyword can be used to bind to a variable name by-reference rather than
1189 by-value. A recursive definition of equality using references is as follows:
1190
1191 ~~~
1192 # enum List {
1193 #     Cons(u32, ~List),
1194 #     Nil
1195 # }
1196 fn eq(xs: &List, ys: &List) -> bool {
1197     // Match on the next node in both lists.
1198     match (xs, ys) {
1199         // If we have reached the end of both lists, they are equal.
1200         (&Nil, &Nil) => true,
1201         // If the current element in both lists is equal, keep going.
1202         (&Cons(x, ~ref next_xs), &Cons(y, ~ref next_ys)) if x == y => eq(next_xs, next_ys),
1203         // If the current elements are not equal, the lists are not equal.
1204         _ => false
1205     }
1206 }
1207
1208 let xs = Cons(5, ~Cons(10, ~Nil));
1209 let ys = Cons(5, ~Cons(10, ~Nil));
1210 assert!(eq(&xs, &ys));
1211 ~~~
1212
1213 > ***Note:*** Rust doesn't guarantee [tail-call](http://en.wikipedia.org/wiki/Tail_call) optimization,
1214 > but LLVM is able to handle a simple case like this with optimizations enabled.
1215
1216 ## Lists of other types
1217
1218 Our `List` type is currently always a list of 32-bit unsigned integers. By
1219 leveraging Rust's support for generics, it can be extended to work for any
1220 element type.
1221
1222 The `u32` in the previous definition can be substituted with a type parameter:
1223
1224 > ***Note:*** The following code introduces generics, which are explained in a
1225 > [dedicated section](#generics).
1226
1227 ~~~
1228 enum List<T> {
1229     Cons(T, ~List<T>),
1230     Nil
1231 }
1232 ~~~
1233
1234 The old `List` of `u32` is now available as `List<u32>`. The `prepend`
1235 definition has to be updated too:
1236
1237 ~~~
1238 # enum List<T> {
1239 #     Cons(T, ~List<T>),
1240 #     Nil
1241 # }
1242 fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1243     Cons(value, ~xs)
1244 }
1245 ~~~
1246
1247 Generic functions and types like this are equivalent to defining specialized
1248 versions for each set of type parameters.
1249
1250 Using the generic `List<T>` works much like before, thanks to type inference:
1251
1252 ~~~
1253 # enum List<T> {
1254 #     Cons(T, ~List<T>),
1255 #     Nil
1256 # }
1257 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1258 #     Cons(value, ~xs)
1259 # }
1260 let mut xs = Nil; // Unknown type! This is a `List<T>`, but `T` can be anything.
1261 xs = prepend(xs, 10); // The compiler infers the type of `xs` as `List<int>` from this.
1262 xs = prepend(xs, 15);
1263 xs = prepend(xs, 20);
1264 ~~~
1265
1266 The code sample above demonstrates type inference making most type annotations optional. It is
1267 equivalent to the following type-annotated code:
1268
1269 ~~~
1270 # enum List<T> {
1271 #     Cons(T, ~List<T>),
1272 #     Nil
1273 # }
1274 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1275 #     Cons(value, ~xs)
1276 # }
1277 let mut xs: List<int> = Nil::<int>;
1278 xs = prepend::<int>(xs, 10);
1279 xs = prepend::<int>(xs, 15);
1280 xs = prepend::<int>(xs, 20);
1281 ~~~
1282
1283 In declarations, the language uses `Type<T, U, V>` to describe a list of type
1284 parameters, but expressions use `identifier::<T, U, V>`, to disambiguate the
1285 `<` operator.
1286
1287 ## Defining list equality with generics
1288
1289 Generic functions are type-checked from the definition, so any necessary properties of the type must
1290 be specified up-front. Our previous definition of list equality relied on the element type having
1291 the `==` operator available, and took advantage of the lack of a destructor on `u32` to copy it
1292 without a move of ownership.
1293
1294 We can add a *trait bound* on the `Eq` trait to require that the type implement the `==` operator.
1295 Two more `ref` annotations need to be added to avoid attempting to move out the element types:
1296
1297 ~~~
1298 # enum List<T> {
1299 #     Cons(T, ~List<T>),
1300 #     Nil
1301 # }
1302 fn eq<T: Eq>(xs: &List<T>, ys: &List<T>) -> bool {
1303     // Match on the next node in both lists.
1304     match (xs, ys) {
1305         // If we have reached the end of both lists, they are equal.
1306         (&Nil, &Nil) => true,
1307         // If the current element in both lists is equal, keep going.
1308         (&Cons(ref x, ~ref next_xs), &Cons(ref y, ~ref next_ys)) if x == y => eq(next_xs, next_ys),
1309         // If the current elements are not equal, the lists are not equal.
1310         _ => false
1311     }
1312 }
1313
1314 let xs = Cons('c', ~Cons('a', ~Cons('t', ~Nil)));
1315 let ys = Cons('c', ~Cons('a', ~Cons('t', ~Nil)));
1316 assert!(eq(&xs, &ys));
1317 ~~~
1318
1319 This would be a good opportunity to implement the `Eq` trait for our list type, making the `==` and
1320 `!=` operators available. We'll need to provide an `impl` for the `Eq` trait and a definition of the
1321 `eq` method. In a method, the `self` parameter refers to an instance of the type we're implementing
1322 on.
1323
1324 ~~~
1325 # enum List<T> {
1326 #     Cons(T, ~List<T>),
1327 #     Nil
1328 # }
1329 impl<T: Eq> Eq for List<T> {
1330     fn eq(&self, ys: &List<T>) -> bool {
1331         // Match on the next node in both lists.
1332         match (self, ys) {
1333             // If we have reached the end of both lists, they are equal.
1334             (&Nil, &Nil) => true,
1335             // If the current element in both lists is equal, keep going.
1336             (&Cons(ref x, ~ref next_xs), &Cons(ref y, ~ref next_ys)) if x == y => next_xs == next_ys,
1337             // If the current elements are not equal, the lists are not equal.
1338             _ => false
1339         }
1340     }
1341 }
1342
1343 let xs = Cons(5, ~Cons(10, ~Nil));
1344 let ys = Cons(5, ~Cons(10, ~Nil));
1345 // The methods below are part of the Eq trait,
1346 // which we implemented on our linked list.
1347 assert!(xs.eq(&ys));
1348 assert!(!xs.ne(&ys));
1349
1350 // The Eq trait also allows us to use the shorthand infix operators.
1351 assert!(xs == ys);    // `xs == ys` is short for `xs.eq(&ys)`
1352 assert!(!(xs != ys)); // `xs != ys` is short for `xs.ne(&ys)`
1353 ~~~
1354
1355 # More on boxes
1356
1357 The most common use case for owned boxes is creating recursive data structures
1358 like a binary search tree. Rust's trait-based generics system (covered later in
1359 the tutorial) is usually used for static dispatch, but also provides dynamic
1360 dispatch via boxing. Values of different types may have different sizes, but a
1361 box is able to *erase* the difference via the layer of indirection they
1362 provide.
1363
1364 In uncommon cases, the indirection can provide a performance gain or memory
1365 reduction by making values smaller. However, unboxed values should almost
1366 always be preferred when they are usable.
1367
1368 Note that returning large unboxed values via boxes is unnecessary. A large
1369 value is returned via a hidden output parameter, and the decision on where to
1370 place the return value should be left to the caller:
1371
1372 ~~~~
1373 fn foo() -> (u64, u64, u64, u64, u64, u64) {
1374     (5, 5, 5, 5, 5, 5)
1375 }
1376
1377 let x = ~foo(); // allocates a `~` box, and writes the integers directly to it
1378 ~~~~
1379
1380 Beyond the properties granted by the size, an owned box behaves as a regular
1381 value by inheriting the mutability and lifetime of the owner:
1382
1383 ~~~~
1384 let x = 5; // immutable
1385 let mut y = 5; // mutable
1386 y += 2;
1387
1388 let x = ~5; // immutable
1389 let mut y = ~5; // mutable
1390 *y += 2; // the `*` operator is needed to access the contained value
1391 ~~~~
1392
1393 # References
1394
1395 In contrast with
1396 owned boxes, where the holder of an owned box is the owner of the pointed-to
1397 memory, references never imply ownership - they are "borrowed".
1398 You can borrow a reference to
1399 any object, and the compiler verifies that it cannot outlive the lifetime of
1400 the object.
1401
1402 As an example, consider a simple struct type, `Point`:
1403
1404 ~~~
1405 struct Point {
1406     x: f64,
1407     y: f64
1408 }
1409 ~~~~
1410
1411 We can use this simple definition to allocate points in many different
1412 ways. For example, in this code, each of these three local variables
1413 contains a point, but allocated in a different location:
1414
1415 ~~~
1416 # struct Point { x: f64, y: f64 }
1417 let on_the_stack : Point  =  Point { x: 3.0, y: 4.0 };
1418 let managed_box  : @Point = @Point { x: 5.0, y: 1.0 };
1419 let owned_box    : ~Point = ~Point { x: 7.0, y: 9.0 };
1420 ~~~
1421
1422 Suppose we want to write a procedure that computes the distance
1423 between any two points, no matter where they are stored. For example,
1424 we might like to compute the distance between `on_the_stack` and
1425 `managed_box`, or between `managed_box` and `owned_box`. One option is
1426 to define a function that takes two arguments of type point—that is,
1427 it takes the points by value. But this will cause the points to be
1428 copied when we call the function. For points, this is probably not so
1429 bad, but often copies are expensive. So we’d like to define a function
1430 that takes the points by pointer. We can use references to do this:
1431
1432 ~~~
1433 use std::num::sqrt;
1434 # struct Point { x: f64, y: f64 }
1435 fn compute_distance(p1: &Point, p2: &Point) -> f64 {
1436     let x_d = p1.x - p2.x;
1437     let y_d = p1.y - p2.y;
1438     sqrt(x_d * x_d + y_d * y_d)
1439 }
1440 ~~~
1441
1442 Now we can call `compute_distance()` in various ways:
1443
1444 ~~~
1445 # struct Point{ x: f64, y: f64 };
1446 # let on_the_stack : Point  =  Point { x: 3.0, y: 4.0 };
1447 # let managed_box  : @Point = @Point { x: 5.0, y: 1.0 };
1448 # let owned_box    : ~Point = ~Point { x: 7.0, y: 9.0 };
1449 # fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
1450 compute_distance(&on_the_stack, managed_box);
1451 compute_distance(managed_box, owned_box);
1452 ~~~
1453
1454 Here the `&` operator is used to take the address of the variable
1455 `on_the_stack`; this is because `on_the_stack` has the type `Point`
1456 (that is, a struct value) and we have to take its address to get a
1457 reference. We also call this _borrowing_ the local variable
1458 `on_the_stack`, because we are creating an alias: that is, another
1459 route to the same data.
1460
1461 In the case of the boxes `managed_box` and `owned_box`, however, no
1462 explicit action is necessary. The compiler will automatically convert
1463 a box like `@point` or `~point` to a reference like
1464 `&point`. This is another form of borrowing; in this case, the
1465 contents of the managed/owned box are being lent out.
1466
1467 Whenever a value is borrowed, there are some limitations on what you
1468 can do with the original. For example, if the contents of a variable
1469 have been lent out, you cannot send that variable to another task, nor
1470 will you be permitted to take actions that might cause the borrowed
1471 value to be freed or to change its type. This rule should make
1472 intuitive sense: you must wait for a borrowed value to be returned
1473 (that is, for the reference to go out of scope) before you can
1474 make full use of it again.
1475
1476 For a more in-depth explanation of references and lifetimes, read the
1477 [references and lifetimes guide][lifetimes].
1478
1479 ## Freezing
1480
1481 Lending an &-pointer to an object freezes it and prevents mutation—even if the object was declared as `mut`.
1482 `Freeze` objects have freezing enforced statically at compile-time. An example
1483 of a non-`Freeze` type is [`RefCell<T>`][refcell].
1484
1485 ~~~~
1486 let mut x = 5;
1487 {
1488     let y = &x; // `x` is now frozen. It cannot be modified or re-assigned.
1489 }
1490 // `x` is now unfrozen again
1491 # x = 3;
1492 ~~~~
1493
1494 [refcell]: http://static.rust-lang.org/doc/master/std/cell/struct.RefCell.html
1495
1496 # Dereferencing pointers
1497
1498 Rust uses the unary star operator (`*`) to access the contents of a
1499 box or pointer, similarly to C.
1500
1501 ~~~
1502 let managed = @10;
1503 let owned = ~20;
1504 let borrowed = &30;
1505
1506 let sum = *managed + *owned + *borrowed;
1507 ~~~
1508
1509 Dereferenced mutable pointers may appear on the left hand side of
1510 assignments. Such an assignment modifies the value that the pointer
1511 points to.
1512
1513 ~~~
1514 let managed = @10;
1515 let mut owned = ~20;
1516
1517 let mut value = 30;
1518 let borrowed = &mut value;
1519
1520 *owned = *borrowed + 100;
1521 *borrowed = *managed + 1000;
1522 ~~~
1523
1524 Pointers have high operator precedence, but lower precedence than the
1525 dot operator used for field and method access. This precedence order
1526 can sometimes make code awkward and parenthesis-filled.
1527
1528 ~~~
1529 # struct Point { x: f64, y: f64 }
1530 # enum Shape { Rectangle(Point, Point) }
1531 # impl Shape { fn area(&self) -> int { 0 } }
1532 let start = @Point { x: 10.0, y: 20.0 };
1533 let end = ~Point { x: (*start).x + 100.0, y: (*start).y + 100.0 };
1534 let rect = &Rectangle(*start, *end);
1535 let area = (*rect).area();
1536 ~~~
1537
1538 To combat this ugliness the dot operator applies _automatic pointer
1539 dereferencing_ to the receiver (the value on the left-hand side of the
1540 dot), so in most cases, explicitly dereferencing the receiver is not necessary.
1541
1542 ~~~
1543 # struct Point { x: f64, y: f64 }
1544 # enum Shape { Rectangle(Point, Point) }
1545 # impl Shape { fn area(&self) -> int { 0 } }
1546 let start = @Point { x: 10.0, y: 20.0 };
1547 let end = ~Point { x: start.x + 100.0, y: start.y + 100.0 };
1548 let rect = &Rectangle(*start, *end);
1549 let area = rect.area();
1550 ~~~
1551
1552 You can write an expression that dereferences any number of pointers
1553 automatically. For example, if you feel inclined, you could write
1554 something silly like
1555
1556 ~~~
1557 # struct Point { x: f64, y: f64 }
1558 let point = &@~Point { x: 10.0, y: 20.0 };
1559 println!("{:f}", point.x);
1560 ~~~
1561
1562 The indexing operator (`[]`) also auto-dereferences.
1563
1564 # Vectors and strings
1565
1566 A vector is a contiguous block of memory containing zero or more values of the
1567 same type. Rust also supports vector reference types, called slices, which are
1568 a view into a block of memory represented as a pointer and a length.
1569
1570 Strings are represented as vectors of `u8`, with the guarantee of containing a
1571 valid UTF-8 sequence.
1572
1573 Fixed-size vectors are an unboxed block of memory, with the element length as
1574 part of the type. A fixed-size vector owns the elements it contains, so the
1575 elements are mutable if the vector is mutable. Fixed-size strings do not exist.
1576
1577 ~~~
1578 // A fixed-size vector
1579 let numbers = [1, 2, 3];
1580 let more_numbers = numbers;
1581
1582 // The type of a fixed-size vector is written as `[Type, ..length]`
1583 let five_zeroes: [int, ..5] = [0, ..5];
1584 ~~~
1585
1586 A unique vector is dynamically sized, and has a destructor to clean up
1587 allocated memory on the heap. A unique vector owns the elements it contains, so
1588 the elements are mutable if the vector is mutable.
1589
1590 ~~~
1591 // A dynamically sized vector (unique vector)
1592 let mut numbers = ~[1, 2, 3];
1593 numbers.push(4);
1594 numbers.push(5);
1595
1596 // The type of a unique vector is written as `~[int]`
1597 let more_numbers: ~[int] = numbers;
1598
1599 // The original `numbers` value can no longer be used, due to move semantics.
1600
1601 let mut string = ~"fo";
1602 string.push_char('o');
1603 ~~~
1604
1605 Slices are similar to fixed-size vectors, but the length is not part of the
1606 type. They simply point into a block of memory and do not have ownership over
1607 the elements.
1608
1609 ~~~
1610 // A slice
1611 let xs = &[1, 2, 3];
1612
1613 // Slices have their type written as `&[int]`
1614 let ys: &[int] = xs;
1615
1616 // Other vector types coerce to slices
1617 let three = [1, 2, 3];
1618 let zs: &[int] = three;
1619
1620 // An unadorned string literal is an immutable string slice
1621 let string = "foobar";
1622
1623 // A string slice type is written as `&str`
1624 let view: &str = string.slice(0, 3);
1625 ~~~
1626
1627 Mutable slices also exist, just as there are mutable references. However, there
1628 are no mutable string slices. Strings are a multi-byte encoding (UTF-8) of
1629 Unicode code points, so they cannot be freely mutated without the ability to
1630 alter the length.
1631
1632 ~~~
1633 let mut xs = [1, 2, 3];
1634 let view = xs.mut_slice(0, 2);
1635 view[0] = 5;
1636
1637 // The type of a mutable slice is written as `&mut [T]`
1638 let ys: &mut [int] = &mut [1, 2, 3];
1639 ~~~
1640
1641 Square brackets denote indexing into a vector:
1642
1643 ~~~~
1644 # enum Crayon { Almond, AntiqueBrass, Apricot,
1645 #               Aquamarine, Asparagus, AtomicTangerine,
1646 #               BananaMania, Beaver, Bittersweet };
1647 # fn draw_scene(c: Crayon) { }
1648 let crayons: [Crayon, ..3] = [BananaMania, Beaver, Bittersweet];
1649 match crayons[0] {
1650     Bittersweet => draw_scene(crayons[0]),
1651     _ => ()
1652 }
1653 ~~~~
1654
1655 A vector can be destructured using pattern matching:
1656
1657 ~~~~
1658 let numbers: &[int] = &[1, 2, 3];
1659 let score = match numbers {
1660     [] => 0,
1661     [a] => a * 10,
1662     [a, b] => a * 6 + b * 4,
1663     [a, b, c, ..rest] => a * 5 + b * 3 + c * 2 + rest.len() as int
1664 };
1665 ~~~~
1666
1667 Both vectors and strings support a number of useful [methods](#methods),
1668 defined in [`std::vec`] and [`std::str`].
1669
1670 [`std::vec`]: std/vec/index.html
1671 [`std::str`]: std/str/index.html
1672
1673 # Ownership escape hatches
1674
1675 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
1676 single parent ownership.
1677
1678 The standard library provides the `std::rc::Rc` pointer type to express *shared ownership* over a
1679 reference counted box. As soon as all of the `Rc` pointers go out of scope, the box and the
1680 contained value are destroyed.
1681
1682 ~~~
1683 use std::rc::Rc;
1684
1685 // A fixed-size array allocated in a reference-counted box
1686 let x = Rc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1687 let y = x.clone(); // a new owner
1688 let z = x; // this moves `x` into `z`, rather than creating a new owner
1689
1690 assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1691
1692 // the variable is mutable, but not the contents of the box
1693 let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
1694 a = z;
1695 ~~~
1696
1697 A garbage collected pointer is provided via `std::gc::Gc`, with a task-local garbage collector
1698 having ownership of the box. It allows the creation of cycles, and the individual `Gc` pointers do
1699 not have a destructor.
1700
1701 ~~~
1702 use std::gc::Gc;
1703
1704 // A fixed-size array allocated in a garbage-collected box
1705 let x = Gc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1706 let y = x; // does not perform a move, unlike with `Rc`
1707 let z = x;
1708
1709 assert!(*z.borrow() == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1710 ~~~
1711
1712 With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
1713 it's possible to use *dynamic* mutability via types like `std::cell::Cell` where freezing is handled
1714 via dynamic checks and can fail at runtime.
1715
1716 The `Rc` and `Gc` types are not sendable, so they cannot be used to share memory between tasks. Safe
1717 immutable and mutable shared memory is provided by the `extra::arc` module.
1718
1719 # Closures
1720
1721 Named functions, like those we've seen so far, may not refer to local
1722 variables declared outside the function: they do not close over their
1723 environment (sometimes referred to as "capturing" variables in their
1724 environment). For example, you couldn't write the following:
1725
1726 ~~~~ {.ignore}
1727 let foo = 10;
1728
1729 fn bar() -> int {
1730    return foo; // `bar` cannot refer to `foo`
1731 }
1732 ~~~~
1733
1734 Rust also supports _closures_, functions that can access variables in
1735 the enclosing scope.
1736
1737 ~~~~
1738 fn call_closure_with_ten(b: |int|) { b(10); }
1739
1740 let captured_var = 20;
1741 let closure = |arg| println!("captured_var={}, arg={}", captured_var, arg);
1742
1743 call_closure_with_ten(closure);
1744 ~~~~
1745
1746 Closures begin with the argument list between vertical bars and are followed by
1747 a single expression. Remember that a block, `{ <expr1>; <expr2>; ... }`, is
1748 considered a single expression: it evaluates to the result of the last
1749 expression it contains if that expression is not followed by a semicolon,
1750 otherwise the block evaluates to `()`.
1751
1752 The types of the arguments are generally omitted, as is the return type,
1753 because the compiler can almost always infer them. In the rare case where the
1754 compiler needs assistance, though, the arguments and return types may be
1755 annotated.
1756
1757 ~~~~
1758 let square = |x: int| -> uint { (x * x) as uint };
1759 ~~~~
1760
1761 There are several forms of closure, each with its own role. The most
1762 common, called a _stack closure_, has type `||` and can directly
1763 access local variables in the enclosing scope.
1764
1765 ~~~~
1766 let mut max = 0;
1767 [1, 2, 3].map(|x| if *x > max { max = *x });
1768 ~~~~
1769
1770 Stack closures are very efficient because their environment is
1771 allocated on the call stack and refers by pointer to captured
1772 locals. To ensure that stack closures never outlive the local
1773 variables to which they refer, stack closures are not
1774 first-class. That is, they can only be used in argument position; they
1775 cannot be stored in data structures or returned from
1776 functions. Despite these limitations, stack closures are used
1777 pervasively in Rust code.
1778
1779 ## Owned closures
1780
1781 Owned closures, written `proc`,
1782 hold on to things that can safely be sent between
1783 processes. They copy the values they close over, much like managed
1784 closures, but they also own them: that is, no other code can access
1785 them. Owned closures are used in concurrent code, particularly
1786 for spawning [tasks][tasks].
1787
1788 Closures can be used to spawn tasks.
1789 A practical example of this pattern is found when using the `spawn` function,
1790 which starts a new task.
1791
1792 ~~~~
1793 use std::task::spawn;
1794
1795 // proc is the closure which will be spawned.
1796 spawn(proc() {
1797     println!("I'm a new task")
1798 });
1799 ~~~~
1800
1801 > ***Note:*** If you want to see the output of `debug!` statements, you will need to turn on
1802 > `debug!` logging.  To enable `debug!` logging, set the RUST_LOG environment
1803 > variable to the name of your crate, which, for a file named `foo.rs`, will be
1804 > `foo` (e.g., with bash, `export RUST_LOG=foo`).
1805
1806 ## Closure compatibility
1807
1808 Rust closures have a convenient subtyping property: you can pass any kind of
1809 closure (as long as the arguments and return types match) to functions
1810 that expect a `||`. Thus, when writing a higher-order function that
1811 only calls its function argument, and does nothing else with it, you
1812 should almost always declare the type of that argument as `||`. That way,
1813 callers may pass any kind of closure.
1814
1815 ~~~~
1816 fn call_twice(f: ||) { f(); f(); }
1817 let closure = || { "I'm a closure, and it doesn't matter what type I am"; };
1818 fn function() { "I'm a normal function"; }
1819 call_twice(closure);
1820 call_twice(function);
1821 ~~~~
1822
1823 > ***Note:*** Both the syntax and the semantics will be changing
1824 > in small ways. At the moment they can be unsound in some
1825 > scenarios, particularly with non-copyable types.
1826
1827 # Methods
1828
1829 Methods are like functions except that they always begin with a special argument,
1830 called `self`,
1831 which has the type of the method's receiver. The
1832 `self` argument is like `this` in C++ and many other languages.
1833 Methods are called with dot notation, as in `my_vec.len()`.
1834
1835 _Implementations_, written with the `impl` keyword, can define
1836 methods on most Rust types, including structs and enums.
1837 As an example, let's define a `draw` method on our `Shape` enum.
1838
1839 ~~~
1840 # fn draw_circle(p: Point, f: f64) { }
1841 # fn draw_rectangle(p: Point, p: Point) { }
1842 struct Point {
1843     x: f64,
1844     y: f64
1845 }
1846
1847 enum Shape {
1848     Circle(Point, f64),
1849     Rectangle(Point, Point)
1850 }
1851
1852 impl Shape {
1853     fn draw(&self) {
1854         match *self {
1855             Circle(p, f) => draw_circle(p, f),
1856             Rectangle(p1, p2) => draw_rectangle(p1, p2)
1857         }
1858     }
1859 }
1860
1861 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1862 s.draw();
1863 ~~~
1864
1865 This defines an _implementation_ for `Shape` containing a single
1866 method, `draw`. In most respects the `draw` method is defined
1867 like any other function, except for the name `self`.
1868
1869 The type of `self` is the type on which the method is implemented,
1870 or a pointer thereof. As an argument it is written either `self`,
1871 `&self`, or `~self`.
1872 A caller must in turn have a compatible pointer type to call the method.
1873
1874 ~~~
1875 # fn draw_circle(p: Point, f: f64) { }
1876 # fn draw_rectangle(p: Point, p: Point) { }
1877 # struct Point { x: f64, y: f64 }
1878 # enum Shape {
1879 #     Circle(Point, f64),
1880 #     Rectangle(Point, Point)
1881 # }
1882 impl Shape {
1883     fn draw_reference(&self) { /* ... */ }
1884     fn draw_owned(~self) { /* ... */ }
1885     fn draw_value(self) { /* ... */ }
1886 }
1887
1888 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1889
1890 (~s).draw_owned();
1891 (&s).draw_reference();
1892 s.draw_value();
1893 ~~~
1894
1895 Methods typically take a reference self type,
1896 so the compiler will go to great lengths to convert a callee
1897 to a reference.
1898
1899 ~~~
1900 # fn draw_circle(p: Point, f: f64) { }
1901 # fn draw_rectangle(p: Point, p: Point) { }
1902 # struct Point { x: f64, y: f64 }
1903 # enum Shape {
1904 #     Circle(Point, f64),
1905 #     Rectangle(Point, Point)
1906 # }
1907 # impl Shape {
1908 #    fn draw_reference(&self) { /* ... */ }
1909 #    fn draw_owned(~self) { /* ... */ }
1910 #    fn draw_value(self) { /* ... */ }
1911 # }
1912 # let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1913 // As with typical function arguments, managed and owned pointers
1914 // are automatically converted to references
1915
1916 (@s).draw_reference();
1917 (~s).draw_reference();
1918
1919 // Unlike typical function arguments, the self value will
1920 // automatically be referenced ...
1921 s.draw_reference();
1922
1923 // ... and dereferenced
1924 (& &s).draw_reference();
1925
1926 // ... and dereferenced and borrowed
1927 (&@~s).draw_reference();
1928 ~~~
1929
1930 Implementations may also define standalone (sometimes called "static")
1931 methods. The absence of a `self` parameter distinguishes such methods.
1932 These methods are the preferred way to define constructor functions.
1933
1934 ~~~~ {.ignore}
1935 impl Circle {
1936     fn area(&self) -> f64 { /* ... */ }
1937     fn new(area: f64) -> Circle { /* ... */ }
1938 }
1939 ~~~~
1940
1941 To call such a method, just prefix it with the type name and a double colon:
1942
1943 ~~~~
1944 use std::f64::consts::PI;
1945 struct Circle { radius: f64 }
1946 impl Circle {
1947     fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
1948 }
1949 let c = Circle::new(42.5);
1950 ~~~~
1951
1952 # Generics
1953
1954 Throughout this tutorial, we've been defining functions that act only
1955 on specific data types. With type parameters we can also define
1956 functions whose arguments have generic types, and which can be invoked
1957 with a variety of types. Consider a generic `map` function, which
1958 takes a function `function` and a vector `vector` and returns a new
1959 vector consisting of the result of applying `function` to each element
1960 of `vector`:
1961
1962 ~~~~
1963 fn map<T, U>(vector: &[T], function: |v: &T| -> U) -> ~[U] {
1964     let mut accumulator = ~[];
1965     for element in vector.iter() {
1966         accumulator.push(function(element));
1967     }
1968     return accumulator;
1969 }
1970 ~~~~
1971
1972 When defined with type parameters, as denoted by `<T, U>`, this
1973 function can be applied to any type of vector, as long as the type of
1974 `function`'s argument and the type of the vector's contents agree with
1975 each other.
1976
1977 Inside a generic function, the names of the type parameters
1978 (capitalized by convention) stand for opaque types. All you can do
1979 with instances of these types is pass them around: you can't apply any
1980 operations to them or pattern-match on them. Note that instances of
1981 generic types are often passed by pointer. For example, the parameter
1982 `function()` is supplied with a pointer to a value of type `T` and not
1983 a value of type `T` itself. This ensures that the function works with
1984 the broadest set of types possible, since some types are expensive or
1985 illegal to copy and pass by value.
1986
1987 Generic `type`, `struct`, and `enum` declarations follow the same pattern:
1988
1989 ~~~~
1990 extern crate collections;
1991 type Set<T> = collections::HashMap<T, ()>;
1992
1993 struct Stack<T> {
1994     elements: ~[T]
1995 }
1996
1997 enum Option<T> {
1998     Some(T),
1999     None
2000 }
2001 # fn main() {}
2002 ~~~~
2003
2004 These declarations can be instantiated to valid types like `Set<int>`,
2005 `Stack<int>`, and `Option<int>`.
2006
2007 The last type in that example, `Option`, appears frequently in Rust code.
2008 Because Rust does not have null pointers (except in unsafe code), we need
2009 another way to write a function whose result isn't defined on every possible
2010 combination of arguments of the appropriate types. The usual way is to write
2011 a function that returns `Option<T>` instead of `T`.
2012
2013 ~~~~
2014 # struct Point { x: f64, y: f64 }
2015 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
2016 fn radius(shape: Shape) -> Option<f64> {
2017     match shape {
2018         Circle(_, radius) => Some(radius),
2019         Rectangle(..)      => None
2020     }
2021 }
2022 ~~~~
2023
2024 The Rust compiler compiles generic functions very efficiently by
2025 *monomorphizing* them. *Monomorphization* is a fancy name for a simple
2026 idea: generate a separate copy of each generic function at each call site,
2027 a copy that is specialized to the argument
2028 types and can thus be optimized specifically for them. In this
2029 respect, Rust's generics have similar performance characteristics to
2030 C++ templates.
2031
2032 ## Traits
2033
2034 Within a generic function—that is, a function parameterized by a
2035 type parameter, say, `T`—the operations we can do on arguments of
2036 type `T` are quite limited.  After all, since we don't know what type
2037 `T` will be instantiated with, we can't safely modify or query values
2038 of type `T`.  This is where _traits_ come into play. Traits are Rust's
2039 most powerful tool for writing polymorphic code. Java developers will
2040 see them as similar to Java interfaces, and Haskellers will notice
2041 their similarities to type classes. Rust's traits give us a way to
2042 express *bounded polymorphism*: by limiting the set of possible types
2043 that a type parameter could refer to, they expand the number of
2044 operations we can safely perform on arguments of that type.
2045
2046 As motivation, let us consider copying of values in Rust.  The `clone`
2047 method is not defined for values of every type.  One reason is
2048 user-defined destructors: copying a value of a type that has a
2049 destructor could result in the destructor running multiple times.
2050 Therefore, values of types that have destructors cannot be copied
2051 unless we explicitly implement `clone` for them.
2052
2053 This complicates handling of generic functions.
2054 If we have a function with a type parameter `T`,
2055 can we copy values of type `T` inside that function?
2056 In Rust, we can't,
2057 and if we try to run the following code the compiler will complain.
2058
2059 ~~~~ {.ignore}
2060 // This does not compile
2061 fn head_bad<T>(v: &[T]) -> T {
2062     v[0] // error: copying a non-copyable value
2063 }
2064 ~~~~
2065
2066 However, we can tell the compiler
2067 that the `head` function is only for copyable types.
2068 In Rust, copyable types are those that _implement the `Clone` trait_.
2069 We can then explicitly create a second copy of the value we are returning
2070 by calling the `clone` method:
2071
2072 ~~~~
2073 // This does
2074 fn head<T: Clone>(v: &[T]) -> T {
2075     v[0].clone()
2076 }
2077 ~~~~
2078
2079 The bounded type parameter `T: Clone` says that `head`
2080 can be called on an argument of type `&[T]` for any `T`,
2081 so long as there is an implementation of the
2082 `Clone` trait for `T`.
2083 When instantiating a generic function,
2084 we can only instantiate it with types
2085 that implement the correct trait,
2086 so we could not apply `head` to a vector whose elements are of some type
2087 that does not implement `Clone`.
2088
2089 While most traits can be defined and implemented by user code,
2090 three traits are automatically derived and implemented
2091 for all applicable types by the compiler,
2092 and may not be overridden:
2093
2094 * `Send` - Sendable types.
2095 Types are sendable
2096 unless they contain managed boxes, managed closures, or references.
2097
2098 * `Share` - Types that are *threadsafe*
2099 These are types that are safe to be used across several threads with access to
2100 a `&T` pointer. `MutexArc` is an example of a *sharable* type with internal mutable data.
2101
2102 * `'static` - Non-borrowed types.
2103 These are types that do not contain any data whose lifetime is bound to
2104 a particular stack frame. These are types that do not contain any
2105 references, or types where the only contained references
2106 have the `'static` lifetime.
2107
2108 > ***Note:*** These two traits were referred to as 'kinds' in earlier
2109 > iterations of the language, and often still are.
2110
2111 Additionally, the `Drop` trait is used to define destructors. This
2112 trait provides one method called `drop`, which is automatically
2113 called when a value of the type that implements this trait is
2114 destroyed, either because the value went out of scope or because the
2115 garbage collector reclaimed it.
2116
2117 ~~~
2118 struct TimeBomb {
2119     explosivity: uint
2120 }
2121
2122 impl Drop for TimeBomb {
2123     fn drop(&mut self) {
2124         for _ in range(0, self.explosivity) {
2125             println!("blam!");
2126         }
2127     }
2128 }
2129 ~~~
2130
2131 It is illegal to call `drop` directly. Only code inserted by the compiler
2132 may call it.
2133
2134 ## Declaring and implementing traits
2135
2136 At its simplest, a trait is a set of zero or more _method signatures_.
2137 For example, we could declare the trait
2138 `Printable` for things that can be printed to the console,
2139 with a single method signature:
2140
2141 ~~~~
2142 trait Printable {
2143     fn print(&self);
2144 }
2145 ~~~~
2146
2147 We say that the `Printable` trait _provides_ a `print` method with the
2148 given signature.  This means that we can call `print` on an argument
2149 of any type that implements the `Printable` trait.
2150
2151 Rust's built-in `Send` and `Share` types are examples of traits that
2152 don't provide any methods.
2153
2154 Traits may be implemented for specific types with [impls]. An impl for
2155 a particular trait gives an implementation of the methods that
2156 trait provides.  For instance, the following impls of
2157 `Printable` for `int` and `~str` give implementations of the `print`
2158 method.
2159
2160 [impls]: #methods
2161
2162 ~~~~
2163 # trait Printable { fn print(&self); }
2164 impl Printable for int {
2165     fn print(&self) { println!("{:?}", *self) }
2166 }
2167
2168 impl Printable for ~str {
2169     fn print(&self) { println!("{}", *self) }
2170 }
2171
2172 # 1.print();
2173 # (~"foo").print();
2174 ~~~~
2175
2176 Methods defined in an impl for a trait may be called just like
2177 any other method, using dot notation, as in `1.print()`.
2178
2179 ## Default method implementations in trait definitions
2180
2181 Sometimes, a method that a trait provides will have the same
2182 implementation for most or all of the types that implement that trait.
2183 For instance, suppose that we wanted `bool`s and `f32`s to be
2184 printable, and that we wanted the implementation of `print` for those
2185 types to be exactly as it is for `int`, above:
2186
2187 ~~~~
2188 # trait Printable { fn print(&self); }
2189 impl Printable for f32 {
2190     fn print(&self) { println!("{:?}", *self) }
2191 }
2192
2193 impl Printable for bool {
2194     fn print(&self) { println!("{:?}", *self) }
2195 }
2196
2197 # true.print();
2198 # 3.14159.print();
2199 ~~~~
2200
2201 This works fine, but we've now repeated the same definition of `print`
2202 in three places.  Instead of doing that, we can simply include the
2203 definition of `print` right in the trait definition, instead of just
2204 giving its signature.  That is, we can write the following:
2205
2206 ~~~~
2207 trait Printable {
2208         // Default method implementation
2209     fn print(&self) { println!("{:?}", *self) }
2210 }
2211
2212 impl Printable for int {}
2213
2214 impl Printable for ~str {
2215     fn print(&self) { println!("{}", *self) }
2216 }
2217
2218 impl Printable for bool {}
2219
2220 impl Printable for f32 {}
2221
2222 # 1.print();
2223 # (~"foo").print();
2224 # true.print();
2225 # 3.14159.print();
2226 ~~~~
2227
2228 Here, the impls of `Printable` for `int`, `bool`, and `f32` don't
2229 need to provide an implementation of `print`, because in the absence
2230 of a specific implementation, Rust just uses the _default method_
2231 provided in the trait definition.  Depending on the trait, default
2232 methods can save a great deal of boilerplate code from having to be
2233 written in impls.  Of course, individual impls can still override the
2234 default method for `print`, as is being done above in the impl for
2235 `~str`.
2236
2237 ## Type-parameterized traits
2238
2239 Traits may be parameterized by type variables.  For example, a trait
2240 for generalized sequence types might look like the following:
2241
2242 ~~~~
2243 trait Seq<T> {
2244     fn length(&self) -> uint;
2245 }
2246
2247 impl<T> Seq<T> for ~[T] {
2248     fn length(&self) -> uint { self.len() }
2249 }
2250 ~~~~
2251
2252 The implementation has to explicitly declare the type parameter that
2253 it binds, `T`, before using it to specify its trait type. Rust
2254 requires this declaration because the `impl` could also, for example,
2255 specify an implementation of `Seq<int>`. The trait type (appearing
2256 between `impl` and `for`) *refers* to a type, rather than
2257 defining one.
2258
2259 The type parameters bound by a trait are in scope in each of the
2260 method declarations. So, re-declaring the type parameter
2261 `T` as an explicit type parameter for `len`, in either the trait or
2262 the impl, would be a compile-time error.
2263
2264 Within a trait definition, `Self` is a special type that you can think
2265 of as a type parameter. An implementation of the trait for any given
2266 type `T` replaces the `Self` type parameter with `T`. The following
2267 trait describes types that support an equality operation:
2268
2269 ~~~~
2270 // In a trait, `self` refers to the self argument.
2271 // `Self` refers to the type implementing the trait.
2272 trait Eq {
2273     fn equals(&self, other: &Self) -> bool;
2274 }
2275
2276 // In an impl, `self` refers just to the value of the receiver
2277 impl Eq for int {
2278     fn equals(&self, other: &int) -> bool { *other == *self }
2279 }
2280 ~~~~
2281
2282 Notice that in the trait definition, `equals` takes a
2283 second parameter of type `Self`.
2284 In contrast, in the `impl`, `equals` takes a second parameter of
2285 type `int`, only using `self` as the name of the receiver.
2286
2287 Just as in type implementations, traits can define standalone (static)
2288 methods.  These methods are called by prefixing the method name with the trait
2289 name and a double colon.  The compiler uses type inference to decide which
2290 implementation to use.
2291
2292 ~~~~
2293 use std::f64::consts::PI;
2294 trait Shape { fn new(area: f64) -> Self; }
2295 struct Circle { radius: f64 }
2296 struct Square { length: f64 }
2297
2298 impl Shape for Circle {
2299     fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
2300 }
2301 impl Shape for Square {
2302     fn new(area: f64) -> Square { Square { length: (area).sqrt() } }
2303 }
2304
2305 let area = 42.5;
2306 let c: Circle = Shape::new(area);
2307 let s: Square = Shape::new(area);
2308 ~~~~
2309
2310 ## Bounded type parameters and static method dispatch
2311
2312 Traits give us a language for defining predicates on types, or
2313 abstract properties that types can have. We can use this language to
2314 define _bounds_ on type parameters, so that we can then operate on
2315 generic types.
2316
2317 ~~~~
2318 # trait Printable { fn print(&self); }
2319 fn print_all<T: Printable>(printable_things: ~[T]) {
2320     for thing in printable_things.iter() {
2321         thing.print();
2322     }
2323 }
2324 ~~~~
2325
2326 Declaring `T` as conforming to the `Printable` trait (as we earlier
2327 did with `Clone`) makes it possible to call methods from that trait
2328 on values of type `T` inside the function. It will also cause a
2329 compile-time error when anyone tries to call `print_all` on an array
2330 whose element type does not have a `Printable` implementation.
2331
2332 Type parameters can have multiple bounds by separating them with `+`,
2333 as in this version of `print_all` that copies elements.
2334
2335 ~~~
2336 # trait Printable { fn print(&self); }
2337 fn print_all<T: Printable + Clone>(printable_things: ~[T]) {
2338     let mut i = 0;
2339     while i < printable_things.len() {
2340         let copy_of_thing = printable_things[i].clone();
2341         copy_of_thing.print();
2342         i += 1;
2343     }
2344 }
2345 ~~~
2346
2347 Method calls to bounded type parameters are _statically dispatched_,
2348 imposing no more overhead than normal function invocation, so are
2349 the preferred way to use traits polymorphically.
2350
2351 This usage of traits is similar to Haskell type classes.
2352
2353 ## Trait objects and dynamic method dispatch
2354
2355 The above allows us to define functions that polymorphically act on
2356 values of a single unknown type that conforms to a given trait.
2357 However, consider this function:
2358
2359 ~~~~
2360 # type Circle = int; type Rectangle = int;
2361 # impl Drawable for int { fn draw(&self) {} }
2362 # fn new_circle() -> int { 1 }
2363 trait Drawable { fn draw(&self); }
2364
2365 fn draw_all<T: Drawable>(shapes: ~[T]) {
2366     for shape in shapes.iter() { shape.draw(); }
2367 }
2368 # let c: Circle = new_circle();
2369 # draw_all(~[c]);
2370 ~~~~
2371
2372 You can call that on an array of circles, or an array of rectangles
2373 (assuming those have suitable `Drawable` traits defined), but not on
2374 an array containing both circles and rectangles. When such behavior is
2375 needed, a trait name can alternately be used as a type, called
2376 an _object_.
2377
2378 ~~~~
2379 # trait Drawable { fn draw(&self); }
2380 fn draw_all(shapes: &[~Drawable]) {
2381     for shape in shapes.iter() { shape.draw(); }
2382 }
2383 ~~~~
2384
2385 In this example, there is no type parameter. Instead, the `~Drawable`
2386 type denotes any owned box value that implements the `Drawable` trait.
2387 To construct such a value, you use the `as` operator to cast a value
2388 to an object:
2389
2390 ~~~~
2391 # type Circle = int; type Rectangle = bool;
2392 # trait Drawable { fn draw(&self); }
2393 # fn new_circle() -> Circle { 1 }
2394 # fn new_rectangle() -> Rectangle { true }
2395 # fn draw_all(shapes: &[~Drawable]) {}
2396
2397 impl Drawable for Circle { fn draw(&self) { /* ... */ } }
2398 impl Drawable for Rectangle { fn draw(&self) { /* ... */ } }
2399
2400 let c: ~Circle = ~new_circle();
2401 let r: ~Rectangle = ~new_rectangle();
2402 draw_all([c as ~Drawable, r as ~Drawable]);
2403 ~~~~
2404
2405 We omit the code for `new_circle` and `new_rectangle`; imagine that
2406 these just return `Circle`s and `Rectangle`s with a default size. Note
2407 that, like strings and vectors, objects have dynamic size and may
2408 only be referred to via one of the pointer types.
2409 Other pointer types work as well.
2410 Casts to traits may only be done with compatible pointers so,
2411 for example, an `@Circle` may not be cast to an `~Drawable`.
2412
2413 ~~~
2414 # type Circle = int; type Rectangle = int;
2415 # trait Drawable { fn draw(&self); }
2416 # impl Drawable for int { fn draw(&self) {} }
2417 # fn new_circle() -> int { 1 }
2418 # fn new_rectangle() -> int { 2 }
2419 // An owned object
2420 let owny: ~Drawable = ~new_circle() as ~Drawable;
2421 // A borrowed object
2422 let stacky: &Drawable = &new_circle() as &Drawable;
2423 ~~~
2424
2425 Method calls to trait types are _dynamically dispatched_. Since the
2426 compiler doesn't know specifically which functions to call at compile
2427 time, it uses a lookup table (also known as a vtable or dictionary) to
2428 select the method to call at runtime.
2429
2430 This usage of traits is similar to Java interfaces.
2431
2432 By default, each of the three storage classes for traits enforce a
2433 particular set of built-in kinds that their contents must fulfill in
2434 order to be packaged up in a trait object of that storage class.
2435
2436 * The contents of owned traits (`~Trait`) must fulfill the `Send` bound.
2437 * The contents of reference traits (`&Trait`) are not constrained by any bound.
2438
2439 Consequently, the trait objects themselves automatically fulfill their
2440 respective kind bounds. However, this default behavior can be overridden by
2441 specifying a list of bounds on the trait type, for example, by writing `~Trait:`
2442 (which indicates that the contents of the owned trait need not fulfill any
2443 bounds), or by writing `~Trait:Send+Share`, which indicates that in addition
2444 to fulfilling `Send`, contents must also fulfill `Share`, and as a consequence,
2445 the trait itself fulfills `Share`.
2446
2447 * `~Trait:Send` is equivalent to `~Trait`.
2448 * `&Trait:` is equivalent to `&Trait`.
2449
2450 Builtin kind bounds can also be specified on closure types in the same way (for
2451 example, by writing `fn:Send()`), and the default behaviours are the same as
2452 for traits of the same storage class.
2453
2454 ## Trait inheritance
2455
2456 We can write a trait declaration that _inherits_ from other traits, called _supertraits_.
2457 Types that implement a trait must also implement its supertraits.
2458 For example,
2459 we can define a `Circle` trait that inherits from `Shape`.
2460
2461 ~~~~
2462 trait Shape { fn area(&self) -> f64; }
2463 trait Circle : Shape { fn radius(&self) -> f64; }
2464 ~~~~
2465
2466 Now, we can implement `Circle` on a type only if we also implement `Shape`.
2467
2468 ~~~~
2469 use std::f64::consts::PI;
2470 # trait Shape { fn area(&self) -> f64; }
2471 # trait Circle : Shape { fn radius(&self) -> f64; }
2472 # struct Point { x: f64, y: f64 }
2473 # fn square(x: f64) -> f64 { x * x }
2474 struct CircleStruct { center: Point, radius: f64 }
2475 impl Circle for CircleStruct {
2476     fn radius(&self) -> f64 { (self.area() / PI).sqrt() }
2477 }
2478 impl Shape for CircleStruct {
2479     fn area(&self) -> f64 { PI * square(self.radius) }
2480 }
2481 ~~~~
2482
2483 Notice that methods of `Circle` can call methods on `Shape`, as our
2484 `radius` implementation calls the `area` method.
2485 This is a silly way to compute the radius of a circle
2486 (since we could just return the `radius` field), but you get the idea.
2487
2488 In type-parameterized functions,
2489 methods of the supertrait may be called on values of subtrait-bound type parameters.
2490 Refering to the previous example of `trait Circle : Shape`:
2491
2492 ~~~
2493 # trait Shape { fn area(&self) -> f64; }
2494 # trait Circle : Shape { fn radius(&self) -> f64; }
2495 fn radius_times_area<T: Circle>(c: T) -> f64 {
2496     // `c` is both a Circle and a Shape
2497     c.radius() * c.area()
2498 }
2499 ~~~
2500
2501 Likewise, supertrait methods may also be called on trait objects.
2502
2503 ~~~ {.ignore}
2504 use std::f64::consts::PI;
2505 # trait Shape { fn area(&self) -> f64; }
2506 # trait Circle : Shape { fn radius(&self) -> f64; }
2507 # struct Point { x: f64, y: f64 }
2508 # struct CircleStruct { center: Point, radius: f64 }
2509 # impl Circle for CircleStruct { fn radius(&self) -> f64 { (self.area() / PI).sqrt() } }
2510 # impl Shape for CircleStruct { fn area(&self) -> f64 { PI * square(self.radius) } }
2511
2512 let concrete = @CircleStruct{center:Point{x:3.0,y:4.0},radius:5.0};
2513 let mycircle: @Circle = concrete as @Circle;
2514 let nonsense = mycircle.radius() * mycircle.area();
2515 ~~~
2516
2517 > ***Note:*** Trait inheritance does not actually work with objects yet
2518
2519 ## Deriving implementations for traits
2520
2521 A small number of traits in `std` and `extra` can have implementations
2522 that can be automatically derived. These instances are specified by
2523 placing the `deriving` attribute on a data type declaration. For
2524 example, the following will mean that `Circle` has an implementation
2525 for `Eq` and can be used with the equality operators, and that a value
2526 of type `ABC` can be randomly generated and converted to a string:
2527
2528 ~~~
2529 #[deriving(Eq)]
2530 struct Circle { radius: f64 }
2531
2532 #[deriving(Clone, Show)]
2533 enum ABC { A, B, C }
2534 ~~~
2535
2536 The full list of derivable traits is `Eq`, `TotalEq`, `Ord`,
2537 `TotalOrd`, `Encodable` `Decodable`, `Clone`,
2538 `Hash`, `Rand`, `Default`, `Zero`, `FromPrimitive` and `Show`.
2539
2540 # Crates and the module system
2541
2542 Rust's module system is very powerful, but because of that also somewhat complex.
2543 Nevertheless, this section will try to explain every important aspect of it.
2544
2545 ## Crates
2546
2547 In order to speak about the module system, we first need to define the medium it exists in:
2548
2549 Let's say you've written a program or a library, compiled it, and got the resulting binary.
2550 In Rust, the content of all source code that the compiler directly had to compile in order to end up with
2551 that binary is collectively called a 'crate'.
2552
2553 For example, for a simple hello world program your crate only consists of this code:
2554
2555 ~~~~
2556 // `main.rs`
2557 fn main() {
2558     println!("Hello world!");
2559 }
2560 ~~~~
2561
2562 A crate is also the unit of independent compilation in Rust: `rustc` always compiles a single crate at a time,
2563 from which it produces either a library or an executable.
2564
2565 Note that merely using an already compiled library in your code does not make it part of your crate.
2566
2567 ## The module hierarchy
2568
2569 For every crate, all the code in it is arranged in a hierarchy of modules starting with a single
2570 root module. That root module is called the 'crate root'.
2571
2572 All modules in a crate below the crate root are declared with the `mod` keyword:
2573
2574 ~~~~
2575 // This is the crate root
2576
2577 mod farm {
2578     // This is the body of module 'farm' declared in the crate root.
2579
2580     fn chicken() { println!("cluck cluck"); }
2581     fn cow() { println!("mooo"); }
2582
2583     mod barn {
2584         // Body of module 'barn'
2585
2586         fn hay() { println!("..."); }
2587     }
2588 }
2589
2590 fn main() {
2591     println!("Hello farm!");
2592 }
2593 ~~~~
2594
2595 As you can see, your module hierarchy is now three modules deep: There is the crate root, which contains your `main()`
2596 function, and the module `farm`. The module `farm` also contains two functions and a third module `barn`,
2597 which contains a function `hay`.
2598
2599 (In case you already stumbled over `extern crate`: It isn't directly related to a bare `mod`, we'll get to it later. )
2600
2601 ## Paths and visibility
2602
2603 We've now defined a nice module hierarchy. But how do we access the items in it from our `main` function?
2604 One way to do it is to simply fully qualifying it:
2605
2606 ~~~~ {.ignore}
2607 mod farm {
2608     fn chicken() { println!("cluck cluck"); }
2609     // ...
2610 }
2611
2612 fn main() {
2613     println!("Hello chicken!");
2614
2615     ::farm::chicken(); // Won't compile yet, see further down
2616 }
2617 ~~~~
2618
2619 The `::farm::chicken` construct is what we call a 'path'.
2620
2621 Because it's starting with a `::`, it's also a 'global path', which qualifies
2622 an item by its full path in the module hierarchy relative to the crate root.
2623
2624 If the path were to start with a regular identifier, like `farm::chicken`, it
2625 would be a 'local path' instead. We'll get to them later.
2626
2627 Now, if you actually tried to compile this code example, you'll notice that you
2628 get a `function 'chicken' is private` error. That's because by default, items
2629 (`fn`, `struct`, `static`, `mod`, ...) are private.
2630
2631 To make them visible outside their containing modules, you need to mark them
2632 _public_ with `pub`:
2633
2634 ~~~~
2635 mod farm {
2636     pub fn chicken() { println!("cluck cluck"); }
2637     pub fn cow() { println!("mooo"); }
2638     // ...
2639 }
2640
2641 fn main() {
2642     println!("Hello chicken!");
2643     ::farm::chicken(); // This compiles now
2644 }
2645 ~~~~
2646
2647 Visibility restrictions in Rust exist only at module boundaries. This
2648 is quite different from most object-oriented languages that also
2649 enforce restrictions on objects themselves. That's not to say that
2650 Rust doesn't support encapsulation: both struct fields and methods can
2651 be private. But this encapsulation is at the module level, not the
2652 struct level.
2653
2654 For convenience, fields are _public_ by default, and can be made _private_ with
2655 the `priv` keyword:
2656
2657 ~~~
2658 mod farm {
2659 # pub type Chicken = int;
2660 # struct Human(int);
2661 # impl Human { pub fn rest(&self) { } }
2662 # pub fn make_me_a_farm() -> Farm { Farm { chickens: ~[], farmer: Human(0) } }
2663     pub struct Farm {
2664         priv chickens: ~[Chicken],
2665         farmer: Human
2666     }
2667
2668     impl Farm {
2669         fn feed_chickens(&self) { /* ... */ }
2670         pub fn add_chicken(&self, c: Chicken) { /* ... */ }
2671     }
2672
2673     pub fn feed_animals(farm: &Farm) {
2674         farm.feed_chickens();
2675     }
2676 }
2677
2678 fn main() {
2679     let f = make_me_a_farm();
2680     f.add_chicken(make_me_a_chicken());
2681     farm::feed_animals(&f);
2682     f.farmer.rest();
2683
2684     // This wouldn't compile because both are private:
2685     // `f.feed_chickens();`
2686     // `let chicken_counter = f.chickens.len();`
2687 }
2688 # fn make_me_a_farm() -> farm::Farm { farm::make_me_a_farm() }
2689 # fn make_me_a_chicken() -> farm::Chicken { 0 }
2690 ~~~
2691
2692 Exact details and specifications about visibility rules can be found in the Rust
2693 manual.
2694
2695 ## Files and modules
2696
2697 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.
2698
2699 The only file that's relevant when compiling is the one that contains the body
2700 of your crate root, and it's only relevant because you have to pass that file
2701 to `rustc` to compile your crate.
2702
2703 In principle, that's all you need: You can write any Rust program as one giant source file that contains your
2704 crate root and everything else in `mod ... { ... }` declarations.
2705
2706 However, in practice you usually want to split up your code into multiple
2707 source files to make it more manageable. Rust allows you to move the body of
2708 any module into its own source file. If you declare a module without its body,
2709 like `mod foo;`, the compiler will look for the files `foo.rs` and `foo/mod.rs`
2710 inside some directory (usually the same as of the source file containing the
2711 `mod foo;` declaration). If it finds either, it uses the content of that file
2712 as the body of the module. If it finds both, that's a compile error.
2713
2714 To move the content of `mod farm` into its own file, you can write:
2715
2716 ~~~~ {.ignore}
2717 // `main.rs` - contains body of the crate root
2718 mod farm; // Compiler will look for `farm.rs` and `farm/mod.rs`
2719
2720 fn main() {
2721     println!("Hello farm!");
2722     ::farm::cow();
2723 }
2724 ~~~~
2725
2726 ~~~~
2727 // `farm.rs` - contains body of module 'farm' in the crate root
2728 pub fn chicken() { println!("cluck cluck"); }
2729 pub fn cow() { println!("mooo"); }
2730
2731 pub mod barn {
2732     pub fn hay() { println!("..."); }
2733 }
2734 # fn main() { }
2735 ~~~~
2736
2737 In short, `mod foo;` is just syntactic sugar for `mod foo { /* content of <...>/foo.rs or <...>/foo/mod.rs */ }`.
2738
2739 This also means that having two or more identical `mod foo;` declarations
2740 somewhere in your crate hierarchy is generally a bad idea,
2741 just like copy-and-paste-ing a module into multiple places is a bad idea.
2742 Both will result in duplicate and mutually incompatible definitions.
2743
2744 When `rustc` resolves these module declarations, it starts by looking in the
2745 parent directory of the file containing the `mod foo` declaration. For example,
2746 given a file with the module body:
2747
2748 ~~~ {.ignore}
2749 // `src/main.rs`
2750 mod plants;
2751 mod animals {
2752     mod fish;
2753     mod mammals {
2754         mod humans;
2755     }
2756 }
2757 ~~~
2758
2759 The compiler will look for these files, in this order:
2760
2761 ~~~ {.notrust}
2762 src/plants.rs
2763 src/plants/mod.rs
2764
2765 src/animals/fish.rs
2766 src/animals/fish/mod.rs
2767
2768 src/animals/mammals/humans.rs
2769 src/animals/mammals/humans/mod.rs
2770 ~~~
2771
2772 Keep in mind that identical module hierarchies can still lead to different path
2773 lookups depending on how and where you've moved a module body to its own file.
2774 For example, if you move the `animals` module into its own file:
2775
2776 ~~~ {.ignore}
2777 // `src/main.rs`
2778 mod plants;
2779 mod animals;
2780 ~~~
2781
2782 ~~~ {.ignore}
2783 // `src/animals.rs` or `src/animals/mod.rs`
2784 mod fish;
2785 mod mammals {
2786     mod humans;
2787 }
2788 ~~~
2789
2790 ...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:
2791
2792 ~~~ {.notrust}
2793 src/animals.rs
2794     src/fish.rs
2795     src/fish/mod.rs
2796
2797     src/mammals/humans.rs
2798     src/mammals/humans/mod.rs
2799 ~~~
2800
2801 If the animals file is `src/animals/mod.rs`, `rustc` will look for:
2802
2803 ~~~ {.notrust}
2804 src/animals/mod.rs
2805     src/animals/fish.rs
2806     src/animals/fish/mod.rs
2807
2808     src/animals/mammals/humans.rs
2809     src/animals/mammals/humans/mod.rs
2810
2811 ~~~
2812
2813 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.
2814
2815 If you need to override where `rustc` will look for the file containing a
2816 module's source code, use the `path` compiler directive. For example, to load a
2817 `classified` module from a different file:
2818
2819 ~~~ {.ignore}
2820 #[path="../../area51/alien.rs"]
2821 mod classified;
2822 ~~~
2823
2824 ## Importing names into the local scope
2825
2826 Always referring to definitions in other modules with their global
2827 path gets old really fast, so Rust has a way to import
2828 them into the local scope of your module: `use`-statements.
2829
2830 They work like this: At the beginning of any module body, `fn` body, or any other block
2831 you can write a list of `use`-statements, consisting of the keyword `use` and a __global path__ to an item
2832 without the `::` prefix. For example, this imports `cow` into the local scope:
2833
2834 ~~~
2835 use farm::cow;
2836 # mod farm { pub fn cow() { println!("I'm a hidden ninja cow!") } }
2837 # fn main() { cow() }
2838 ~~~
2839
2840 The path you give to `use` is per default global, meaning relative to the crate root,
2841 no matter how deep the module hierarchy is, or whether the module body it's written in
2842 is contained in its own file (remember: files are irrelevant).
2843
2844 This is different to other languages, where you often only find a single import construct that combines the semantic
2845 of `mod foo;` and `use`-statements, and which tend to work relative to the source file or use an absolute file path
2846 - Rubys `require` or C/C++'s `#include` come to mind.
2847
2848 However, it's also possible to import things relative to the module of the `use`-statement:
2849 Adding a `super::` in front of the path will start in the parent module,
2850 while adding a `self::` prefix will start in the current module:
2851
2852 ~~~
2853 # mod workaround {
2854 # pub fn some_parent_item(){ println!("...") }
2855 # mod foo {
2856 use super::some_parent_item;
2857 use self::some_child_module::some_item;
2858 # pub fn bar() { some_parent_item(); some_item() }
2859 # pub mod some_child_module { pub fn some_item() {} }
2860 # }
2861 # }
2862 ~~~
2863
2864 Again - relative to the module, not to the file.
2865
2866 Imports are also shadowed by local definitions:
2867 For each name you mention in a module/block, `rust`
2868 will first look at all items that are defined locally,
2869 and only if that results in no match look at items you brought in
2870 scope with corresponding `use` statements.
2871
2872 ~~~ {.ignore}
2873 # // FIXME: Allow unused import in doc test
2874 use farm::cow;
2875 // ...
2876 # mod farm { pub fn cow() { println!("Hidden ninja cow is hidden.") } }
2877 fn cow() { println!("Mooo!") }
2878
2879 fn main() {
2880     cow() // resolves to the locally defined `cow()` function
2881 }
2882 ~~~
2883
2884 To make this behavior more obvious, the rule has been made that `use`-statement always need to be written
2885 before any declaration, like in the example above. This is a purely artificial rule introduced
2886 because people always assumed they shadowed each other based on order, despite the fact that all items in rust are
2887 mutually recursive, order independent definitions.
2888
2889 One odd consequence of that rule is that `use` statements also go in front of any `mod` declaration,
2890 even if they refer to things inside them:
2891
2892 ~~~
2893 use farm::cow;
2894 mod farm {
2895     pub fn cow() { println!("Moooooo?") }
2896 }
2897
2898 fn main() { cow() }
2899 ~~~
2900
2901 This is what our `farm` example looks like with `use` statements:
2902
2903 ~~~~
2904 use farm::chicken;
2905 use farm::cow;
2906 use farm::barn;
2907
2908 mod farm {
2909     pub fn chicken() { println!("cluck cluck"); }
2910     pub fn cow() { println!("mooo"); }
2911
2912     pub mod barn {
2913         pub fn hay() { println!("..."); }
2914     }
2915 }
2916
2917 fn main() {
2918     println!("Hello farm!");
2919
2920     // Can now refer to those names directly:
2921     chicken();
2922     cow();
2923     barn::hay();
2924 }
2925 ~~~~
2926
2927 And here an example with multiple files:
2928
2929 ~~~{.ignore}
2930 // `a.rs` - crate root
2931 use b::foo;
2932 mod b;
2933 fn main() { foo(); }
2934 ~~~
2935
2936 ~~~{.ignore}
2937 // `b.rs`
2938 use b::c::bar;
2939 pub mod c;
2940 pub fn foo() { bar(); }
2941 ~~~
2942
2943 ~~~
2944 // `c.rs`
2945 pub fn bar() { println!("Baz!"); }
2946 # fn main() {}
2947 ~~~
2948
2949 There also exist two short forms for importing multiple names at once:
2950
2951 1. Explicit mention multiple names as the last element of an `use` path:
2952
2953 ~~~
2954 use farm::{chicken, cow};
2955 # mod farm {
2956 #     pub fn cow() { println!("Did I already mention how hidden and ninja I am?") }
2957 #     pub fn chicken() { println!("I'm Bat-chicken, guardian of the hidden tutorial code.") }
2958 # }
2959 # fn main() { cow(); chicken() }
2960 ~~~
2961
2962 2. Import everything in a module with a wildcard:
2963
2964 ~~~
2965 use farm::*;
2966 # mod farm {
2967 #     pub fn cow() { println!("Bat-chicken? What a stupid name!") }
2968 #     pub fn chicken() { println!("Says the 'hidden ninja' cow.") }
2969 # }
2970 # fn main() { cow(); chicken() }
2971 ~~~
2972
2973 > ***Note:*** This feature of the compiler is currently gated behind the
2974 > `#[feature(globs)]` directive. More about these directives can be found in
2975 > the manual.
2976
2977 However, that's not all. You can also rename an item while you're bringing it into scope:
2978
2979 ~~~
2980 use egg_layer = farm::chicken;
2981 # mod farm { pub fn chicken() { println!("Laying eggs is fun!")  } }
2982 // ...
2983
2984 fn main() {
2985     egg_layer();
2986 }
2987 ~~~
2988
2989 In general, `use` creates an local alias:
2990 An alternate path and a possibly different name to access the same item,
2991 without touching the original, and with both being interchangeable.
2992
2993 ## Reexporting names
2994
2995 It is also possible to reexport items to be accessible under your module.
2996
2997 For that, you write `pub use`:
2998
2999 ~~~
3000 mod farm {
3001     pub use self::barn::hay;
3002
3003     pub fn chicken() { println!("cluck cluck"); }
3004     pub fn cow() { println!("mooo"); }
3005
3006     mod barn {
3007         pub fn hay() { println!("..."); }
3008     }
3009 }
3010
3011 fn main() {
3012     farm::chicken();
3013     farm::cow();
3014     farm::hay();
3015 }
3016 ~~~
3017
3018 Just like in normal `use` statements, the exported names
3019 merely represent an alias to the same thing and can also be renamed.
3020
3021 The above example also demonstrate what you can use `pub use` for:
3022 The nested `barn` module is private, but the `pub use` allows users
3023 of the module `farm` to access a function from `barn` without needing
3024 to know that `barn` exists.
3025
3026 In other words, you can use them to decouple an public api from their internal implementation.
3027
3028 ## Using libraries
3029
3030 So far we've only talked about how to define and structure your own crate.
3031
3032 However, most code out there will want to use preexisting libraries,
3033 as there really is no reason to start from scratch each time you start a new project.
3034
3035 In Rust terminology, we need a way to refer to other crates.
3036
3037 For that, Rust offers you the `extern crate` declaration:
3038
3039 ~~~
3040 extern crate num;
3041 // `num` ships with Rust (much like `extra`; more details further down).
3042
3043 fn main() {
3044     // The rational number '1/2':
3045     let one_half = ::num::rational::Ratio::new(1, 2);
3046 }
3047 ~~~
3048
3049 Despite its name, `extern crate` is a distinct construct from regular `mod` declarations:
3050 A statement of the form `extern crate foo;` will cause `rustc` to search for the crate `foo`,
3051 and if it finds a matching binary it lets you use it from inside your crate.
3052
3053 The effect it has on your module hierarchy mirrors aspects of both `mod` and `use`:
3054
3055 - Like `mod`, it causes `rustc` to actually emit code:
3056   The linkage information the binary needs to use the library `foo`.
3057
3058 - But like `use`, all `extern crate` statements that refer to the same library are interchangeable,
3059   as each one really just presents an alias to an external module (the crate root of the library
3060   you're linking against).
3061
3062 Remember how `use`-statements have to go before local declarations because the latter shadows the former?
3063 Well, `extern crate` statements also have their own rules in that regard:
3064 Both `use` and local declarations can shadow them, so the rule is that `extern crate` has to go in front
3065 of both `use` and local declarations.
3066
3067 Which can result in something like this:
3068
3069 ~~~
3070 extern crate num;
3071
3072 use farm::dog;
3073 use num::rational::Ratio;
3074
3075 mod farm {
3076     pub fn dog() { println!("woof"); }
3077 }
3078
3079 fn main() {
3080     farm::dog();
3081     let a_third = Ratio::new(1, 3);
3082 }
3083 ~~~
3084
3085 It's a bit weird, but it's the result of shadowing rules that have been set that way because
3086 they model most closely what people expect to shadow.
3087
3088 ## Crate metadata and settings
3089
3090 For every crate you can define a number of metadata items, such as link name, version or author.
3091 You can also toggle settings that have crate-global consequences. Both mechanism
3092 work by providing attributes in the crate root.
3093
3094 For example, Rust uniquely identifies crates by their link metadata, which includes
3095 the link name and the version. It also hashes the filename and the symbols in a binary
3096 based on the link metadata, allowing you to use two different versions of the same library in a crate
3097 without conflict.
3098
3099 Therefore, if you plan to compile your crate as a library, you should annotate it with that information:
3100
3101 ~~~~
3102 // `lib.rs`
3103
3104 # #[crate_type = "lib"];
3105 #[crate_id = "farm#2.5"];
3106
3107 // ...
3108 # fn farm() {}
3109 ~~~~
3110
3111 You can also specify crate id information in a `extern crate` statement.  For
3112 example, these `extern crate` statements would both accept and select the
3113 crate define above:
3114
3115 ~~~~ {.ignore}
3116 extern crate farm;
3117 extern crate farm = "farm#2.5";
3118 extern crate my_farm = "farm";
3119 ~~~~
3120
3121 Other crate settings and metadata include things like enabling/disabling certain errors or warnings,
3122 or setting the crate type (library or executable) explicitly:
3123
3124 ~~~~
3125 // `lib.rs`
3126 // ...
3127
3128 // This crate is a library ("bin" is the default)
3129 #[crate_id = "farm#2.5"];
3130 #[crate_type = "lib"];
3131
3132 // Turn on a warning
3133 #[warn(non_camel_case_types)]
3134 # fn farm() {}
3135 ~~~~
3136
3137 ## A minimal example
3138
3139 Now for something that you can actually compile yourself.
3140
3141 We define two crates, and use one of them as a library in the other.
3142
3143 ~~~~
3144 // `world.rs`
3145 #[crate_id = "world#0.42"];
3146
3147 # mod secret_module_to_make_this_test_run {
3148 pub fn explore() -> &'static str { "world" }
3149 # }
3150 ~~~~
3151
3152 ~~~~ {.ignore}
3153 // `main.rs`
3154 extern crate world;
3155 fn main() { println!("hello {}", world::explore()); }
3156 ~~~~
3157
3158 Now compile and run like this (adjust to your platform if necessary):
3159
3160 ~~~~ {.notrust}
3161 > rustc --crate-type=lib world.rs  # compiles libworld-<HASH>-0.42.so
3162 > rustc main.rs -L .               # compiles main
3163 > ./main
3164 "hello world"
3165 ~~~~
3166
3167 Notice that the library produced contains the version in the file name
3168 as well as an inscrutable string of alphanumerics. As explained in the previous paragraph,
3169 these are both part of Rust's library versioning scheme. The alphanumerics are
3170 a hash representing the crate's id.
3171
3172 ## The standard library and the prelude
3173
3174 While reading the examples in this tutorial, you might have asked yourself where all
3175 those magical predefined items like `range` are coming from.
3176
3177 The truth is, there's nothing magical about them: They are all defined normally
3178 in the `std` library, which is a crate that ships with Rust.
3179
3180 The only magical thing that happens is that `rustc` automatically inserts this line into your crate root:
3181
3182 ~~~ {.ignore}
3183 extern crate std;
3184 ~~~
3185
3186 As well as this line into every module body:
3187
3188 ~~~ {.ignore}
3189 use std::prelude::*;
3190 ~~~
3191
3192 The role of the `prelude` module is to re-export common definitions from `std`.
3193
3194 This allows you to use common types and functions like `Option<T>` or `range`
3195 without needing to import them. And if you need something from `std` that's not in the prelude,
3196 you just have to import it with an `use` statement.
3197
3198 For example, it re-exports `range` which is defined in `std::iter::range`:
3199
3200 ~~~
3201 use iter_range = std::iter::range;
3202
3203 fn main() {
3204     // `range` is imported by default
3205     for _ in range(0, 10) {}
3206
3207     // Doesn't hinder you from importing it under a different name yourself
3208     for _ in iter_range(0, 10) {}
3209
3210     // Or from not using the automatic import.
3211     for _ in ::std::iter::range(0, 10) {}
3212 }
3213 ~~~
3214
3215 Both auto-insertions can be disabled with an attribute if necessary:
3216
3217 ~~~
3218 // In the crate root:
3219 #[no_std];
3220 ~~~
3221
3222 ~~~
3223 // In any module:
3224 #[no_implicit_prelude];
3225 ~~~
3226
3227 See the [API documentation][stddoc] for details.
3228
3229 [stddoc]: std/index.html
3230
3231 # What next?
3232
3233 Now that you know the essentials, check out any of the additional
3234 guides on individual topics.
3235
3236 * [Pointers][pointers]
3237 * [Lifetimes][lifetimes]
3238 * [Tasks and communication][tasks]
3239 * [Macros][macros]
3240 * [The foreign function interface][ffi]
3241 * [Containers and iterators][container]
3242 * [Documenting Rust code][rustdoc]
3243 * [Testing Rust code][testing]
3244 * [The Rust Runtime][runtime]
3245
3246 There is further documentation on the [wiki], however those tend to be even more out of date as this document.
3247
3248 [pointers]: guide-pointers.html
3249 [lifetimes]: guide-lifetimes.html
3250 [tasks]: guide-tasks.html
3251 [macros]: guide-macros.html
3252 [ffi]: guide-ffi.html
3253 [container]: guide-container.html
3254 [testing]: guide-testing.html
3255 [runtime]: guide-runtime.html
3256 [rustdoc]: rustdoc.html
3257 [wiki]: https://github.com/mozilla/rust/wiki/Docs
3258
3259 [wiki-packages]: https://github.com/mozilla/rust/wiki/Doc-packages,-editors,-and-other-tools