]> git.lizzy.rs Git - rust.git/blob - src/doc/tutorial.md
auto merge of #13296 : brson/rust/0.11-pre, r=alexcrichton
[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-nightly.tar.gz
104 $ tar -xzf rust-nightly.tar.gz
105 $ cd rust-nightly
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-nightly.tar.gz
121 [win-exe]: http://static.rust-lang.org/dist/rust-nightly-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 fn angle(vector: (f64, f64)) -> f64 {
508     let pi = f64::consts::PI;
509     match vector {
510       (0.0, y) if y < 0.0 => 1.5 * pi,
511       (0.0, _) => 0.5 * pi,
512       (x, y) => (y / x).atan()
513     }
514 }
515 ~~~~
516
517 A variable name in a pattern matches any value, *and* binds that name
518 to the value of the matched value inside of the arm's action. Thus, `(0.0,
519 y)` matches any tuple whose first element is zero, and binds `y` to
520 the second element. `(x, y)` matches any two-element tuple, and binds both
521 elements to variables. `(0.0,_)` matches any tuple whose first element is zero
522 and does not bind anything to the second element.
523
524 A subpattern can also be bound to a variable, using `variable @ pattern`. For
525 example:
526
527 ~~~~
528 # let age = 23;
529 match age {
530     a @ 0..20 => println!("{} years old", a),
531     _ => println!("older than 21")
532 }
533 ~~~~
534
535 Any `match` arm can have a guard clause (written `if EXPR`), called a
536 *pattern guard*, which is an expression of type `bool` that
537 determines, after the pattern is found to match, whether the arm is
538 taken or not. The variables bound by the pattern are in scope in this
539 guard expression. The first arm in the `angle` example shows an
540 example of a pattern guard.
541
542 You've already seen simple `let` bindings, but `let` is a little
543 fancier than you've been led to believe. It, too, supports destructuring
544 patterns. For example, you can write this to extract the fields from a
545 tuple, introducing two variables at once: `a` and `b`.
546
547 ~~~~
548 # fn get_tuple_of_two_ints() -> (int, int) { (1, 1) }
549 let (a, b) = get_tuple_of_two_ints();
550 ~~~~
551
552 Let bindings only work with _irrefutable_ patterns: that is, patterns
553 that can never fail to match. This excludes `let` from matching
554 literals and most `enum` variants.
555
556 ## Loops
557
558 `while` denotes a loop that iterates as long as its given condition
559 (which must have type `bool`) evaluates to `true`. Inside a loop, the
560 keyword `break` aborts the loop, and `continue` aborts the current
561 iteration and continues with the next.
562
563 ~~~~
564 let mut cake_amount = 8;
565 while cake_amount > 0 {
566     cake_amount -= 1;
567 }
568 ~~~~
569
570 `loop` denotes an infinite loop, and is the preferred way of writing `while true`:
571
572 ~~~~
573 let mut x = 5u;
574 loop {
575     x += x - 3;
576     if x % 5 == 0 { break; }
577     println!("{}", x);
578 }
579 ~~~~
580
581 This code prints out a weird sequence of numbers and stops as soon as
582 it finds one that can be divided by five.
583
584 There is also a for-loop that can be used to iterate over a range of numbers:
585
586 ~~~~
587 for n in range(0, 5) {
588     println!("{}", n);
589 }
590 ~~~~
591
592 The snippet above prints integer numbers under 5 starting at 0.
593
594 More generally, a for loop works with anything implementing the `Iterator` trait.
595 Data structures can provide one or more methods that return iterators over
596 their contents. For example, strings support iteration over their contents in
597 various ways:
598
599 ~~~~
600 let s = "Hello";
601 for c in s.chars() {
602     println!("{}", c);
603 }
604 ~~~~
605
606 The snippet above prints the characters in "Hello" vertically, adding a new
607 line after each character.
608
609
610 # Data structures
611
612 ## Structs
613
614 Rust struct types must be declared before they are used using the `struct`
615 syntax: `struct Name { field1: T1, field2: T2 [, ...] }`, where `T1`, `T2`,
616 ... denote types. To construct a struct, use the same syntax, but leave off
617 the `struct`: for example: `Point { x: 1.0, y: 2.0 }`.
618
619 Structs are quite similar to C structs and are even laid out the same way in
620 memory (so you can read from a Rust struct in C, and vice-versa). Use the dot
621 operator to access struct fields, as in `mypoint.x`.
622
623 ~~~~
624 struct Point {
625     x: f64,
626     y: f64
627 }
628 ~~~~
629
630 Structs have "inherited mutability", which means that any field of a struct
631 may be mutable, if the struct is in a mutable slot.
632
633 With a value (say, `mypoint`) of such a type in a mutable location, you can do
634 `mypoint.y += 1.0`. But in an immutable location, such an assignment to a
635 struct without inherited mutability would result in a type error.
636
637 ~~~~ {.ignore}
638 # struct Point { x: f64, y: f64 }
639 let mut mypoint = Point { x: 1.0, y: 1.0 };
640 let origin = Point { x: 0.0, y: 0.0 };
641
642 mypoint.y += 1.0; // `mypoint` is mutable, and its fields as well
643 origin.y += 1.0; // ERROR: assigning to immutable field
644 ~~~~
645
646 `match` patterns destructure structs. The basic syntax is
647 `Name { fieldname: pattern, ... }`:
648
649 ~~~~
650 # struct Point { x: f64, y: f64 }
651 # let mypoint = Point { x: 0.0, y: 0.0 };
652 match mypoint {
653     Point { x: 0.0, y: yy } => println!("{}", yy),
654     Point { x: xx,  y: yy } => println!("{} {}", xx, yy)
655 }
656 ~~~~
657
658 In general, the field names of a struct do not have to appear in the same
659 order they appear in the type. When you are not interested in all
660 the fields of a struct, a struct pattern may end with `, ..` (as in
661 `Name { field1, .. }`) to indicate that you're ignoring all other fields.
662 Additionally, struct fields have a shorthand matching form that simply
663 reuses the field name as the binding name.
664
665 ~~~
666 # struct Point { x: f64, y: f64 }
667 # let mypoint = Point { x: 0.0, y: 0.0 };
668 match mypoint {
669     Point { x, .. } => println!("{}", x)
670 }
671 ~~~
672
673 ## Enums
674
675 Enums are datatypes with several alternate representations. A simple `enum`
676 defines one or more constants, all of which have the same type:
677
678 ~~~~
679 enum Direction {
680     North,
681     East,
682     South,
683     West
684 }
685 ~~~~
686
687 Each variant of this enum has a unique and constant integral discriminator
688 value. If no explicit discriminator is specified for a variant, the value
689 defaults to the value of the previous variant plus one. If the first variant
690 does not have a discriminator, it defaults to 0. For example, the value of
691 `North` is 0, `East` is 1, `South` is 2, and `West` is 3.
692
693 When an enum has simple integer discriminators, you can apply the `as` cast
694 operator to convert a variant to its discriminator value as an `int`:
695
696 ~~~~
697 # enum Direction { North }
698 println!( "{:?} => {}", North, North as int );
699 ~~~~
700
701 It is possible to set the discriminator values to chosen constant values:
702
703 ~~~~
704 enum Color {
705   Red = 0xff0000,
706   Green = 0x00ff00,
707   Blue = 0x0000ff
708 }
709 ~~~~
710
711 Variants do not have to be simple values; they may be more complex:
712
713 ~~~~
714 # struct Point { x: f64, y: f64 }
715 enum Shape {
716     Circle(Point, f64),
717     Rectangle(Point, Point)
718 }
719 ~~~~
720
721 A value of this type is either a `Circle`, in which case it contains a
722 `Point` struct and a f64, or a `Rectangle`, in which case it contains
723 two `Point` structs. The run-time representation of such a value
724 includes an identifier of the actual form that it holds, much like the
725 "tagged union" pattern in C, but with better static guarantees.
726
727 This declaration defines a type `Shape` that can refer to such shapes, and two
728 functions, `Circle` and `Rectangle`, which can be used to construct values of
729 the type. To create a new Circle, write `Circle(Point { x: 0.0, y: 0.0 },
730 10.0)`.
731
732 All of these variant constructors may be used as patterns. The only way to
733 access the contents of an enum instance is the destructuring of a match. For
734 example:
735
736 ~~~~
737 use std::f64;
738 # struct Point {x: f64, y: f64}
739 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
740 fn area(sh: Shape) -> f64 {
741     match sh {
742         Circle(_, size) => f64::consts::PI * size * size,
743         Rectangle(Point { x, y }, Point { x: x2, y: y2 }) => (x2 - x) * (y2 - y)
744     }
745 }
746 ~~~~
747
748 Use a lone `_` to ignore an individual field. Ignore all fields of a variant
749 like: `Circle(..)`. Nullary enum patterns are written without parentheses:
750
751 ~~~~
752 # struct Point { x: f64, y: f64 }
753 # enum Direction { North, East, South, West }
754 fn point_from_direction(dir: Direction) -> Point {
755     match dir {
756         North => Point { x:  0.0, y:  1.0 },
757         East  => Point { x:  1.0, y:  0.0 },
758         South => Point { x:  0.0, y: -1.0 },
759         West  => Point { x: -1.0, y:  0.0 }
760     }
761 }
762 ~~~~
763
764 Enum variants may also be structs. For example:
765
766 ~~~~
767 use std::f64;
768 # struct Point { x: f64, y: f64 }
769 # fn square(x: f64) -> f64 { x * x }
770 enum Shape {
771     Circle { center: Point, radius: f64 },
772     Rectangle { top_left: Point, bottom_right: Point }
773 }
774 fn area(sh: Shape) -> f64 {
775     match sh {
776         Circle { radius: radius, .. } => f64::consts::PI * square(radius),
777         Rectangle { top_left: top_left, bottom_right: bottom_right } => {
778             (bottom_right.x - top_left.x) * (top_left.y - bottom_right.y)
779         }
780     }
781 }
782 ~~~~
783
784 > ***Note:*** This feature of the compiler is currently gated behind the
785 > `#[feature(struct_variant)]` directive. More about these directives can be
786 > found in the manual.
787
788 ## Tuples
789
790 Tuples in Rust behave exactly like structs, except that their fields do not
791 have names. Thus, you cannot access their fields with dot notation.  Tuples
792 can have any arity (number of elements) except for 0 (though you may consider
793 unit, `()`, as the empty tuple if you like).
794
795 ~~~~
796 let mytup: (int, int, f64) = (10, 20, 30.0);
797 match mytup {
798   (a, b, c) => println!("{}", a + b + (c as int))
799 }
800 ~~~~
801
802 ## Tuple structs
803
804 Rust also has _tuple structs_, which behave like both structs and tuples,
805 except that, unlike tuples, tuple structs have names (so `Foo(1, 2)` has a
806 different type from `Bar(1, 2)`), and tuple structs' _fields_ do not have
807 names.
808
809 For example:
810
811 ~~~~
812 struct MyTup(int, int, f64);
813 let mytup: MyTup = MyTup(10, 20, 30.0);
814 match mytup {
815   MyTup(a, b, c) => println!("{}", a + b + (c as int))
816 }
817 ~~~~
818
819 <a name="newtype"></a>
820
821 There is a special case for tuple structs with a single field, which are
822 sometimes called "newtypes" (after Haskell's "newtype" feature). These are
823 used to define new types in such a way that the new name is not just a
824 synonym for an existing type but is rather its own distinct type.
825
826 ~~~~
827 struct GizmoId(int);
828 ~~~~
829
830 Types like this can be useful to differentiate between data that have
831 the same underlying type but must be used in different ways.
832
833 ~~~~
834 struct Inches(int);
835 struct Centimeters(int);
836 ~~~~
837
838 The above definitions allow for a simple way for programs to avoid
839 confusing numbers that correspond to different units. Their integer
840 values can be extracted with pattern matching:
841
842 ~~~
843 # struct Inches(int);
844
845 let length_with_unit = Inches(10);
846 let Inches(integer_length) = length_with_unit;
847 println!("length is {} inches", integer_length);
848 ~~~
849
850 # Functions
851
852 We've already seen several function definitions. Like all other static
853 declarations, such as `type`, functions can be declared both at the
854 top level and inside other functions (or in modules, which we'll come
855 back to [later](#crates-and-the-module-system)). The `fn` keyword introduces a
856 function. A function has an argument list, which is a parenthesized
857 list of `name: type` pairs separated by commas. An arrow `->`
858 separates the argument list and the function's return type.
859
860 ~~~~
861 fn line(a: int, b: int, x: int) -> int {
862     return a * x + b;
863 }
864 ~~~~
865
866 The `return` keyword immediately returns from the body of a function. It
867 is optionally followed by an expression to return. A function can
868 also return a value by having its top-level block produce an
869 expression.
870
871 ~~~~
872 fn line(a: int, b: int, x: int) -> int {
873     a * x + b
874 }
875 ~~~~
876
877 It's better Rust style to write a return value this way instead of
878 writing an explicit `return`. The utility of `return` comes in when
879 returning early from a function. Functions that do not return a value
880 are said to return unit, `()`, and both the return type and the return
881 value may be omitted from the definition. The following two functions
882 are equivalent.
883
884 ~~~~
885 fn do_nothing_the_hard_way() -> () { return (); }
886
887 fn do_nothing_the_easy_way() { }
888 ~~~~
889
890 Ending the function with a semicolon like so is equivalent to returning `()`.
891
892 ~~~~
893 fn line(a: int, b: int, x: int) -> int { a * x + b  }
894 fn oops(a: int, b: int, x: int) -> ()  { a * x + b; }
895
896 assert!(8 == line(5, 3, 1));
897 assert!(() == oops(5, 3, 1));
898 ~~~~
899
900 As with `match` expressions and `let` bindings, function arguments support
901 pattern destructuring. Like `let`, argument patterns must be irrefutable,
902 as in this example that unpacks the first value from a tuple and returns it.
903
904 ~~~
905 fn first((value, _): (int, f64)) -> int { value }
906 ~~~
907
908 # Destructors
909
910 A *destructor* is a function responsible for cleaning up the resources used by
911 an object when it is no longer accessible. Destructors can be defined to handle
912 the release of resources like files, sockets and heap memory.
913
914 Objects are never accessible after their destructor has been called, so no
915 dynamic failures are possible from accessing freed resources. When a task
916 fails, destructors of all objects in the task are called.
917
918 The `~` sigil represents a unique handle for a memory allocation on the heap:
919
920 ~~~~
921 {
922     // an integer allocated on the heap
923     let y = ~10;
924 }
925 // the destructor frees the heap memory as soon as `y` goes out of scope
926 ~~~~
927
928 Rust includes syntax for heap memory allocation in the language since it's
929 commonly used, but the same semantics can be implemented by a type with a
930 custom destructor.
931
932 # Ownership
933
934 Rust formalizes the concept of object ownership to delegate management of an
935 object's lifetime to either a variable or a task-local garbage collector. An
936 object's owner is responsible for managing the lifetime of the object by
937 calling the destructor, and the owner determines whether the object is mutable.
938
939 Ownership is recursive, so mutability is inherited recursively and a destructor
940 destroys the contained tree of owned objects. Variables are top-level owners
941 and destroy the contained object when they go out of scope.
942
943 ~~~~
944 // the struct owns the objects contained in the `x` and `y` fields
945 struct Foo { x: int, y: ~int }
946
947 {
948     // `a` is the owner of the struct, and thus the owner of the struct's fields
949     let a = Foo { x: 5, y: ~10 };
950 }
951 // when `a` goes out of scope, the destructor for the `~int` in the struct's
952 // field is called
953
954 // `b` is mutable, and the mutability is inherited by the objects it owns
955 let mut b = Foo { x: 5, y: ~10 };
956 b.x = 10;
957 ~~~~
958
959 If an object doesn't contain any non-Send types, it consists of a single
960 ownership tree and is itself given the `Send` trait which allows it to be sent
961 between tasks. Custom destructors can only be implemented directly on types
962 that are `Send`, but non-`Send` types can still *contain* types with custom
963 destructors. Example of types which are not `Send` are [`Gc<T>`][gc] and
964 [`Rc<T>`][rc], the shared-ownership types.
965
966 [gc]: http://static.rust-lang.org/doc/master/std/gc/struct.Gc.html
967 [rc]: http://static.rust-lang.org/doc/master/std/rc/struct.Rc.html
968
969 # Implementing a linked list
970
971 An `enum` is a natural fit for describing a linked list, because it can express
972 a `List` type as being *either* the end of the list (`Nil`) or another node
973 (`Cons`). The full definition of the `Cons` variant will require some thought.
974
975 ~~~ {.ignore}
976 enum List {
977     Cons(...), // an incomplete definition of the next element in a List
978     Nil        // the end of a List
979 }
980 ~~~
981
982 The obvious approach is to define `Cons` as containing an element in the list
983 along with the next `List` node. However, this will generate a compiler error.
984
985 ~~~ {.ignore}
986 // error: illegal recursive enum type; wrap the inner value in a box to make it representable
987 enum List {
988     Cons(u32, List), // an element (`u32`) and the next node in the list
989     Nil
990 }
991 ~~~
992
993 This error message is related to Rust's precise control over memory layout, and
994 solving it will require introducing the concept of *boxing*.
995
996 ## Boxes
997
998 A value in Rust is stored directly inside the owner. If a `struct` contains
999 four `u32` fields, it will be four times as large as a single `u32`.
1000
1001 ~~~
1002 use std::mem::size_of; // bring `size_of` into the current scope, for convenience
1003
1004 struct Foo {
1005     a: u32,
1006     b: u32,
1007     c: u32,
1008     d: u32
1009 }
1010
1011 assert_eq!(size_of::<Foo>(), size_of::<u32>() * 4);
1012
1013 struct Bar {
1014     a: Foo,
1015     b: Foo,
1016     c: Foo,
1017     d: Foo
1018 }
1019
1020 assert_eq!(size_of::<Bar>(), size_of::<u32>() * 16);
1021 ~~~
1022
1023 Our previous attempt at defining the `List` type included an `u32` and a `List`
1024 directly inside `Cons`, making it at least as big as the sum of both types. The
1025 type was invalid because the size was infinite!
1026
1027 An *owned box* (`~`) uses a dynamic memory allocation to provide the invariant
1028 of always being the size of a pointer, regardless of the contained type. This
1029 can be leveraged to create a valid `List` definition:
1030
1031 ~~~
1032 enum List {
1033     Cons(u32, ~List),
1034     Nil
1035 }
1036 ~~~
1037
1038 Defining a recursive data structure like this is the canonical example of an
1039 owned box. Much like an unboxed value, an owned box has a single owner and is
1040 therefore limited to expressing a tree-like data structure.
1041
1042 Consider an instance of our `List` type:
1043
1044 ~~~
1045 # enum List {
1046 #     Cons(u32, ~List),
1047 #     Nil
1048 # }
1049 let list = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1050 ~~~
1051
1052 It represents an owned tree of values, inheriting mutability down the tree and
1053 being destroyed along with the owner. Since the `list` variable above is
1054 immutable, the whole list is immutable. The memory allocation itself is the
1055 box, while the owner holds onto a pointer to it:
1056
1057 ~~~ {.notrust}
1058           List box             List box           List box            List box
1059         +--------------+    +--------------+    +--------------+    +--------------+
1060 list -> | Cons | 1 | ~ | -> | Cons | 2 | ~ | -> | Cons | 3 | ~ | -> | Nil          |
1061         +--------------+    +--------------+    +--------------+    +--------------+
1062 ~~~
1063
1064 > ***Note:*** the above diagram shows the logical contents of the enum. The actual
1065 > memory layout of the enum may vary. For example, for the `List` enum shown
1066 > above, Rust guarantees that there will be no enum tag field in the actual
1067 > structure. See the language reference for more details.
1068
1069 An owned box is a common example of a type with a destructor. The allocated
1070 memory is cleaned up when the box is destroyed.
1071
1072 ## Move semantics
1073
1074 Rust uses a shallow copy for parameter passing, assignment and returning from
1075 functions. Passing around the `List` will copy only as deep as the pointer to
1076 the box rather than doing an implicit heap allocation.
1077
1078 ~~~
1079 # enum List {
1080 #     Cons(u32, ~List),
1081 #     Nil
1082 # }
1083 let xs = Cons(1, ~Cons(2, ~Cons(3, ~Nil)));
1084 let ys = xs; // copies `Cons(u32, pointer)` shallowly
1085 ~~~
1086
1087 Rust will consider a shallow copy of a type with a destructor like `List` to
1088 *move ownership* of the value. After a value has been moved, the source
1089 location cannot be used unless it is reinitialized.
1090
1091 ~~~
1092 # enum List {
1093 #     Cons(u32, ~List),
1094 #     Nil
1095 # }
1096 let mut xs = Nil;
1097 let ys = xs;
1098
1099 // attempting to use `xs` will result in an error here
1100
1101 xs = Nil;
1102
1103 // `xs` can be used again
1104 ~~~
1105
1106 A destructor call will only occur for a variable that has not been moved from,
1107 as it is only called a single time.
1108
1109
1110 Avoiding a move can be done with the library-defined `clone` method:
1111
1112 ~~~~
1113 let x = ~5;
1114 let y = x.clone(); // `y` is a newly allocated box
1115 let z = x; // no new memory allocated, `x` can no longer be used
1116 ~~~~
1117
1118 The `clone` method is provided by the `Clone` trait, and can be derived for
1119 our `List` type. Traits will be explained in detail [later](#traits).
1120
1121 ~~~{.ignore}
1122 #[deriving(Clone)]
1123 enum List {
1124     Cons(u32, ~List),
1125     Nil
1126 }
1127
1128 let x = Cons(5, ~Nil);
1129 let y = x.clone();
1130
1131 // `x` can still be used!
1132
1133 let z = x;
1134
1135 // and now, it can no longer be used since it has been moved
1136 ~~~
1137
1138 The mutability of a value may be changed by moving it to a new owner:
1139
1140 ~~~~
1141 let r = ~13;
1142 let mut s = r; // box becomes mutable
1143 *s += 1;
1144 let t = s; // box becomes immutable
1145 ~~~~
1146
1147 A simple way to define a function prepending to the `List` type is to take
1148 advantage of moves:
1149
1150 ~~~
1151 enum List {
1152     Cons(u32, ~List),
1153     Nil
1154 }
1155
1156 fn prepend(xs: List, value: u32) -> List {
1157     Cons(value, ~xs)
1158 }
1159
1160 let mut xs = Nil;
1161 xs = prepend(xs, 1);
1162 xs = prepend(xs, 2);
1163 xs = prepend(xs, 3);
1164 ~~~
1165
1166 However, this is not a very flexible definition of `prepend` as it requires
1167 ownership of a list to be passed in rather than just mutating it in-place.
1168
1169 ## References
1170
1171 The obvious signature for a `List` equality comparison is the following:
1172
1173 ~~~{.ignore}
1174 fn eq(xs: List, ys: List) -> bool { /* ... */ }
1175 ~~~
1176
1177 However, this will cause both lists to be moved into the function. Ownership
1178 isn't required to compare the lists, so the function should take *references*
1179 (&T) instead.
1180
1181 ~~~{.ignore}
1182 fn eq(xs: &List, ys: &List) -> bool { /* ... */ }
1183 ~~~
1184
1185 A reference is a *non-owning* view of a value. A reference can be obtained with the `&` (address-of)
1186 operator. It can be dereferenced by using the `*` operator. In a pattern, such as `match` expression
1187 branches, the `ref` keyword can be used to bind to a variable name by-reference rather than
1188 by-value. A recursive definition of equality using references is as follows:
1189
1190 ~~~
1191 # enum List {
1192 #     Cons(u32, ~List),
1193 #     Nil
1194 # }
1195 fn eq(xs: &List, ys: &List) -> bool {
1196     // Match on the next node in both lists.
1197     match (xs, ys) {
1198         // If we have reached the end of both lists, they are equal.
1199         (&Nil, &Nil) => true,
1200         // If the current element in both lists is equal, keep going.
1201         (&Cons(x, ~ref next_xs), &Cons(y, ~ref next_ys)) if x == y => eq(next_xs, next_ys),
1202         // If the current elements are not equal, the lists are not equal.
1203         _ => false
1204     }
1205 }
1206
1207 let xs = Cons(5, ~Cons(10, ~Nil));
1208 let ys = Cons(5, ~Cons(10, ~Nil));
1209 assert!(eq(&xs, &ys));
1210 ~~~
1211
1212 > ***Note:*** Rust doesn't guarantee [tail-call](http://en.wikipedia.org/wiki/Tail_call) optimization,
1213 > but LLVM is able to handle a simple case like this with optimizations enabled.
1214
1215 ## Lists of other types
1216
1217 Our `List` type is currently always a list of 32-bit unsigned integers. By
1218 leveraging Rust's support for generics, it can be extended to work for any
1219 element type.
1220
1221 The `u32` in the previous definition can be substituted with a type parameter:
1222
1223 > ***Note:*** The following code introduces generics, which are explained in a
1224 > [dedicated section](#generics).
1225
1226 ~~~
1227 enum List<T> {
1228     Cons(T, ~List<T>),
1229     Nil
1230 }
1231 ~~~
1232
1233 The old `List` of `u32` is now available as `List<u32>`. The `prepend`
1234 definition has to be updated too:
1235
1236 ~~~
1237 # enum List<T> {
1238 #     Cons(T, ~List<T>),
1239 #     Nil
1240 # }
1241 fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1242     Cons(value, ~xs)
1243 }
1244 ~~~
1245
1246 Generic functions and types like this are equivalent to defining specialized
1247 versions for each set of type parameters.
1248
1249 Using the generic `List<T>` works much like before, thanks to type inference:
1250
1251 ~~~
1252 # enum List<T> {
1253 #     Cons(T, ~List<T>),
1254 #     Nil
1255 # }
1256 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1257 #     Cons(value, ~xs)
1258 # }
1259 let mut xs = Nil; // Unknown type! This is a `List<T>`, but `T` can be anything.
1260 xs = prepend(xs, 10); // The compiler infers the type of `xs` as `List<int>` from this.
1261 xs = prepend(xs, 15);
1262 xs = prepend(xs, 20);
1263 ~~~
1264
1265 The code sample above demonstrates type inference making most type annotations optional. It is
1266 equivalent to the following type-annotated code:
1267
1268 ~~~
1269 # enum List<T> {
1270 #     Cons(T, ~List<T>),
1271 #     Nil
1272 # }
1273 # fn prepend<T>(xs: List<T>, value: T) -> List<T> {
1274 #     Cons(value, ~xs)
1275 # }
1276 let mut xs: List<int> = Nil::<int>;
1277 xs = prepend::<int>(xs, 10);
1278 xs = prepend::<int>(xs, 15);
1279 xs = prepend::<int>(xs, 20);
1280 ~~~
1281
1282 In declarations, the language uses `Type<T, U, V>` to describe a list of type
1283 parameters, but expressions use `identifier::<T, U, V>`, to disambiguate the
1284 `<` operator.
1285
1286 ## Defining list equality with generics
1287
1288 Generic functions are type-checked from the definition, so any necessary properties of the type must
1289 be specified up-front. Our previous definition of list equality relied on the element type having
1290 the `==` operator available, and took advantage of the lack of a destructor on `u32` to copy it
1291 without a move of ownership.
1292
1293 We can add a *trait bound* on the `Eq` trait to require that the type implement the `==` operator.
1294 Two more `ref` annotations need to be added to avoid attempting to move out the element types:
1295
1296 ~~~
1297 # enum List<T> {
1298 #     Cons(T, ~List<T>),
1299 #     Nil
1300 # }
1301 fn eq<T: Eq>(xs: &List<T>, ys: &List<T>) -> bool {
1302     // Match on the next node in both lists.
1303     match (xs, ys) {
1304         // If we have reached the end of both lists, they are equal.
1305         (&Nil, &Nil) => true,
1306         // If the current element in both lists is equal, keep going.
1307         (&Cons(ref x, ~ref next_xs), &Cons(ref y, ~ref next_ys)) if x == y => eq(next_xs, next_ys),
1308         // If the current elements are not equal, the lists are not equal.
1309         _ => false
1310     }
1311 }
1312
1313 let xs = Cons('c', ~Cons('a', ~Cons('t', ~Nil)));
1314 let ys = Cons('c', ~Cons('a', ~Cons('t', ~Nil)));
1315 assert!(eq(&xs, &ys));
1316 ~~~
1317
1318 This would be a good opportunity to implement the `Eq` trait for our list type, making the `==` and
1319 `!=` operators available. We'll need to provide an `impl` for the `Eq` trait and a definition of the
1320 `eq` method. In a method, the `self` parameter refers to an instance of the type we're implementing
1321 on.
1322
1323 ~~~
1324 # enum List<T> {
1325 #     Cons(T, ~List<T>),
1326 #     Nil
1327 # }
1328 impl<T: Eq> Eq for List<T> {
1329     fn eq(&self, ys: &List<T>) -> bool {
1330         // Match on the next node in both lists.
1331         match (self, ys) {
1332             // If we have reached the end of both lists, they are equal.
1333             (&Nil, &Nil) => true,
1334             // If the current element in both lists is equal, keep going.
1335             (&Cons(ref x, ~ref next_xs), &Cons(ref y, ~ref next_ys)) if x == y => next_xs == next_ys,
1336             // If the current elements are not equal, the lists are not equal.
1337             _ => false
1338         }
1339     }
1340 }
1341
1342 let xs = Cons(5, ~Cons(10, ~Nil));
1343 let ys = Cons(5, ~Cons(10, ~Nil));
1344 // The methods below are part of the Eq trait,
1345 // which we implemented on our linked list.
1346 assert!(xs.eq(&ys));
1347 assert!(!xs.ne(&ys));
1348
1349 // The Eq trait also allows us to use the shorthand infix operators.
1350 assert!(xs == ys);    // `xs == ys` is short for `xs.eq(&ys)`
1351 assert!(!(xs != ys)); // `xs != ys` is short for `xs.ne(&ys)`
1352 ~~~
1353
1354 # More on boxes
1355
1356 The most common use case for owned boxes is creating recursive data structures
1357 like a binary search tree. Rust's trait-based generics system (covered later in
1358 the tutorial) is usually used for static dispatch, but also provides dynamic
1359 dispatch via boxing. Values of different types may have different sizes, but a
1360 box is able to *erase* the difference via the layer of indirection they
1361 provide.
1362
1363 In uncommon cases, the indirection can provide a performance gain or memory
1364 reduction by making values smaller. However, unboxed values should almost
1365 always be preferred when they are usable.
1366
1367 Note that returning large unboxed values via boxes is unnecessary. A large
1368 value is returned via a hidden output parameter, and the decision on where to
1369 place the return value should be left to the caller:
1370
1371 ~~~~
1372 fn foo() -> (u64, u64, u64, u64, u64, u64) {
1373     (5, 5, 5, 5, 5, 5)
1374 }
1375
1376 let x = ~foo(); // allocates a `~` box, and writes the integers directly to it
1377 ~~~~
1378
1379 Beyond the properties granted by the size, an owned box behaves as a regular
1380 value by inheriting the mutability and lifetime of the owner:
1381
1382 ~~~~
1383 let x = 5; // immutable
1384 let mut y = 5; // mutable
1385 y += 2;
1386
1387 let x = ~5; // immutable
1388 let mut y = ~5; // mutable
1389 *y += 2; // the `*` operator is needed to access the contained value
1390 ~~~~
1391
1392 # References
1393
1394 In contrast with
1395 owned boxes, where the holder of an owned box is the owner of the pointed-to
1396 memory, references never imply ownership - they are "borrowed".
1397 You can borrow a reference to
1398 any object, and the compiler verifies that it cannot outlive the lifetime of
1399 the object.
1400
1401 As an example, consider a simple struct type, `Point`:
1402
1403 ~~~
1404 struct Point {
1405     x: f64,
1406     y: f64
1407 }
1408 ~~~~
1409
1410 We can use this simple definition to allocate points in many different
1411 ways. For example, in this code, each of these three local variables
1412 contains a point, but allocated in a different location:
1413
1414 ~~~
1415 # struct Point { x: f64, y: f64 }
1416 let on_the_stack : Point  =  Point { x: 3.0, y: 4.0 };
1417 let managed_box  : @Point = @Point { x: 5.0, y: 1.0 };
1418 let owned_box    : ~Point = ~Point { x: 7.0, y: 9.0 };
1419 ~~~
1420
1421 Suppose we want to write a procedure that computes the distance
1422 between any two points, no matter where they are stored. For example,
1423 we might like to compute the distance between `on_the_stack` and
1424 `managed_box`, or between `managed_box` and `owned_box`. One option is
1425 to define a function that takes two arguments of type point—that is,
1426 it takes the points by value. But this will cause the points to be
1427 copied when we call the function. For points, this is probably not so
1428 bad, but often copies are expensive. So we’d like to define a function
1429 that takes the points by pointer. We can use references to do this:
1430
1431 ~~~
1432 # struct Point { x: f64, y: f64 }
1433 fn compute_distance(p1: &Point, p2: &Point) -> f64 {
1434     let x_d = p1.x - p2.x;
1435     let y_d = p1.y - p2.y;
1436     (x_d * x_d + y_d * y_d).sqrt()
1437 }
1438 ~~~
1439
1440 Now we can call `compute_distance()` in various ways:
1441
1442 ~~~
1443 # struct Point{ x: f64, y: f64 };
1444 # let on_the_stack : Point  =  Point { x: 3.0, y: 4.0 };
1445 # let managed_box  : @Point = @Point { x: 5.0, y: 1.0 };
1446 # let owned_box    : ~Point = ~Point { x: 7.0, y: 9.0 };
1447 # fn compute_distance(p1: &Point, p2: &Point) -> f64 { 0.0 }
1448 compute_distance(&on_the_stack, managed_box);
1449 compute_distance(managed_box, owned_box);
1450 ~~~
1451
1452 Here the `&` operator is used to take the address of the variable
1453 `on_the_stack`; this is because `on_the_stack` has the type `Point`
1454 (that is, a struct value) and we have to take its address to get a
1455 reference. We also call this _borrowing_ the local variable
1456 `on_the_stack`, because we are creating an alias: that is, another
1457 route to the same data.
1458
1459 In the case of the boxes `managed_box` and `owned_box`, however, no
1460 explicit action is necessary. The compiler will automatically convert
1461 a box like `@point` or `~point` to a reference like
1462 `&point`. This is another form of borrowing; in this case, the
1463 contents of the managed/owned box are being lent out.
1464
1465 Whenever a value is borrowed, there are some limitations on what you
1466 can do with the original. For example, if the contents of a variable
1467 have been lent out, you cannot send that variable to another task, nor
1468 will you be permitted to take actions that might cause the borrowed
1469 value to be freed or to change its type. This rule should make
1470 intuitive sense: you must wait for a borrowed value to be returned
1471 (that is, for the reference to go out of scope) before you can
1472 make full use of it again.
1473
1474 For a more in-depth explanation of references and lifetimes, read the
1475 [references and lifetimes guide][lifetimes].
1476
1477 ## Freezing
1478
1479 Lending an &-pointer to an object freezes it and prevents mutation—even if the object was declared as `mut`.
1480 `Freeze` objects have freezing enforced statically at compile-time. An example
1481 of a non-`Freeze` type is [`RefCell<T>`][refcell].
1482
1483 ~~~~
1484 let mut x = 5;
1485 {
1486     let y = &x; // `x` is now frozen. It cannot be modified or re-assigned.
1487 }
1488 // `x` is now unfrozen again
1489 # x = 3;
1490 ~~~~
1491
1492 [refcell]: http://static.rust-lang.org/doc/master/std/cell/struct.RefCell.html
1493
1494 # Dereferencing pointers
1495
1496 Rust uses the unary star operator (`*`) to access the contents of a
1497 box or pointer, similarly to C.
1498
1499 ~~~
1500 let managed = @10;
1501 let owned = ~20;
1502 let borrowed = &30;
1503
1504 let sum = *managed + *owned + *borrowed;
1505 ~~~
1506
1507 Dereferenced mutable pointers may appear on the left hand side of
1508 assignments. Such an assignment modifies the value that the pointer
1509 points to.
1510
1511 ~~~
1512 let managed = @10;
1513 let mut owned = ~20;
1514
1515 let mut value = 30;
1516 let borrowed = &mut value;
1517
1518 *owned = *borrowed + 100;
1519 *borrowed = *managed + 1000;
1520 ~~~
1521
1522 Pointers have high operator precedence, but lower precedence than the
1523 dot operator used for field and method access. This precedence order
1524 can sometimes make code awkward and parenthesis-filled.
1525
1526 ~~~
1527 # struct Point { x: f64, y: f64 }
1528 # enum Shape { Rectangle(Point, Point) }
1529 # impl Shape { fn area(&self) -> int { 0 } }
1530 let start = @Point { x: 10.0, y: 20.0 };
1531 let end = ~Point { x: (*start).x + 100.0, y: (*start).y + 100.0 };
1532 let rect = &Rectangle(*start, *end);
1533 let area = (*rect).area();
1534 ~~~
1535
1536 To combat this ugliness the dot operator applies _automatic pointer
1537 dereferencing_ to the receiver (the value on the left-hand side of the
1538 dot), so in most cases, explicitly dereferencing the receiver is not necessary.
1539
1540 ~~~
1541 # struct Point { x: f64, y: f64 }
1542 # enum Shape { Rectangle(Point, Point) }
1543 # impl Shape { fn area(&self) -> int { 0 } }
1544 let start = @Point { x: 10.0, y: 20.0 };
1545 let end = ~Point { x: start.x + 100.0, y: start.y + 100.0 };
1546 let rect = &Rectangle(*start, *end);
1547 let area = rect.area();
1548 ~~~
1549
1550 You can write an expression that dereferences any number of pointers
1551 automatically. For example, if you feel inclined, you could write
1552 something silly like
1553
1554 ~~~
1555 # struct Point { x: f64, y: f64 }
1556 let point = &@~Point { x: 10.0, y: 20.0 };
1557 println!("{:f}", point.x);
1558 ~~~
1559
1560 The indexing operator (`[]`) also auto-dereferences.
1561
1562 # Vectors and strings
1563
1564 A vector is a contiguous block of memory containing zero or more values of the
1565 same type. Rust also supports vector reference types, called slices, which are
1566 a view into a block of memory represented as a pointer and a length.
1567
1568 Strings are represented as vectors of `u8`, with the guarantee of containing a
1569 valid UTF-8 sequence.
1570
1571 Fixed-size vectors are an unboxed block of memory, with the element length as
1572 part of the type. A fixed-size vector owns the elements it contains, so the
1573 elements are mutable if the vector is mutable. Fixed-size strings do not exist.
1574
1575 ~~~
1576 // A fixed-size vector
1577 let numbers = [1, 2, 3];
1578 let more_numbers = numbers;
1579
1580 // The type of a fixed-size vector is written as `[Type, ..length]`
1581 let five_zeroes: [int, ..5] = [0, ..5];
1582 ~~~
1583
1584 A unique vector is dynamically sized, and has a destructor to clean up
1585 allocated memory on the heap. A unique vector owns the elements it contains, so
1586 the elements are mutable if the vector is mutable.
1587
1588 ~~~
1589 // A dynamically sized vector (unique vector)
1590 let mut numbers = ~[1, 2, 3];
1591 numbers.push(4);
1592 numbers.push(5);
1593
1594 // The type of a unique vector is written as `~[int]`
1595 let more_numbers: ~[int] = numbers;
1596
1597 // The original `numbers` value can no longer be used, due to move semantics.
1598
1599 let mut string = ~"fo";
1600 string.push_char('o');
1601 ~~~
1602
1603 Slices are similar to fixed-size vectors, but the length is not part of the
1604 type. They simply point into a block of memory and do not have ownership over
1605 the elements.
1606
1607 ~~~
1608 // A slice
1609 let xs = &[1, 2, 3];
1610
1611 // Slices have their type written as `&[int]`
1612 let ys: &[int] = xs;
1613
1614 // Other vector types coerce to slices
1615 let three = [1, 2, 3];
1616 let zs: &[int] = three;
1617
1618 // An unadorned string literal is an immutable string slice
1619 let string = "foobar";
1620
1621 // A string slice type is written as `&str`
1622 let view: &str = string.slice(0, 3);
1623 ~~~
1624
1625 Mutable slices also exist, just as there are mutable references. However, there
1626 are no mutable string slices. Strings are a multi-byte encoding (UTF-8) of
1627 Unicode code points, so they cannot be freely mutated without the ability to
1628 alter the length.
1629
1630 ~~~
1631 let mut xs = [1, 2, 3];
1632 let view = xs.mut_slice(0, 2);
1633 view[0] = 5;
1634
1635 // The type of a mutable slice is written as `&mut [T]`
1636 let ys: &mut [int] = &mut [1, 2, 3];
1637 ~~~
1638
1639 Square brackets denote indexing into a vector:
1640
1641 ~~~~
1642 # enum Crayon { Almond, AntiqueBrass, Apricot,
1643 #               Aquamarine, Asparagus, AtomicTangerine,
1644 #               BananaMania, Beaver, Bittersweet };
1645 # fn draw_scene(c: Crayon) { }
1646 let crayons: [Crayon, ..3] = [BananaMania, Beaver, Bittersweet];
1647 match crayons[0] {
1648     Bittersweet => draw_scene(crayons[0]),
1649     _ => ()
1650 }
1651 ~~~~
1652
1653 A vector can be destructured using pattern matching:
1654
1655 ~~~~
1656 let numbers: &[int] = &[1, 2, 3];
1657 let score = match numbers {
1658     [] => 0,
1659     [a] => a * 10,
1660     [a, b] => a * 6 + b * 4,
1661     [a, b, c, ..rest] => a * 5 + b * 3 + c * 2 + rest.len() as int
1662 };
1663 ~~~~
1664
1665 Both vectors and strings support a number of useful [methods](#methods),
1666 defined in [`std::vec`] and [`std::str`].
1667
1668 [`std::vec`]: std/vec/index.html
1669 [`std::str`]: std/str/index.html
1670
1671 # Ownership escape hatches
1672
1673 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
1674 single parent ownership.
1675
1676 The standard library provides the `std::rc::Rc` pointer type to express *shared ownership* over a
1677 reference counted box. As soon as all of the `Rc` pointers go out of scope, the box and the
1678 contained value are destroyed.
1679
1680 ~~~
1681 use std::rc::Rc;
1682
1683 // A fixed-size array allocated in a reference-counted box
1684 let x = Rc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1685 let y = x.clone(); // a new owner
1686 let z = x; // this moves `x` into `z`, rather than creating a new owner
1687
1688 assert!(*z == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1689
1690 // the variable is mutable, but not the contents of the box
1691 let mut a = Rc::new([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
1692 a = z;
1693 ~~~
1694
1695 A garbage collected pointer is provided via `std::gc::Gc`, with a task-local garbage collector
1696 having ownership of the box. It allows the creation of cycles, and the individual `Gc` pointers do
1697 not have a destructor.
1698
1699 ~~~
1700 use std::gc::Gc;
1701
1702 // A fixed-size array allocated in a garbage-collected box
1703 let x = Gc::new([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1704 let y = x; // does not perform a move, unlike with `Rc`
1705 let z = x;
1706
1707 assert!(*z.borrow() == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1708 ~~~
1709
1710 With shared ownership, mutability cannot be inherited so the boxes are always immutable. However,
1711 it's possible to use *dynamic* mutability via types like `std::cell::Cell` where freezing is handled
1712 via dynamic checks and can fail at runtime.
1713
1714 The `Rc` and `Gc` types are not sendable, so they cannot be used to share memory between tasks. Safe
1715 immutable and mutable shared memory is provided by the `extra::arc` module.
1716
1717 # Closures
1718
1719 Named functions, like those we've seen so far, may not refer to local
1720 variables declared outside the function: they do not close over their
1721 environment (sometimes referred to as "capturing" variables in their
1722 environment). For example, you couldn't write the following:
1723
1724 ~~~~ {.ignore}
1725 let foo = 10;
1726
1727 fn bar() -> int {
1728    return foo; // `bar` cannot refer to `foo`
1729 }
1730 ~~~~
1731
1732 Rust also supports _closures_, functions that can access variables in
1733 the enclosing scope.
1734
1735 ~~~~
1736 fn call_closure_with_ten(b: |int|) { b(10); }
1737
1738 let captured_var = 20;
1739 let closure = |arg| println!("captured_var={}, arg={}", captured_var, arg);
1740
1741 call_closure_with_ten(closure);
1742 ~~~~
1743
1744 Closures begin with the argument list between vertical bars and are followed by
1745 a single expression. Remember that a block, `{ <expr1>; <expr2>; ... }`, is
1746 considered a single expression: it evaluates to the result of the last
1747 expression it contains if that expression is not followed by a semicolon,
1748 otherwise the block evaluates to `()`.
1749
1750 The types of the arguments are generally omitted, as is the return type,
1751 because the compiler can almost always infer them. In the rare case where the
1752 compiler needs assistance, though, the arguments and return types may be
1753 annotated.
1754
1755 ~~~~
1756 let square = |x: int| -> uint { (x * x) as uint };
1757 ~~~~
1758
1759 There are several forms of closure, each with its own role. The most
1760 common, called a _stack closure_, has type `||` and can directly
1761 access local variables in the enclosing scope.
1762
1763 ~~~~
1764 let mut max = 0;
1765 let f = |x: int| if x > max { max = x };
1766 for x in [1, 2, 3].iter() {
1767     f(*x);
1768 }
1769 ~~~~
1770
1771 Stack closures are very efficient because their environment is
1772 allocated on the call stack and refers by pointer to captured
1773 locals. To ensure that stack closures never outlive the local
1774 variables to which they refer, stack closures are not
1775 first-class. That is, they can only be used in argument position; they
1776 cannot be stored in data structures or returned from
1777 functions. Despite these limitations, stack closures are used
1778 pervasively in Rust code.
1779
1780 ## Owned closures
1781
1782 Owned closures, written `proc`,
1783 hold on to things that can safely be sent between
1784 processes. They copy the values they close over, much like managed
1785 closures, but they also own them: that is, no other code can access
1786 them. Owned closures are used in concurrent code, particularly
1787 for spawning [tasks][tasks].
1788
1789 Closures can be used to spawn tasks.
1790 A practical example of this pattern is found when using the `spawn` function,
1791 which starts a new task.
1792
1793 ~~~~
1794 use std::task::spawn;
1795
1796 // proc is the closure which will be spawned.
1797 spawn(proc() {
1798     println!("I'm a new task")
1799 });
1800 ~~~~
1801
1802 > ***Note:*** If you want to see the output of `debug!` statements, you will need to turn on
1803 > `debug!` logging.  To enable `debug!` logging, set the RUST_LOG environment
1804 > variable to the name of your crate, which, for a file named `foo.rs`, will be
1805 > `foo` (e.g., with bash, `export RUST_LOG=foo`).
1806
1807 ## Closure compatibility
1808
1809 Rust closures have a convenient subtyping property: you can pass any kind of
1810 closure (as long as the arguments and return types match) to functions
1811 that expect a `||`. Thus, when writing a higher-order function that
1812 only calls its function argument, and does nothing else with it, you
1813 should almost always declare the type of that argument as `||`. That way,
1814 callers may pass any kind of closure.
1815
1816 ~~~~
1817 fn call_twice(f: ||) { f(); f(); }
1818 let closure = || { "I'm a closure, and it doesn't matter what type I am"; };
1819 fn function() { "I'm a normal function"; }
1820 call_twice(closure);
1821 call_twice(function);
1822 ~~~~
1823
1824 > ***Note:*** Both the syntax and the semantics will be changing
1825 > in small ways. At the moment they can be unsound in some
1826 > scenarios, particularly with non-copyable types.
1827
1828 # Methods
1829
1830 Methods are like functions except that they always begin with a special argument,
1831 called `self`,
1832 which has the type of the method's receiver. The
1833 `self` argument is like `this` in C++ and many other languages.
1834 Methods are called with dot notation, as in `my_vec.len()`.
1835
1836 _Implementations_, written with the `impl` keyword, can define
1837 methods on most Rust types, including structs and enums.
1838 As an example, let's define a `draw` method on our `Shape` enum.
1839
1840 ~~~
1841 # fn draw_circle(p: Point, f: f64) { }
1842 # fn draw_rectangle(p: Point, p: Point) { }
1843 struct Point {
1844     x: f64,
1845     y: f64
1846 }
1847
1848 enum Shape {
1849     Circle(Point, f64),
1850     Rectangle(Point, Point)
1851 }
1852
1853 impl Shape {
1854     fn draw(&self) {
1855         match *self {
1856             Circle(p, f) => draw_circle(p, f),
1857             Rectangle(p1, p2) => draw_rectangle(p1, p2)
1858         }
1859     }
1860 }
1861
1862 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1863 s.draw();
1864 ~~~
1865
1866 This defines an _implementation_ for `Shape` containing a single
1867 method, `draw`. In most respects the `draw` method is defined
1868 like any other function, except for the name `self`.
1869
1870 The type of `self` is the type on which the method is implemented,
1871 or a pointer thereof. As an argument it is written either `self`,
1872 `&self`, or `~self`.
1873 A caller must in turn have a compatible pointer type to call the method.
1874
1875 ~~~
1876 # fn draw_circle(p: Point, f: f64) { }
1877 # fn draw_rectangle(p: Point, p: Point) { }
1878 # struct Point { x: f64, y: f64 }
1879 # enum Shape {
1880 #     Circle(Point, f64),
1881 #     Rectangle(Point, Point)
1882 # }
1883 impl Shape {
1884     fn draw_reference(&self) { /* ... */ }
1885     fn draw_owned(~self) { /* ... */ }
1886     fn draw_value(self) { /* ... */ }
1887 }
1888
1889 let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1890
1891 (~s).draw_owned();
1892 (&s).draw_reference();
1893 s.draw_value();
1894 ~~~
1895
1896 Methods typically take a reference self type,
1897 so the compiler will go to great lengths to convert a callee
1898 to a reference.
1899
1900 ~~~
1901 # fn draw_circle(p: Point, f: f64) { }
1902 # fn draw_rectangle(p: Point, p: Point) { }
1903 # struct Point { x: f64, y: f64 }
1904 # enum Shape {
1905 #     Circle(Point, f64),
1906 #     Rectangle(Point, Point)
1907 # }
1908 # impl Shape {
1909 #    fn draw_reference(&self) { /* ... */ }
1910 #    fn draw_owned(~self) { /* ... */ }
1911 #    fn draw_value(self) { /* ... */ }
1912 # }
1913 # let s = Circle(Point { x: 1.0, y: 2.0 }, 3.0);
1914 // As with typical function arguments, managed and owned pointers
1915 // are automatically converted to references
1916
1917 (@s).draw_reference();
1918 (~s).draw_reference();
1919
1920 // Unlike typical function arguments, the self value will
1921 // automatically be referenced ...
1922 s.draw_reference();
1923
1924 // ... and dereferenced
1925 (& &s).draw_reference();
1926
1927 // ... and dereferenced and borrowed
1928 (&@~s).draw_reference();
1929 ~~~
1930
1931 Implementations may also define standalone (sometimes called "static")
1932 methods. The absence of a `self` parameter distinguishes such methods.
1933 These methods are the preferred way to define constructor functions.
1934
1935 ~~~~ {.ignore}
1936 impl Circle {
1937     fn area(&self) -> f64 { /* ... */ }
1938     fn new(area: f64) -> Circle { /* ... */ }
1939 }
1940 ~~~~
1941
1942 To call such a method, just prefix it with the type name and a double colon:
1943
1944 ~~~~
1945 use std::f64::consts::PI;
1946 struct Circle { radius: f64 }
1947 impl Circle {
1948     fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
1949 }
1950 let c = Circle::new(42.5);
1951 ~~~~
1952
1953 # Generics
1954
1955 Throughout this tutorial, we've been defining functions that act only
1956 on specific data types. With type parameters we can also define
1957 functions whose arguments have generic types, and which can be invoked
1958 with a variety of types. Consider a generic `map` function, which
1959 takes a function `function` and a vector `vector` and returns a new
1960 vector consisting of the result of applying `function` to each element
1961 of `vector`:
1962
1963 ~~~~
1964 fn map<T, U>(vector: &[T], function: |v: &T| -> U) -> ~[U] {
1965     let mut accumulator = ~[];
1966     for element in vector.iter() {
1967         accumulator.push(function(element));
1968     }
1969     return accumulator;
1970 }
1971 ~~~~
1972
1973 When defined with type parameters, as denoted by `<T, U>`, this
1974 function can be applied to any type of vector, as long as the type of
1975 `function`'s argument and the type of the vector's contents agree with
1976 each other.
1977
1978 Inside a generic function, the names of the type parameters
1979 (capitalized by convention) stand for opaque types. All you can do
1980 with instances of these types is pass them around: you can't apply any
1981 operations to them or pattern-match on them. Note that instances of
1982 generic types are often passed by pointer. For example, the parameter
1983 `function()` is supplied with a pointer to a value of type `T` and not
1984 a value of type `T` itself. This ensures that the function works with
1985 the broadest set of types possible, since some types are expensive or
1986 illegal to copy and pass by value.
1987
1988 Generic `type`, `struct`, and `enum` declarations follow the same pattern:
1989
1990 ~~~~
1991 extern crate collections;
1992 type Set<T> = collections::HashMap<T, ()>;
1993
1994 struct Stack<T> {
1995     elements: ~[T]
1996 }
1997
1998 enum Option<T> {
1999     Some(T),
2000     None
2001 }
2002 # fn main() {}
2003 ~~~~
2004
2005 These declarations can be instantiated to valid types like `Set<int>`,
2006 `Stack<int>`, and `Option<int>`.
2007
2008 The last type in that example, `Option`, appears frequently in Rust code.
2009 Because Rust does not have null pointers (except in unsafe code), we need
2010 another way to write a function whose result isn't defined on every possible
2011 combination of arguments of the appropriate types. The usual way is to write
2012 a function that returns `Option<T>` instead of `T`.
2013
2014 ~~~~
2015 # struct Point { x: f64, y: f64 }
2016 # enum Shape { Circle(Point, f64), Rectangle(Point, Point) }
2017 fn radius(shape: Shape) -> Option<f64> {
2018     match shape {
2019         Circle(_, radius) => Some(radius),
2020         Rectangle(..)      => None
2021     }
2022 }
2023 ~~~~
2024
2025 The Rust compiler compiles generic functions very efficiently by
2026 *monomorphizing* them. *Monomorphization* is a fancy name for a simple
2027 idea: generate a separate copy of each generic function at each call site,
2028 a copy that is specialized to the argument
2029 types and can thus be optimized specifically for them. In this
2030 respect, Rust's generics have similar performance characteristics to
2031 C++ templates.
2032
2033 ## Traits
2034
2035 Within a generic function—that is, a function parameterized by a
2036 type parameter, say, `T`—the operations we can do on arguments of
2037 type `T` are quite limited.  After all, since we don't know what type
2038 `T` will be instantiated with, we can't safely modify or query values
2039 of type `T`.  This is where _traits_ come into play. Traits are Rust's
2040 most powerful tool for writing polymorphic code. Java developers will
2041 see them as similar to Java interfaces, and Haskellers will notice
2042 their similarities to type classes. Rust's traits give us a way to
2043 express *bounded polymorphism*: by limiting the set of possible types
2044 that a type parameter could refer to, they expand the number of
2045 operations we can safely perform on arguments of that type.
2046
2047 As motivation, let us consider copying of values in Rust.  The `clone`
2048 method is not defined for values of every type.  One reason is
2049 user-defined destructors: copying a value of a type that has a
2050 destructor could result in the destructor running multiple times.
2051 Therefore, values of types that have destructors cannot be copied
2052 unless we explicitly implement `clone` for them.
2053
2054 This complicates handling of generic functions.
2055 If we have a function with a type parameter `T`,
2056 can we copy values of type `T` inside that function?
2057 In Rust, we can't,
2058 and if we try to run the following code the compiler will complain.
2059
2060 ~~~~ {.ignore}
2061 // This does not compile
2062 fn head_bad<T>(v: &[T]) -> T {
2063     v[0] // error: copying a non-copyable value
2064 }
2065 ~~~~
2066
2067 However, we can tell the compiler
2068 that the `head` function is only for copyable types.
2069 In Rust, copyable types are those that _implement the `Clone` trait_.
2070 We can then explicitly create a second copy of the value we are returning
2071 by calling the `clone` method:
2072
2073 ~~~~
2074 // This does
2075 fn head<T: Clone>(v: &[T]) -> T {
2076     v[0].clone()
2077 }
2078 ~~~~
2079
2080 The bounded type parameter `T: Clone` says that `head`
2081 can be called on an argument of type `&[T]` for any `T`,
2082 so long as there is an implementation of the
2083 `Clone` trait for `T`.
2084 When instantiating a generic function,
2085 we can only instantiate it with types
2086 that implement the correct trait,
2087 so we could not apply `head` to a vector whose elements are of some type
2088 that does not implement `Clone`.
2089
2090 While most traits can be defined and implemented by user code,
2091 three traits are automatically derived and implemented
2092 for all applicable types by the compiler,
2093 and may not be overridden:
2094
2095 * `Send` - Sendable types.
2096 Types are sendable
2097 unless they contain managed boxes, managed closures, or references.
2098
2099 * `Share` - Types that are *threadsafe*
2100 These are types that are safe to be used across several threads with access to
2101 a `&T` pointer. `MutexArc` is an example of a *sharable* type with internal mutable data.
2102
2103 * `'static` - Non-borrowed types.
2104 These are types that do not contain any data whose lifetime is bound to
2105 a particular stack frame. These are types that do not contain any
2106 references, or types where the only contained references
2107 have the `'static` lifetime. (For more on named lifetimes and their uses,
2108 see the [references and lifetimes guide][lifetimes].)
2109
2110 > ***Note:*** These built-in traits were referred to as 'kinds' in earlier
2111 > iterations of the language, and often still are.
2112
2113 Additionally, the `Drop` trait is used to define destructors. This
2114 trait provides one method called `drop`, which is automatically
2115 called when a value of the type that implements this trait is
2116 destroyed, either because the value went out of scope or because the
2117 garbage collector reclaimed it.
2118
2119 ~~~
2120 struct TimeBomb {
2121     explosivity: uint
2122 }
2123
2124 impl Drop for TimeBomb {
2125     fn drop(&mut self) {
2126         for _ in range(0, self.explosivity) {
2127             println!("blam!");
2128         }
2129     }
2130 }
2131 ~~~
2132
2133 It is illegal to call `drop` directly. Only code inserted by the compiler
2134 may call it.
2135
2136 ## Declaring and implementing traits
2137
2138 At its simplest, a trait is a set of zero or more _method signatures_.
2139 For example, we could declare the trait
2140 `Printable` for things that can be printed to the console,
2141 with a single method signature:
2142
2143 ~~~~
2144 trait Printable {
2145     fn print(&self);
2146 }
2147 ~~~~
2148
2149 We say that the `Printable` trait _provides_ a `print` method with the
2150 given signature.  This means that we can call `print` on an argument
2151 of any type that implements the `Printable` trait.
2152
2153 Rust's built-in `Send` and `Share` types are examples of traits that
2154 don't provide any methods.
2155
2156 Traits may be implemented for specific types with [impls]. An impl for
2157 a particular trait gives an implementation of the methods that
2158 trait provides.  For instance, the following impls of
2159 `Printable` for `int` and `~str` give implementations of the `print`
2160 method.
2161
2162 [impls]: #methods
2163
2164 ~~~~
2165 # trait Printable { fn print(&self); }
2166 impl Printable for int {
2167     fn print(&self) { println!("{:?}", *self) }
2168 }
2169
2170 impl Printable for ~str {
2171     fn print(&self) { println!("{}", *self) }
2172 }
2173
2174 # 1.print();
2175 # (~"foo").print();
2176 ~~~~
2177
2178 Methods defined in an impl for a trait may be called just like
2179 any other method, using dot notation, as in `1.print()`.
2180
2181 ## Default method implementations in trait definitions
2182
2183 Sometimes, a method that a trait provides will have the same
2184 implementation for most or all of the types that implement that trait.
2185 For instance, suppose that we wanted `bool`s and `f32`s to be
2186 printable, and that we wanted the implementation of `print` for those
2187 types to be exactly as it is for `int`, above:
2188
2189 ~~~~
2190 # trait Printable { fn print(&self); }
2191 impl Printable for f32 {
2192     fn print(&self) { println!("{:?}", *self) }
2193 }
2194
2195 impl Printable for bool {
2196     fn print(&self) { println!("{:?}", *self) }
2197 }
2198
2199 # true.print();
2200 # 3.14159.print();
2201 ~~~~
2202
2203 This works fine, but we've now repeated the same definition of `print`
2204 in three places.  Instead of doing that, we can simply include the
2205 definition of `print` right in the trait definition, instead of just
2206 giving its signature.  That is, we can write the following:
2207
2208 ~~~~
2209 trait Printable {
2210         // Default method implementation
2211     fn print(&self) { println!("{:?}", *self) }
2212 }
2213
2214 impl Printable for int {}
2215
2216 impl Printable for ~str {
2217     fn print(&self) { println!("{}", *self) }
2218 }
2219
2220 impl Printable for bool {}
2221
2222 impl Printable for f32 {}
2223
2224 # 1.print();
2225 # (~"foo").print();
2226 # true.print();
2227 # 3.14159.print();
2228 ~~~~
2229
2230 Here, the impls of `Printable` for `int`, `bool`, and `f32` don't
2231 need to provide an implementation of `print`, because in the absence
2232 of a specific implementation, Rust just uses the _default method_
2233 provided in the trait definition.  Depending on the trait, default
2234 methods can save a great deal of boilerplate code from having to be
2235 written in impls.  Of course, individual impls can still override the
2236 default method for `print`, as is being done above in the impl for
2237 `~str`.
2238
2239 ## Type-parameterized traits
2240
2241 Traits may be parameterized by type variables.  For example, a trait
2242 for generalized sequence types might look like the following:
2243
2244 ~~~~
2245 trait Seq<T> {
2246     fn length(&self) -> uint;
2247 }
2248
2249 impl<T> Seq<T> for ~[T] {
2250     fn length(&self) -> uint { self.len() }
2251 }
2252 ~~~~
2253
2254 The implementation has to explicitly declare the type parameter that
2255 it binds, `T`, before using it to specify its trait type. Rust
2256 requires this declaration because the `impl` could also, for example,
2257 specify an implementation of `Seq<int>`. The trait type (appearing
2258 between `impl` and `for`) *refers* to a type, rather than
2259 defining one.
2260
2261 The type parameters bound by a trait are in scope in each of the
2262 method declarations. So, re-declaring the type parameter
2263 `T` as an explicit type parameter for `len`, in either the trait or
2264 the impl, would be a compile-time error.
2265
2266 Within a trait definition, `Self` is a special type that you can think
2267 of as a type parameter. An implementation of the trait for any given
2268 type `T` replaces the `Self` type parameter with `T`. The following
2269 trait describes types that support an equality operation:
2270
2271 ~~~~
2272 // In a trait, `self` refers to the self argument.
2273 // `Self` refers to the type implementing the trait.
2274 trait Eq {
2275     fn equals(&self, other: &Self) -> bool;
2276 }
2277
2278 // In an impl, `self` refers just to the value of the receiver
2279 impl Eq for int {
2280     fn equals(&self, other: &int) -> bool { *other == *self }
2281 }
2282 ~~~~
2283
2284 Notice that in the trait definition, `equals` takes a
2285 second parameter of type `Self`.
2286 In contrast, in the `impl`, `equals` takes a second parameter of
2287 type `int`, only using `self` as the name of the receiver.
2288
2289 Just as in type implementations, traits can define standalone (static)
2290 methods.  These methods are called by prefixing the method name with the trait
2291 name and a double colon.  The compiler uses type inference to decide which
2292 implementation to use.
2293
2294 ~~~~
2295 use std::f64::consts::PI;
2296 trait Shape { fn new(area: f64) -> Self; }
2297 struct Circle { radius: f64 }
2298 struct Square { length: f64 }
2299
2300 impl Shape for Circle {
2301     fn new(area: f64) -> Circle { Circle { radius: (area / PI).sqrt() } }
2302 }
2303 impl Shape for Square {
2304     fn new(area: f64) -> Square { Square { length: area.sqrt() } }
2305 }
2306
2307 let area = 42.5;
2308 let c: Circle = Shape::new(area);
2309 let s: Square = Shape::new(area);
2310 ~~~~
2311
2312 ## Bounded type parameters and static method dispatch
2313
2314 Traits give us a language for defining predicates on types, or
2315 abstract properties that types can have. We can use this language to
2316 define _bounds_ on type parameters, so that we can then operate on
2317 generic types.
2318
2319 ~~~~
2320 # trait Printable { fn print(&self); }
2321 fn print_all<T: Printable>(printable_things: ~[T]) {
2322     for thing in printable_things.iter() {
2323         thing.print();
2324     }
2325 }
2326 ~~~~
2327
2328 Declaring `T` as conforming to the `Printable` trait (as we earlier
2329 did with `Clone`) makes it possible to call methods from that trait
2330 on values of type `T` inside the function. It will also cause a
2331 compile-time error when anyone tries to call `print_all` on an array
2332 whose element type does not have a `Printable` implementation.
2333
2334 Type parameters can have multiple bounds by separating them with `+`,
2335 as in this version of `print_all` that copies elements.
2336
2337 ~~~
2338 # trait Printable { fn print(&self); }
2339 fn print_all<T: Printable + Clone>(printable_things: ~[T]) {
2340     let mut i = 0;
2341     while i < printable_things.len() {
2342         let copy_of_thing = printable_things[i].clone();
2343         copy_of_thing.print();
2344         i += 1;
2345     }
2346 }
2347 ~~~
2348
2349 Method calls to bounded type parameters are _statically dispatched_,
2350 imposing no more overhead than normal function invocation, so are
2351 the preferred way to use traits polymorphically.
2352
2353 This usage of traits is similar to Haskell type classes.
2354
2355 ## Trait objects and dynamic method dispatch
2356
2357 The above allows us to define functions that polymorphically act on
2358 values of a single unknown type that conforms to a given trait.
2359 However, consider this function:
2360
2361 ~~~~
2362 # type Circle = int; type Rectangle = int;
2363 # impl Drawable for int { fn draw(&self) {} }
2364 # fn new_circle() -> int { 1 }
2365 trait Drawable { fn draw(&self); }
2366
2367 fn draw_all<T: Drawable>(shapes: ~[T]) {
2368     for shape in shapes.iter() { shape.draw(); }
2369 }
2370 # let c: Circle = new_circle();
2371 # draw_all(~[c]);
2372 ~~~~
2373
2374 You can call that on an array of circles, or an array of rectangles
2375 (assuming those have suitable `Drawable` traits defined), but not on
2376 an array containing both circles and rectangles. When such behavior is
2377 needed, a trait name can alternately be used as a type, called
2378 an _object_.
2379
2380 ~~~~
2381 # trait Drawable { fn draw(&self); }
2382 fn draw_all(shapes: &[~Drawable]) {
2383     for shape in shapes.iter() { shape.draw(); }
2384 }
2385 ~~~~
2386
2387 In this example, there is no type parameter. Instead, the `~Drawable`
2388 type denotes any owned box value that implements the `Drawable` trait.
2389 To construct such a value, you use the `as` operator to cast a value
2390 to an object:
2391
2392 ~~~~
2393 # type Circle = int; type Rectangle = bool;
2394 # trait Drawable { fn draw(&self); }
2395 # fn new_circle() -> Circle { 1 }
2396 # fn new_rectangle() -> Rectangle { true }
2397 # fn draw_all(shapes: &[~Drawable]) {}
2398
2399 impl Drawable for Circle { fn draw(&self) { /* ... */ } }
2400 impl Drawable for Rectangle { fn draw(&self) { /* ... */ } }
2401
2402 let c: ~Circle = ~new_circle();
2403 let r: ~Rectangle = ~new_rectangle();
2404 draw_all([c as ~Drawable, r as ~Drawable]);
2405 ~~~~
2406
2407 We omit the code for `new_circle` and `new_rectangle`; imagine that
2408 these just return `Circle`s and `Rectangle`s with a default size. Note
2409 that, like strings and vectors, objects have dynamic size and may
2410 only be referred to via one of the pointer types.
2411 Other pointer types work as well.
2412 Casts to traits may only be done with compatible pointers so,
2413 for example, an `@Circle` may not be cast to an `~Drawable`.
2414
2415 ~~~
2416 # type Circle = int; type Rectangle = int;
2417 # trait Drawable { fn draw(&self); }
2418 # impl Drawable for int { fn draw(&self) {} }
2419 # fn new_circle() -> int { 1 }
2420 # fn new_rectangle() -> int { 2 }
2421 // An owned object
2422 let owny: ~Drawable = ~new_circle() as ~Drawable;
2423 // A borrowed object
2424 let stacky: &Drawable = &new_circle() as &Drawable;
2425 ~~~
2426
2427 Method calls to trait types are _dynamically dispatched_. Since the
2428 compiler doesn't know specifically which functions to call at compile
2429 time, it uses a lookup table (also known as a vtable or dictionary) to
2430 select the method to call at runtime.
2431
2432 This usage of traits is similar to Java interfaces.
2433
2434 There are some built-in bounds, such as `Send` and `Share`, which are properties
2435 of the components of types. By design, trait objects don't know the exact type
2436 of their contents and so the compiler cannot reason about those properties.
2437
2438 You can instruct the compiler, however, that the contents of a trait object must
2439 acribe to a particular bound with a trailing colon (`:`). These are examples of
2440 valid types:
2441
2442 ~~~rust
2443 trait Foo {}
2444 trait Bar<T> {}
2445
2446 fn sendable_foo(f: ~Foo:Send) { /* ... */ }
2447 fn shareable_bar<T: Share>(b: &Bar<T>: Share) { /* ... */ }
2448 ~~~
2449
2450 When no colon is specified (such as the type `~Foo`), it is inferred that the
2451 value ascribes to no bounds. They must be added manually if any bounds are
2452 necessary for usage.
2453
2454 Builtin kind bounds can also be specified on closure types in the same way (for
2455 example, by writing `fn:Send()`), and the default behaviours are the same as
2456 for traits of the same storage class.
2457
2458 ## Trait inheritance
2459
2460 We can write a trait declaration that _inherits_ from other traits, called _supertraits_.
2461 Types that implement a trait must also implement its supertraits.
2462 For example,
2463 we can define a `Circle` trait that inherits from `Shape`.
2464
2465 ~~~~
2466 trait Shape { fn area(&self) -> f64; }
2467 trait Circle : Shape { fn radius(&self) -> f64; }
2468 ~~~~
2469
2470 Now, we can implement `Circle` on a type only if we also implement `Shape`.
2471
2472 ~~~~
2473 use std::f64::consts::PI;
2474 # trait Shape { fn area(&self) -> f64; }
2475 # trait Circle : Shape { fn radius(&self) -> f64; }
2476 # struct Point { x: f64, y: f64 }
2477 # fn square(x: f64) -> f64 { x * x }
2478 struct CircleStruct { center: Point, radius: f64 }
2479 impl Circle for CircleStruct {
2480     fn radius(&self) -> f64 { (self.area() / PI).sqrt() }
2481 }
2482 impl Shape for CircleStruct {
2483     fn area(&self) -> f64 { PI * square(self.radius) }
2484 }
2485 ~~~~
2486
2487 Notice that methods of `Circle` can call methods on `Shape`, as our
2488 `radius` implementation calls the `area` method.
2489 This is a silly way to compute the radius of a circle
2490 (since we could just return the `radius` field), but you get the idea.
2491
2492 In type-parameterized functions,
2493 methods of the supertrait may be called on values of subtrait-bound type parameters.
2494 Refering to the previous example of `trait Circle : Shape`:
2495
2496 ~~~
2497 # trait Shape { fn area(&self) -> f64; }
2498 # trait Circle : Shape { fn radius(&self) -> f64; }
2499 fn radius_times_area<T: Circle>(c: T) -> f64 {
2500     // `c` is both a Circle and a Shape
2501     c.radius() * c.area()
2502 }
2503 ~~~
2504
2505 Likewise, supertrait methods may also be called on trait objects.
2506
2507 ~~~ {.ignore}
2508 use std::f64::consts::PI;
2509 # trait Shape { fn area(&self) -> f64; }
2510 # trait Circle : Shape { fn radius(&self) -> f64; }
2511 # struct Point { x: f64, y: f64 }
2512 # struct CircleStruct { center: Point, radius: f64 }
2513 # impl Circle for CircleStruct { fn radius(&self) -> f64 { (self.area() / PI).sqrt() } }
2514 # impl Shape for CircleStruct { fn area(&self) -> f64 { PI * square(self.radius) } }
2515
2516 let concrete = @CircleStruct{center:Point{x:3.0,y:4.0},radius:5.0};
2517 let mycircle: @Circle = concrete as @Circle;
2518 let nonsense = mycircle.radius() * mycircle.area();
2519 ~~~
2520
2521 > ***Note:*** Trait inheritance does not actually work with objects yet
2522
2523 ## Deriving implementations for traits
2524
2525 A small number of traits in `std` and `extra` can have implementations
2526 that can be automatically derived. These instances are specified by
2527 placing the `deriving` attribute on a data type declaration. For
2528 example, the following will mean that `Circle` has an implementation
2529 for `Eq` and can be used with the equality operators, and that a value
2530 of type `ABC` can be randomly generated and converted to a string:
2531
2532 ~~~
2533 #[deriving(Eq)]
2534 struct Circle { radius: f64 }
2535
2536 #[deriving(Clone, Show)]
2537 enum ABC { A, B, C }
2538 ~~~
2539
2540 The full list of derivable traits is `Eq`, `TotalEq`, `Ord`,
2541 `TotalOrd`, `Encodable` `Decodable`, `Clone`,
2542 `Hash`, `Rand`, `Default`, `Zero`, `FromPrimitive` and `Show`.
2543
2544 # Crates and the module system
2545
2546 Rust's module system is very powerful, but because of that also somewhat complex.
2547 Nevertheless, this section will try to explain every important aspect of it.
2548
2549 ## Crates
2550
2551 In order to speak about the module system, we first need to define the medium it exists in:
2552
2553 Let's say you've written a program or a library, compiled it, and got the resulting binary.
2554 In Rust, the content of all source code that the compiler directly had to compile in order to end up with
2555 that binary is collectively called a 'crate'.
2556
2557 For example, for a simple hello world program your crate only consists of this code:
2558
2559 ~~~~
2560 // `main.rs`
2561 fn main() {
2562     println!("Hello world!");
2563 }
2564 ~~~~
2565
2566 A crate is also the unit of independent compilation in Rust: `rustc` always compiles a single crate at a time,
2567 from which it produces either a library or an executable.
2568
2569 Note that merely using an already compiled library in your code does not make it part of your crate.
2570
2571 ## The module hierarchy
2572
2573 For every crate, all the code in it is arranged in a hierarchy of modules starting with a single
2574 root module. That root module is called the 'crate root'.
2575
2576 All modules in a crate below the crate root are declared with the `mod` keyword:
2577
2578 ~~~~
2579 // This is the crate root
2580
2581 mod farm {
2582     // This is the body of module 'farm' declared in the crate root.
2583
2584     fn chicken() { println!("cluck cluck"); }
2585     fn cow() { println!("mooo"); }
2586
2587     mod barn {
2588         // Body of module 'barn'
2589
2590         fn hay() { println!("..."); }
2591     }
2592 }
2593
2594 fn main() {
2595     println!("Hello farm!");
2596 }
2597 ~~~~
2598
2599 As you can see, your module hierarchy is now three modules deep: There is the crate root, which contains your `main()`
2600 function, and the module `farm`. The module `farm` also contains two functions and a third module `barn`,
2601 which contains a function `hay`.
2602
2603 ## Paths and visibility
2604
2605 We've now defined a nice module hierarchy. But how do we access the items in it from our `main` function?
2606 One way to do it is to simply fully qualifying it:
2607
2608 ~~~~ {.ignore}
2609 mod farm {
2610     fn chicken() { println!("cluck cluck"); }
2611     // ...
2612 }
2613
2614 fn main() {
2615     println!("Hello chicken!");
2616
2617     ::farm::chicken(); // Won't compile yet, see further down
2618 }
2619 ~~~~
2620
2621 The `::farm::chicken` construct is what we call a 'path'.
2622
2623 Because it's starting with a `::`, it's also a 'global path', which qualifies
2624 an item by its full path in the module hierarchy relative to the crate root.
2625
2626 If the path were to start with a regular identifier, like `farm::chicken`, it
2627 would be a 'local path' instead. We'll get to them later.
2628
2629 Now, if you actually tried to compile this code example, you'll notice that you
2630 get a `function 'chicken' is private` error. That's because by default, items
2631 (`fn`, `struct`, `static`, `mod`, ...) are private.
2632
2633 To make them visible outside their containing modules, you need to mark them
2634 _public_ with `pub`:
2635
2636 ~~~~
2637 mod farm {
2638     pub fn chicken() { println!("cluck cluck"); }
2639     pub fn cow() { println!("mooo"); }
2640     // ...
2641 }
2642
2643 fn main() {
2644     println!("Hello chicken!");
2645     ::farm::chicken(); // This compiles now
2646 }
2647 ~~~~
2648
2649 Visibility restrictions in Rust exist only at module boundaries. This
2650 is quite different from most object-oriented languages that also
2651 enforce restrictions on objects themselves. That's not to say that
2652 Rust doesn't support encapsulation: both struct fields and methods can
2653 be private. But this encapsulation is at the module level, not the
2654 struct level.
2655
2656 Fields are _private_ by default, and can be made _public_ with
2657 the `pub` keyword:
2658
2659 ~~~
2660 mod farm {
2661 # pub type Chicken = int;
2662 # struct Human(int);
2663 # impl Human { pub fn rest(&self) { } }
2664 # pub fn make_me_a_farm() -> Farm { Farm { chickens: ~[], farmer: Human(0) } }
2665     pub struct Farm {
2666         chickens: ~[Chicken],
2667         pub farmer: Human
2668     }
2669
2670     impl Farm {
2671         fn feed_chickens(&self) { /* ... */ }
2672         pub fn add_chicken(&self, c: Chicken) { /* ... */ }
2673     }
2674
2675     pub fn feed_animals(farm: &Farm) {
2676         farm.feed_chickens();
2677     }
2678 }
2679
2680 fn main() {
2681     let f = make_me_a_farm();
2682     f.add_chicken(make_me_a_chicken());
2683     farm::feed_animals(&f);
2684     f.farmer.rest();
2685
2686     // This wouldn't compile because both are private:
2687     // `f.feed_chickens();`
2688     // `let chicken_counter = f.chickens.len();`
2689 }
2690 # fn make_me_a_farm() -> farm::Farm { farm::make_me_a_farm() }
2691 # fn make_me_a_chicken() -> farm::Chicken { 0 }
2692 ~~~
2693
2694 Exact details and specifications about visibility rules can be found in the Rust
2695 manual.
2696
2697 ## Files and modules
2698
2699 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.
2700
2701 The only file that's relevant when compiling is the one that contains the body
2702 of your crate root, and it's only relevant because you have to pass that file
2703 to `rustc` to compile your crate.
2704
2705 In principle, that's all you need: You can write any Rust program as one giant source file that contains your
2706 crate root and everything else in `mod ... { ... }` declarations.
2707
2708 However, in practice you usually want to split up your code into multiple
2709 source files to make it more manageable. Rust allows you to move the body of
2710 any module into its own source file. If you declare a module without its body,
2711 like `mod foo;`, the compiler will look for the files `foo.rs` and `foo/mod.rs`
2712 inside some directory (usually the same as of the source file containing the
2713 `mod foo;` declaration). If it finds either, it uses the content of that file
2714 as the body of the module. If it finds both, that's a compile error.
2715
2716 To move the content of `mod farm` into its own file, you can write:
2717
2718 ~~~~ {.ignore}
2719 // `main.rs` - contains body of the crate root
2720 mod farm; // Compiler will look for `farm.rs` and `farm/mod.rs`
2721
2722 fn main() {
2723     println!("Hello farm!");
2724     ::farm::cow();
2725 }
2726 ~~~~
2727
2728 ~~~~
2729 // `farm.rs` - contains body of module 'farm' in the crate root
2730 pub fn chicken() { println!("cluck cluck"); }
2731 pub fn cow() { println!("mooo"); }
2732
2733 pub mod barn {
2734     pub fn hay() { println!("..."); }
2735 }
2736 # fn main() { }
2737 ~~~~
2738
2739 In short, `mod foo;` is just syntactic sugar for `mod foo { /* content of <...>/foo.rs or <...>/foo/mod.rs */ }`.
2740
2741 This also means that having two or more identical `mod foo;` declarations
2742 somewhere in your crate hierarchy is generally a bad idea,
2743 just like copy-and-paste-ing a module into multiple places is a bad idea.
2744 Both will result in duplicate and mutually incompatible definitions.
2745
2746 When `rustc` resolves these module declarations, it starts by looking in the
2747 parent directory of the file containing the `mod foo` declaration. For example,
2748 given a file with the module body:
2749
2750 ~~~ {.ignore}
2751 // `src/main.rs`
2752 mod plants;
2753 mod animals {
2754     mod fish;
2755     mod mammals {
2756         mod humans;
2757     }
2758 }
2759 ~~~
2760
2761 The compiler will look for these files, in this order:
2762
2763 ~~~ {.notrust}
2764 src/plants.rs
2765 src/plants/mod.rs
2766
2767 src/animals/fish.rs
2768 src/animals/fish/mod.rs
2769
2770 src/animals/mammals/humans.rs
2771 src/animals/mammals/humans/mod.rs
2772 ~~~
2773
2774 Keep in mind that identical module hierarchies can still lead to different path
2775 lookups depending on how and where you've moved a module body to its own file.
2776 For example, if you move the `animals` module into its own file:
2777
2778 ~~~ {.ignore}
2779 // `src/main.rs`
2780 mod plants;
2781 mod animals;
2782 ~~~
2783
2784 ~~~ {.ignore}
2785 // `src/animals.rs` or `src/animals/mod.rs`
2786 mod fish;
2787 mod mammals {
2788     mod humans;
2789 }
2790 ~~~
2791
2792 ...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:
2793
2794 ~~~ {.notrust}
2795 src/animals.rs
2796     src/fish.rs
2797     src/fish/mod.rs
2798
2799     src/mammals/humans.rs
2800     src/mammals/humans/mod.rs
2801 ~~~
2802
2803 If the animals file is `src/animals/mod.rs`, `rustc` will look for:
2804
2805 ~~~ {.notrust}
2806 src/animals/mod.rs
2807     src/animals/fish.rs
2808     src/animals/fish/mod.rs
2809
2810     src/animals/mammals/humans.rs
2811     src/animals/mammals/humans/mod.rs
2812
2813 ~~~
2814
2815 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.
2816
2817 If you need to override where `rustc` will look for the file containing a
2818 module's source code, use the `path` compiler directive. For example, to load a
2819 `classified` module from a different file:
2820
2821 ~~~ {.ignore}
2822 #[path="../../area51/alien.rs"]
2823 mod classified;
2824 ~~~
2825
2826 ## Importing names into the local scope
2827
2828 Always referring to definitions in other modules with their global
2829 path gets old really fast, so Rust has a way to import
2830 them into the local scope of your module: `use`-statements.
2831
2832 They work like this: At the beginning of any module body, `fn` body, or any other block
2833 you can write a list of `use`-statements, consisting of the keyword `use` and a __global path__ to an item
2834 without the `::` prefix. For example, this imports `cow` into the local scope:
2835
2836 ~~~
2837 use farm::cow;
2838 # mod farm { pub fn cow() { println!("I'm a hidden ninja cow!") } }
2839 # fn main() { cow() }
2840 ~~~
2841
2842 The path you give to `use` is per default global, meaning relative to the crate root,
2843 no matter how deep the module hierarchy is, or whether the module body it's written in
2844 is contained in its own file. (Remember: files are irrelevant.)
2845
2846 This is different from other languages, where you often only find a single import construct that combines the semantic
2847 of `mod foo;` and `use`-statements, and which tend to work relative to the source file or use an absolute file path
2848 - Ruby's `require` or C/C++'s `#include` come to mind.
2849
2850 However, it's also possible to import things relative to the module of the `use`-statement:
2851 Adding a `super::` in front of the path will start in the parent module,
2852 while adding a `self::` prefix will start in the current module:
2853
2854 ~~~
2855 # mod workaround {
2856 # pub fn some_parent_item(){ println!("...") }
2857 # mod foo {
2858 use super::some_parent_item;
2859 use self::some_child_module::some_item;
2860 # pub fn bar() { some_parent_item(); some_item() }
2861 # pub mod some_child_module { pub fn some_item() {} }
2862 # }
2863 # }
2864 ~~~
2865
2866 Again - relative to the module, not to the file.
2867
2868 Imports are also shadowed by local definitions:
2869 For each name you mention in a module/block, `rust`
2870 will first look at all items that are defined locally,
2871 and only if that results in no match look at items you brought in
2872 scope with corresponding `use` statements.
2873
2874 ~~~ {.ignore}
2875 # // FIXME: Allow unused import in doc test
2876 use farm::cow;
2877 // ...
2878 # mod farm { pub fn cow() { println!("Hidden ninja cow is hidden.") } }
2879 fn cow() { println!("Mooo!") }
2880
2881 fn main() {
2882     cow() // resolves to the locally defined `cow()` function
2883 }
2884 ~~~
2885
2886 To make this behavior more obvious, the rule has been made that `use`-statement always need to be written
2887 before any declaration, like in the example above. This is a purely artificial rule introduced
2888 because people always assumed they shadowed each other based on order, despite the fact that all items in rust are
2889 mutually recursive, order independent definitions.
2890
2891 One odd consequence of that rule is that `use` statements also go in front of any `mod` declaration,
2892 even if they refer to things inside them:
2893
2894 ~~~
2895 use farm::cow;
2896 mod farm {
2897     pub fn cow() { println!("Moooooo?") }
2898 }
2899
2900 fn main() { cow() }
2901 ~~~
2902
2903 This is what our `farm` example looks like with `use` statements:
2904
2905 ~~~~
2906 use farm::chicken;
2907 use farm::cow;
2908 use farm::barn;
2909
2910 mod farm {
2911     pub fn chicken() { println!("cluck cluck"); }
2912     pub fn cow() { println!("mooo"); }
2913
2914     pub mod barn {
2915         pub fn hay() { println!("..."); }
2916     }
2917 }
2918
2919 fn main() {
2920     println!("Hello farm!");
2921
2922     // Can now refer to those names directly:
2923     chicken();
2924     cow();
2925     barn::hay();
2926 }
2927 ~~~~
2928
2929 And here an example with multiple files:
2930
2931 ~~~{.ignore}
2932 // `a.rs` - crate root
2933 use b::foo;
2934 mod b;
2935 fn main() { foo(); }
2936 ~~~
2937
2938 ~~~{.ignore}
2939 // `b.rs`
2940 use b::c::bar;
2941 pub mod c;
2942 pub fn foo() { bar(); }
2943 ~~~
2944
2945 ~~~
2946 // `c.rs`
2947 pub fn bar() { println!("Baz!"); }
2948 # fn main() {}
2949 ~~~
2950
2951 There also exist two short forms for importing multiple names at once:
2952
2953 1. Explicit mention multiple names as the last element of an `use` path:
2954
2955 ~~~
2956 use farm::{chicken, cow};
2957 # mod farm {
2958 #     pub fn cow() { println!("Did I already mention how hidden and ninja I am?") }
2959 #     pub fn chicken() { println!("I'm Bat-chicken, guardian of the hidden tutorial code.") }
2960 # }
2961 # fn main() { cow(); chicken() }
2962 ~~~
2963
2964 2. Import everything in a module with a wildcard:
2965
2966 ~~~
2967 use farm::*;
2968 # mod farm {
2969 #     pub fn cow() { println!("Bat-chicken? What a stupid name!") }
2970 #     pub fn chicken() { println!("Says the 'hidden ninja' cow.") }
2971 # }
2972 # fn main() { cow(); chicken() }
2973 ~~~
2974
2975 > ***Note:*** This feature of the compiler is currently gated behind the
2976 > `#[feature(globs)]` directive. More about these directives can be found in
2977 > the manual.
2978
2979 However, that's not all. You can also rename an item while you're bringing it into scope:
2980
2981 ~~~
2982 use egg_layer = farm::chicken;
2983 # mod farm { pub fn chicken() { println!("Laying eggs is fun!")  } }
2984 // ...
2985
2986 fn main() {
2987     egg_layer();
2988 }
2989 ~~~
2990
2991 In general, `use` creates an local alias:
2992 An alternate path and a possibly different name to access the same item,
2993 without touching the original, and with both being interchangeable.
2994
2995 ## Reexporting names
2996
2997 It is also possible to reexport items to be accessible under your module.
2998
2999 For that, you write `pub use`:
3000
3001 ~~~
3002 mod farm {
3003     pub use self::barn::hay;
3004
3005     pub fn chicken() { println!("cluck cluck"); }
3006     pub fn cow() { println!("mooo"); }
3007
3008     mod barn {
3009         pub fn hay() { println!("..."); }
3010     }
3011 }
3012
3013 fn main() {
3014     farm::chicken();
3015     farm::cow();
3016     farm::hay();
3017 }
3018 ~~~
3019
3020 Just like in normal `use` statements, the exported names
3021 merely represent an alias to the same thing and can also be renamed.
3022
3023 The above example also demonstrate what you can use `pub use` for:
3024 The nested `barn` module is private, but the `pub use` allows users
3025 of the module `farm` to access a function from `barn` without needing
3026 to know that `barn` exists.
3027
3028 In other words, you can use it to decouple a public api from its internal implementation.
3029
3030 ## Using libraries
3031
3032 So far we've only talked about how to define and structure your own crate.
3033
3034 However, most code out there will want to use preexisting libraries,
3035 as there really is no reason to start from scratch each time you start a new project.
3036
3037 In Rust terminology, we need a way to refer to other crates.
3038
3039 For that, Rust offers you the `extern crate` declaration:
3040
3041 ~~~
3042 extern crate num;
3043 // `num` ships with Rust (much like `extra`; more details further down).
3044
3045 fn main() {
3046     // The rational number '1/2':
3047     let one_half = ::num::rational::Ratio::new(1, 2);
3048 }
3049 ~~~
3050
3051 A statement of the form `extern crate foo;` will cause `rustc` to search for the crate `foo`,
3052 and if it finds a matching binary it lets you use it from inside your crate.
3053
3054 The effect it has on your module hierarchy mirrors aspects of both `mod` and `use`:
3055
3056 - Like `mod`, it causes `rustc` to actually emit code:
3057   The linkage information the binary needs to use the library `foo`.
3058
3059 - But like `use`, all `extern crate` statements that refer to the same library are interchangeable,
3060   as each one really just presents an alias to an external module (the crate root of the library
3061   you're linking against).
3062
3063 Remember how `use`-statements have to go before local declarations because the latter shadows the former?
3064 Well, `extern crate` statements also have their own rules in that regard:
3065 Both `use` and local declarations can shadow them, so the rule is that `extern crate` has to go in front
3066 of both `use` and local declarations.
3067
3068 Which can result in something like this:
3069
3070 ~~~
3071 extern crate num;
3072
3073 use farm::dog;
3074 use num::rational::Ratio;
3075
3076 mod farm {
3077     pub fn dog() { println!("woof"); }
3078 }
3079
3080 fn main() {
3081     farm::dog();
3082     let a_third = Ratio::new(1, 3);
3083 }
3084 ~~~
3085
3086 It's a bit weird, but it's the result of shadowing rules that have been set that way because
3087 they model most closely what people expect to shadow.
3088
3089 ## Crate metadata and settings
3090
3091 For every crate you can define a number of metadata items, such as link name, version or author.
3092 You can also toggle settings that have crate-global consequences. Both mechanism
3093 work by providing attributes in the crate root.
3094
3095 For example, Rust uniquely identifies crates by their link metadata, which includes
3096 the link name and the version. It also hashes the filename and the symbols in a binary
3097 based on the link metadata, allowing you to use two different versions of the same library in a crate
3098 without conflict.
3099
3100 Therefore, if you plan to compile your crate as a library, you should annotate it with that information:
3101
3102 ~~~~
3103 // `lib.rs`
3104
3105 # #[crate_type = "lib"];
3106 #[crate_id = "farm#2.5"];
3107
3108 // ...
3109 # fn farm() {}
3110 ~~~~
3111
3112 You can also specify crate id information in a `extern crate` statement.  For
3113 example, these `extern crate` statements would both accept and select the
3114 crate define above:
3115
3116 ~~~~ {.ignore}
3117 extern crate farm;
3118 extern crate farm = "farm#2.5";
3119 extern crate my_farm = "farm";
3120 ~~~~
3121
3122 Other crate settings and metadata include things like enabling/disabling certain errors or warnings,
3123 or setting the crate type (library or executable) explicitly:
3124
3125 ~~~~
3126 // `lib.rs`
3127 // ...
3128
3129 // This crate is a library ("bin" is the default)
3130 #[crate_id = "farm#2.5"];
3131 #[crate_type = "lib"];
3132
3133 // Turn on a warning
3134 #[warn(non_camel_case_types)]
3135 # fn farm() {}
3136 ~~~~
3137
3138 ## A minimal example
3139
3140 Now for something that you can actually compile yourself.
3141
3142 We define two crates, and use one of them as a library in the other.
3143
3144 ~~~~
3145 // `world.rs`
3146 #[crate_id = "world#0.42"];
3147
3148 # mod secret_module_to_make_this_test_run {
3149 pub fn explore() -> &'static str { "world" }
3150 # }
3151 ~~~~
3152
3153 ~~~~ {.ignore}
3154 // `main.rs`
3155 extern crate world;
3156 fn main() { println!("hello {}", world::explore()); }
3157 ~~~~
3158
3159 Now compile and run like this (adjust to your platform if necessary):
3160
3161 ~~~~ {.notrust}
3162 > rustc --crate-type=lib world.rs  # compiles libworld-<HASH>-0.42.so
3163 > rustc main.rs -L .               # compiles main
3164 > ./main
3165 "hello world"
3166 ~~~~
3167
3168 Notice that the library produced contains the version in the file name
3169 as well as an inscrutable string of alphanumerics. As explained in the previous paragraph,
3170 these are both part of Rust's library versioning scheme. The alphanumerics are
3171 a hash representing the crate's id.
3172
3173 ## The standard library and the prelude
3174
3175 While reading the examples in this tutorial, you might have asked yourself where all
3176 those magical predefined items like `range` are coming from.
3177
3178 The truth is, there's nothing magical about them: They are all defined normally
3179 in the `std` library, which is a crate that ships with Rust.
3180
3181 The only magical thing that happens is that `rustc` automatically inserts this line into your crate root:
3182
3183 ~~~ {.ignore}
3184 extern crate std;
3185 ~~~
3186
3187 As well as this line into every module body:
3188
3189 ~~~ {.ignore}
3190 use std::prelude::*;
3191 ~~~
3192
3193 The role of the `prelude` module is to re-export common definitions from `std`.
3194
3195 This allows you to use common types and functions like `Option<T>` or `range`
3196 without needing to import them. And if you need something from `std` that's not in the prelude,
3197 you just have to import it with an `use` statement.
3198
3199 For example, it re-exports `range` which is defined in `std::iter::range`:
3200
3201 ~~~
3202 use iter_range = std::iter::range;
3203
3204 fn main() {
3205     // `range` is imported by default
3206     for _ in range(0, 10) {}
3207
3208     // Doesn't hinder you from importing it under a different name yourself
3209     for _ in iter_range(0, 10) {}
3210
3211     // Or from not using the automatic import.
3212     for _ in ::std::iter::range(0, 10) {}
3213 }
3214 ~~~
3215
3216 Both auto-insertions can be disabled with an attribute if necessary:
3217
3218 ~~~
3219 // In the crate root:
3220 #[no_std];
3221 ~~~
3222
3223 ~~~
3224 // In any module:
3225 #[no_implicit_prelude];
3226 ~~~
3227
3228 See the [API documentation][stddoc] for details.
3229
3230 [stddoc]: std/index.html
3231
3232 # What next?
3233
3234 Now that you know the essentials, check out any of the additional
3235 guides on individual topics.
3236
3237 * [Pointers][pointers]
3238 * [Lifetimes][lifetimes]
3239 * [Tasks and communication][tasks]
3240 * [Macros][macros]
3241 * [The foreign function interface][ffi]
3242 * [Containers and iterators][container]
3243 * [Documenting Rust code][rustdoc]
3244 * [Testing Rust code][testing]
3245 * [The Rust Runtime][runtime]
3246
3247 There is further documentation on the [wiki], however those tend to be even more out of date as this document.
3248
3249 [pointers]: guide-pointers.html
3250 [lifetimes]: guide-lifetimes.html
3251 [tasks]: guide-tasks.html
3252 [macros]: guide-macros.html
3253 [ffi]: guide-ffi.html
3254 [container]: guide-container.html
3255 [testing]: guide-testing.html
3256 [runtime]: guide-runtime.html
3257 [rustdoc]: rustdoc.html
3258 [wiki]: https://github.com/mozilla/rust/wiki/Docs
3259
3260 [wiki-packages]: https://github.com/mozilla/rust/wiki/Doc-packages,-editors,-and-other-tools