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