]> git.lizzy.rs Git - rust.git/blob - src/doc/guide.md
doc: remove incomplete sentence
[rust.git] / src / doc / guide.md
1 % The Rust Guide
2
3 Hey there! Welcome to the Rust guide. This is the place to be if you'd like to
4 learn how to program in Rust. Rust is a systems programming language with a
5 focus on "high-level, bare-metal programming": the lowest level control a
6 programming language can give you, but with zero-cost, higher level
7 abstractions, because people aren't computers. We really think Rust is
8 something special, and we hope you do too.
9
10 To show you how to get going with Rust, we're going to write the traditional
11 "Hello, World!" program. Next, we'll introduce you to a tool that's useful for
12 writing real-world Rust programs and libraries: "Cargo." After that, we'll talk
13 about the basics of Rust, write a little program to try them out, and then learn
14 more advanced things.
15
16 Sound good? Let's go!
17
18 # Installing Rust
19
20 The first step to using Rust is to install it! There are a number of ways to
21 install Rust, but the easiest is to use the `rustup` script. If you're on
22 Linux or a Mac, all you need to do is this (note that you don't need to type
23 in the `$`s, they just indicate the start of each command):
24
25 ```bash
26 curl -L https://static.rust-lang.org/rustup.sh | sudo sh
27 ```
28
29 If you're concerned about the [potential insecurity](http://curlpipesh.tumblr.com/) of using `curl | sudo sh`,
30 please keep reading and see our disclaimer below. And feel free to use a two-step version of the installation and examine our installation script:
31
32 ```bash
33 curl -L https://static.rust-lang.org/rustup.sh -O
34 sudo sh rustup.sh
35 ```
36
37 If you're on Windows, please download either the [32-bit
38 installer](https://static.rust-lang.org/dist/rust-nightly-i686-pc-windows-gnu.exe)
39 or the [64-bit
40 installer](https://static.rust-lang.org/dist/rust-nightly-x86_64-pc-windows-gnu.exe)
41 and run it.
42
43 If you decide you don't want Rust anymore, we'll be a bit sad, but that's okay.
44 Not every programming language is great for everyone. Just pass an argument to
45 the script:
46
47 ```bash
48 $ curl -s https://static.rust-lang.org/rustup.sh | sudo sh -s -- --uninstall
49 ```
50
51 If you used the Windows installer, just re-run the `.exe` and it will give you
52 an uninstall option.
53
54 You can re-run this script any time you want to update Rust. Which, at this
55 point, is often. Rust is still pre-1.0, and so people assume that you're using
56 a very recent Rust.
57
58 This brings me to one other point: some people, and somewhat rightfully so, get
59 very upset when we tell you to `curl | sudo sh`. And they should be! Basically,
60 when you do this, you are trusting that the good people who maintain Rust
61 aren't going to hack your computer and do bad things. That's a good instinct!
62 If you're one of those people, please check out the documentation on [building
63 Rust from Source](https://github.com/rust-lang/rust#building-from-source), or
64 [the official binary downloads](http://www.rust-lang.org/install.html). And we
65 promise that this method will not be the way to install Rust forever: it's just
66 the easiest way to keep people updated while Rust is in its alpha state.
67
68 Oh, we should also mention the officially supported platforms:
69
70 * Windows (7, 8, Server 2008 R2)
71 * Linux (2.6.18 or later, various distributions), x86 and x86-64
72 * OSX 10.7 (Lion) or greater, x86 and x86-64
73
74 We extensively test Rust on these platforms, and a few others, too, like
75 Android. But these are the ones most likely to work, as they have the most
76 testing.
77
78 Finally, a comment about Windows. Rust considers Windows to be a first-class
79 platform upon release, but if we're honest, the Windows experience isn't as
80 integrated as the Linux/OS X experience is. We're working on it! If anything
81 does not work, it is a bug. Please let us know if that happens. Each and every
82 commit is tested against Windows just like any other platform.
83
84 If you've got Rust installed, you can open up a shell, and type this:
85
86 ```bash
87 $ rustc --version
88 ```
89
90 You should see some output that looks something like this:
91
92 ```bash
93 rustc 0.12.0-nightly (b7aa03a3c 2014-09-28 11:38:01 +0000)
94 ```
95
96 If you did, Rust has been installed successfully! Congrats!
97
98 If not, there are a number of places where you can get help. The easiest is
99 [the #rust IRC channel on irc.mozilla.org](irc://irc.mozilla.org/#rust), which
100 you can access through
101 [Mibbit](http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust). Click
102 that link, and you'll be chatting with other Rustaceans (a silly nickname we
103 call ourselves), and we can help you out. Other great resources include [our
104 mailing list](https://mail.mozilla.org/listinfo/rust-dev), [the /r/rust
105 subreddit](http://www.reddit.com/r/rust), and [Stack
106 Overflow](http://stackoverflow.com/questions/tagged/rust).
107
108 # Hello, world!
109
110 Now that you have Rust installed, let's write your first Rust program. It's
111 traditional to make your first program in any new language one that prints the
112 text "Hello, world!" to the screen. The nice thing about starting with such a
113 simple program is that you can verify that your compiler isn't just installed,
114 but also working properly. And printing information to the screen is a pretty
115 common thing to do.
116
117 The first thing that we need to do is make a file to put our code in. I like
118 to make a `projects` directory in my home directory, and keep all my projects
119 there. Rust does not care where your code lives.
120
121 This actually leads to one other concern we should address: this guide will
122 assume that you have basic familiarity with the command line. Rust does not
123 require that you know a whole ton about the command line, but until the
124 language is in a more finished state, IDE support is spotty. Rust makes no
125 specific demands on your editing tooling, or where your code lives.
126
127 With that said, let's make a directory in our projects directory.
128
129 ```{bash}
130 $ mkdir ~/projects
131 $ cd ~/projects
132 $ mkdir hello_world
133 $ cd hello_world
134 ```
135
136 If you're on Windows and not using PowerShell, the `~` may not work. Consult
137 the documentation for your shell for more details.
138
139 Let's make a new source file next. I'm going to use the syntax `editor
140 filename` to represent editing a file in these examples, but you should use
141 whatever method you want. We'll call our file `main.rs`:
142
143 ```{bash}
144 $ editor main.rs
145 ```
146
147 Rust files always end in a `.rs` extension. If you're using more than one word
148 in your filename, use an underscore. `hello_world.rs` rather than
149 `helloworld.rs`.
150
151 Now that you've got your file open, type this in:
152
153 ```{rust}
154 fn main() {
155     println!("Hello, world!");
156 }
157 ```
158
159 Save the file, and then type this into your terminal window:
160
161 ```{bash}
162 $ rustc main.rs
163 $ ./main # or main.exe on Windows
164 Hello, world!
165 ```
166
167 You can also run these examples on [play.rust-lang.org](http://play.rust-lang.org/) by clicking on the arrow that appears in the upper right of the example when you mouse over the code.
168
169 Success! Let's go over what just happened in detail.
170
171 ```{rust}
172 fn main() {
173
174 }
175 ```
176
177 These lines define a **function** in Rust. The `main` function is special:
178 it's the beginning of every Rust program. The first line says "I'm declaring a
179 function named `main`, which takes no arguments and returns nothing." If there
180 were arguments, they would go inside the parentheses (`(` and `)`), and because
181 we aren't returning anything from this function, we've dropped that notation
182 entirely.  We'll get to it later.
183
184 You'll also note that the function is wrapped in curly braces (`{` and `}`).
185 Rust requires these around all function bodies. It is also considered good
186 style to put the opening curly brace on the same line as the function
187 declaration, with one space in between.
188
189 Next up is this line:
190
191 ```{rust}
192     println!("Hello, world!");
193 ```
194
195 This line does all of the work in our little program. There are a number of
196 details that are important here. The first is that it's indented with four
197 spaces, not tabs. Please configure your editor of choice to insert four spaces
198 with the tab key. We provide some [sample configurations for various
199 editors](https://github.com/rust-lang/rust/tree/master/src/etc).
200
201 The second point is the `println!()` part. This is calling a Rust **macro**,
202 which is how metaprogramming is done in Rust. If it were a function instead, it
203 would look like this: `println()`. For our purposes, we don't need to worry
204 about this difference. Just know that sometimes, you'll see a `!`, and that
205 means that you're calling a macro instead of a normal function. Rust implements
206 `println!` as a macro rather than a function for good reasons, but that's a
207 very advanced topic. You'll learn more when we talk about macros later. One
208 last thing to mention: Rust's macros are significantly different from C macros,
209 if you've used those. Don't be scared of using macros. We'll get to the details
210 eventually, you'll just have to trust us for now.
211
212 Next, `"Hello, world!"` is a **string**. Strings are a surprisingly complicated
213 topic in a systems programming language, and this is a **statically allocated**
214 string. We will talk more about different kinds of allocation later. We pass
215 this string as an argument to `println!`, which prints the string to the
216 screen. Easy enough!
217
218 Finally, the line ends with a semicolon (`;`). Rust is an **expression
219 oriented** language, which means that most things are expressions. The `;` is
220 used to indicate that this expression is over, and the next one is ready to
221 begin. Most lines of Rust code end with a `;`. We will cover this in-depth
222 later in the guide.
223
224 Finally, actually **compiling** and **running** our program. We can compile
225 with our compiler, `rustc`, by passing it the name of our source file:
226
227 ```{bash}
228 $ rustc main.rs
229 ```
230
231 This is similar to `gcc` or `clang`, if you come from a C or C++ background. Rust
232 will output a binary executable. You can see it with `ls`:
233
234 ```{bash}
235 $ ls
236 main  main.rs
237 ```
238
239 Or on Windows:
240
241 ```{bash}
242 $ dir
243 main.exe  main.rs
244 ```
245
246 There are now two files: our source code, with the `.rs` extension, and the
247 executable (`main.exe` on Windows, `main` everywhere else)
248
249 ```{bash}
250 $ ./main  # or main.exe on Windows
251 ```
252
253 This prints out our `Hello, world!` text to our terminal.
254
255 If you come from a dynamically typed language like Ruby, Python, or JavaScript,
256 you may not be used to these two steps being separate. Rust is an
257 **ahead-of-time compiled language**, which means that you can compile a
258 program, give it to someone else, and they don't need to have Rust installed.
259 If you give someone a `.rb` or `.py` or `.js` file, they need to have
260 Ruby/Python/JavaScript installed, but you just need one command to both compile
261 and run your program. Everything is a tradeoff in language design, and Rust has
262 made its choice.
263
264 Congratulations! You have officially written a Rust program. That makes you a
265 Rust programmer! Welcome.
266
267 Next, I'd like to introduce you to another tool, Cargo, which is used to write
268 real-world Rust programs. Just using `rustc` is nice for simple things, but as
269 your project grows, you'll want something to help you manage all of the options
270 that it has, and to make it easy to share your code with other people and
271 projects.
272
273 # Hello, Cargo!
274
275 [Cargo](http://crates.io) is a tool that Rustaceans use to help manage their
276 Rust projects. Cargo is currently in an alpha state, just like Rust, and so it
277 is still a work in progress. However, it is already good enough to use for many
278 Rust projects, and so it is assumed that Rust projects will use Cargo from the
279 beginning.
280
281 Cargo manages three things: building your code, downloading the dependencies
282 your code needs, and building the dependencies your code needs.  At first, your
283 program doesn't have any dependencies, so we'll only be using the first part of
284 its functionality. Eventually, we'll add more. Since we started off by using
285 Cargo, it'll be easy to add later.
286
287 Let's convert Hello World to Cargo. The first thing we need to do to begin
288 using Cargo is to install Cargo. Luckily for us, the script we ran to install
289 Rust includes Cargo by default. If you installed Rust some other way, you may
290 want to [check the Cargo
291 README](https://github.com/rust-lang/cargo#installing-cargo-from-nightlies)
292 for specific instructions about installing it.
293
294 To Cargo-ify our project, we need to do two things: Make a `Cargo.toml`
295 configuration file, and put our source file in the right place. Let's
296 do that part first:
297
298 ```{bash}
299 $ mkdir src
300 $ mv main.rs src/main.rs
301 ```
302
303 Cargo expects your source files to live inside a `src` directory. That leaves
304 the top level for other things, like READMEs, license information, and anything
305 not related to your code. Cargo helps us keep our projects nice and tidy. A
306 place for everything, and everything in its place.
307
308 Next, our configuration file:
309
310 ```{bash}
311 $ editor Cargo.toml
312 ```
313
314 Make sure to get this name right: you need the capital `C`!
315
316 Put this inside:
317
318 ```toml
319 [package]
320
321 name = "hello_world"
322 version = "0.0.1"
323 authors = [ "Your name <you@example.com>" ]
324
325 [[bin]]
326
327 name = "hello_world"
328 ```
329
330 This file is in the [TOML](https://github.com/toml-lang/toml) format. Let's let
331 it explain itself to you:
332
333 > TOML aims to be a minimal configuration file format that's easy to read due
334 > to obvious semantics. TOML is designed to map unambiguously to a hash table.
335 > TOML should be easy to parse into data structures in a wide variety of
336 > languages.
337
338 TOML is very similar to INI, but with some extra goodies.
339
340 Anyway, there are two **table**s in this file: `package` and `bin`. The first
341 tells Cargo metadata about your package. The second tells Cargo that we're
342 interested in building a binary, not a library (though we could do both!), as
343 well as what it is named.
344
345 Once you have this file in place, we should be ready to build! Try this:
346
347 ```{bash}
348 $ cargo build
349    Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
350 $ ./target/hello_world
351 Hello, world!
352 ```
353
354 Bam! We build our project with `cargo build`, and run it with
355 `./target/hello_world`. This hasn't bought us a whole lot over our simple use
356 of `rustc`, but think about the future: when our project has more than one
357 file, we would need to call `rustc` twice, and pass it a bunch of options to
358 tell it to build everything together. With Cargo, as our project grows, we can
359 just `cargo build` and it'll work the right way.
360
361 You'll also notice that Cargo has created a new file: `Cargo.lock`.
362
363 ```toml
364 [root]
365 name = "hello_world"
366 version = "0.0.1"
367 ```
368
369 This file is used by Cargo to keep track of dependencies in your application.
370 Right now, we don't have any, so it's a bit sparse. You won't ever need
371 to touch this file yourself, just let Cargo handle it.
372
373 That's it! We've successfully built `hello_world` with Cargo. Even though our
374 program is simple, it's using much of the real tooling that you'll use for the
375 rest of your Rust career.
376
377 Now that you've got the tools down, let's actually learn more about the Rust
378 language itself. These are the basics that will serve you well through the rest
379 of your time with Rust.
380
381 # Variable bindings
382
383 The first thing we'll learn about are 'variable bindings.' They look like this:
384
385 ```{rust}
386 fn main() {
387     let x = 5i;
388 }
389 ```
390
391 Putting `fn main() {` in each example is a bit tedious, so we'll leave that out
392 in the future. If you're following along, make sure to edit your `main()`
393 function, rather than leaving it off. Otherwise, you'll get an error.
394
395 In many languages, this is called a 'variable.' But Rust's variable bindings
396 have a few tricks up their sleeves. Rust has a very powerful feature called
397 'pattern matching' that we'll get into detail with later, but the left
398 hand side of a `let` expression is a full pattern, not just a variable name.
399 This means we can do things like:
400
401 ```{rust}
402 let (x, y) = (1i, 2i);
403 ```
404
405 After this expression is evaluated, `x` will be one, and `y` will be two.
406 Patterns are really powerful, but this is about all we can do with them so far.
407 So let's just keep this in the back of our minds as we go forward.
408
409 By the way, in these examples, `i` indicates that the number is an integer.
410
411 Rust is a statically typed language, which means that we specify our types up
412 front. So why does our first example compile? Well, Rust has this thing called
413 "type inference." If it can figure out what the type of something is, Rust
414 doesn't require you to actually type it out.
415
416 We can add the type if we want to, though. Types come after a colon (`:`):
417
418 ```{rust}
419 let x: int = 5;
420 ```
421
422 If I asked you to read this out loud to the rest of the class, you'd say "`x`
423 is a binding with the type `int` and the value `five`."
424
425 In future examples, we may annotate the type in a comment. The examples will
426 look like this:
427
428 ```{rust}
429 fn main() {
430     let x = 5i; // x: int
431 }
432 ```
433
434 Note the similarities between this annotation and the syntax you use with `let`.
435 Including these kinds of comments is not idiomatic Rust, but we'll occasionally
436 include them to help you understand what the types that Rust infers are.
437
438 By default, bindings are **immutable**. This code will not compile:
439
440 ```{ignore}
441 let x = 5i;
442 x = 10i;
443 ```
444
445 It will give you this error:
446
447 ```text
448 error: re-assignment of immutable variable `x`
449      x = 10i;
450      ^~~~~~~
451 ```
452
453 If you want a binding to be mutable, you can use `mut`:
454
455 ```{rust}
456 let mut x = 5i; // mut x: int
457 x = 10i;
458 ```
459
460 There is no single reason that bindings are immutable by default, but we can
461 think about it through one of Rust's primary focuses: safety. If you forget to
462 say `mut`, the compiler will catch it, and let you know that you have mutated
463 something you may not have intended to mutate. If bindings were mutable by
464 default, the compiler would not be able to tell you this. If you _did_ intend
465 mutation, then the solution is quite easy: add `mut`.
466
467 There are other good reasons to avoid mutable state when possible, but they're
468 out of the scope of this guide. In general, you can often avoid explicit
469 mutation, and so it is preferable in Rust. That said, sometimes, mutation is
470 what you need, so it's not verboten.
471
472 Let's get back to bindings. Rust variable bindings have one more aspect that
473 differs from other languages: bindings are required to be initialized with a
474 value before you're allowed to use them. If we try...
475
476 ```{ignore}
477 let x;
478 ```
479
480 ...we'll get an error:
481
482 ```text
483 src/main.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type
484 src/main.rs:2     let x;
485                       ^
486 ```
487
488 Giving it a type will compile, though:
489
490 ```{rust}
491 let x: int;
492 ```
493
494 Let's try it out. Change your `src/main.rs` file to look like this:
495
496 ```{rust}
497 fn main() {
498     let x: int;
499
500     println!("Hello world!");
501 }
502 ```
503
504 You can use `cargo build` on the command line to build it. You'll get a warning,
505 but it will still print "Hello, world!":
506
507 ```text
508    Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
509 src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
510 src/main.rs:2     let x: int;
511                       ^
512 ```
513
514 Rust warns us that we never use the variable binding, but since we never use it,
515 no harm, no foul. Things change if we try to actually use this `x`, however. Let's
516 do that. Change your program to look like this:
517
518 ```{rust,ignore}
519 fn main() {
520     let x: int;
521
522     println!("The value of x is: {}", x);
523 }
524 ```
525
526 And try to build it. You'll get an error:
527
528 ```{bash}
529 $ cargo build
530    Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
531 src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
532 src/main.rs:4     println!("The value of x is: {}", x);
533                                                     ^
534 note: in expansion of format_args!
535 <std macros>:2:23: 2:77 note: expansion site
536 <std macros>:1:1: 3:2 note: in expansion of println!
537 src/main.rs:4:5: 4:42 note: expansion site
538 error: aborting due to previous error
539 Could not compile `hello_world`.
540 ```
541
542 Rust will not let us use a value that has not been initialized. Next, let's
543 talk about this stuff we've added to `println!`.
544
545 If you include two curly braces (`{}`, some call them moustaches...) in your
546 string to print, Rust will interpret this as a request to interpolate some sort
547 of value. **String interpolation** is a computer science term that means "stick
548 in the middle of a string." We add a comma, and then `x`, to indicate that we
549 want `x` to be the value we're interpolating. The comma is used to separate
550 arguments we pass to functions and macros, if you're passing more than one.
551
552 When you just use the curly braces, Rust will attempt to display the
553 value in a meaningful way by checking out its type. If you want to specify the
554 format in a more detailed manner, there are a [wide number of options
555 available](std/fmt/index.html). For now, we'll just stick to the default:
556 integers aren't very complicated to print.
557
558 # `if`
559
560 Rust's take on `if` is not particularly complex, but it's much more like the
561 `if` you'll find in a dynamically typed language than in a more traditional
562 systems language. So let's talk about it, to make sure you grasp the nuances.
563
564 `if` is a specific form of a more general concept, the 'branch.' The name comes
565 from a branch in a tree: a decision point, where depending on a choice,
566 multiple paths can be taken.
567
568 In the case of `if`, there is one choice that leads down two paths:
569
570 ```rust
571 let x = 5i;
572
573 if x == 5i {
574     println!("x is five!");
575 }
576 ```
577
578 If we changed the value of `x` to something else, this line would not print.
579 More specifically, if the expression after the `if` evaluates to `true`, then
580 the block is executed. If it's `false`, then it is not.
581
582 If you want something to happen in the `false` case, use an `else`:
583
584 ```{rust}
585 let x = 5i;
586
587 if x == 5i {
588     println!("x is five!");
589 } else {
590     println!("x is not five :(");
591 }
592 ```
593
594 This is all pretty standard. However, you can also do this:
595
596
597 ```{rust}
598 let x = 5i;
599
600 let y = if x == 5i {
601     10i
602 } else {
603     15i
604 }; // y: int
605 ```
606
607 Which we can (and probably should) write like this:
608
609 ```{rust}
610 let x = 5i;
611
612 let y = if x == 5i { 10i } else { 15i }; // y: int
613 ```
614
615 This reveals two interesting things about Rust: it is an expression-based
616 language, and semicolons are different from semicolons in other 'curly brace
617 and semicolon'-based languages. These two things are related.
618
619 ## Expressions vs. Statements
620
621 Rust is primarily an expression based language. There are only two kinds of
622 statements, and everything else is an expression.
623
624 So what's the difference? Expressions return a value, and statements do not.
625 In many languages, `if` is a statement, and therefore, `let x = if ...` would
626 make no sense. But in Rust, `if` is an expression, which means that it returns
627 a value. We can then use this value to initialize the binding.
628
629 Speaking of which, bindings are a kind of the first of Rust's two statements.
630 The proper name is a **declaration statement**. So far, `let` is the only kind
631 of declaration statement we've seen. Let's talk about that some more.
632
633 In some languages, variable bindings can be written as expressions, not just
634 statements. Like Ruby:
635
636 ```{ruby}
637 x = y = 5
638 ```
639
640 In Rust, however, using `let` to introduce a binding is _not_ an expression. The
641 following will produce a compile-time error:
642
643 ```{ignore}
644 let x = (let y = 5i); // expected identifier, found keyword `let`
645 ```
646
647 The compiler is telling us here that it was expecting to see the beginning of
648 an expression, and a `let` can only begin a statement, not an expression.
649
650 Note that assigning to an already-bound variable (e.g. `y = 5i`) is still an
651 expression, although its value is not particularly useful. Unlike C, where an
652 assignment evaluates to the assigned value (e.g. `5i` in the previous example),
653 in Rust the value of an assignment is the unit type `()` (which we'll cover later).
654
655 The second kind of statement in Rust is the **expression statement**. Its
656 purpose is to turn any expression into a statement. In practical terms, Rust's
657 grammar expects statements to follow other statements. This means that you use
658 semicolons to separate expressions from each other. This means that Rust
659 looks a lot like most other languages that require you to use semicolons
660 at the end of every line, and you will see semicolons at the end of almost
661 every line of Rust code you see.
662
663 What is this exception that makes us say 'almost?' You saw it already, in this
664 code:
665
666 ```{rust}
667 let x = 5i;
668
669 let y: int = if x == 5i { 10i } else { 15i };
670 ```
671
672 Note that I've added the type annotation to `y`, to specify explicitly that I
673 want `y` to be an integer.
674
675 This is not the same as this, which won't compile:
676
677 ```{ignore}
678 let x = 5i;
679
680 let y: int = if x == 5i { 10i; } else { 15i; };
681 ```
682
683 Note the semicolons after the 10 and 15. Rust will give us the following error:
684
685 ```text
686 error: mismatched types: expected `int` but found `()` (expected int but found ())
687 ```
688
689 We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a
690 special type in Rust's type system. In Rust, `()` is _not_ a valid value for a
691 variable of type `int`. It's only a valid value for variables of the type `()`,
692 which aren't very useful. Remember how we said statements don't return a value?
693 Well, that's the purpose of unit in this case. The semicolon turns any
694 expression into a statement by throwing away its value and returning unit
695 instead.
696
697 There's one more time in which you won't see a semicolon at the end of a line
698 of Rust code. For that, we'll need our next concept: functions.
699
700 # Functions
701
702 You've already seen one function so far, the `main` function:
703
704 ```{rust}
705 fn main() {
706 }
707 ```
708
709 This is the simplest possible function declaration. As we mentioned before,
710 `fn` says 'this is a function,' followed by the name, some parentheses because
711 this function takes no arguments, and then some curly braces to indicate the
712 body. Here's a function named `foo`:
713
714 ```{rust}
715 fn foo() {
716 }
717 ```
718
719 So, what about taking arguments? Here's a function that prints a number:
720
721 ```{rust}
722 fn print_number(x: int) {
723     println!("x is: {}", x);
724 }
725 ```
726
727 Here's a complete program that uses `print_number`:
728
729 ```{rust}
730 fn main() {
731     print_number(5);
732 }
733
734 fn print_number(x: int) {
735     println!("x is: {}", x);
736 }
737 ```
738
739 As you can see, function arguments work very similar to `let` declarations:
740 you add a type to the argument name, after a colon.
741
742 Here's a complete program that adds two numbers together and prints them:
743
744 ```{rust}
745 fn main() {
746     print_sum(5, 6);
747 }
748
749 fn print_sum(x: int, y: int) {
750     println!("sum is: {}", x + y);
751 }
752 ```
753
754 You separate arguments with a comma, both when you call the function, as well
755 as when you declare it.
756
757 Unlike `let`, you _must_ declare the types of function arguments. This does
758 not work:
759
760 ```{ignore}
761 fn print_number(x, y) {
762     println!("x is: {}", x + y);
763 }
764 ```
765
766 You get this error:
767
768 ```text
769 hello.rs:5:18: 5:19 error: expected `:` but found `,`
770 hello.rs:5 fn print_number(x, y) {
771 ```
772
773 This is a deliberate design decision. While full-program inference is possible,
774 languages which have it, like Haskell, often suggest that documenting your
775 types explicitly is a best-practice. We agree that forcing functions to declare
776 types while allowing for inference inside of function bodies is a wonderful
777 sweet spot between full inference and no inference.
778
779 What about returning a value? Here's a function that adds one to an integer:
780
781 ```{rust}
782 fn add_one(x: int) -> int {
783     x + 1
784 }
785 ```
786
787 Rust functions return exactly one value, and you declare the type after an
788 'arrow', which is a dash (`-`) followed by a greater-than sign (`>`).
789
790 You'll note the lack of a semicolon here. If we added it in:
791
792 ```{ignore}
793 fn add_one(x: int) -> int {
794     x + 1;
795 }
796 ```
797
798 We would get an error:
799
800 ```text
801 error: not all control paths return a value
802 fn add_one(x: int) -> int {
803      x + 1;
804 }
805
806 help: consider removing this semicolon:
807      x + 1;
808           ^
809 ```
810
811 Remember our earlier discussions about semicolons and `()`? Our function claims
812 to return an `int`, but with a semicolon, it would return `()` instead. Rust
813 realizes this probably isn't what we want, and suggests removing the semicolon.
814
815 This is very much like our `if` statement before: the result of the block
816 (`{}`) is the value of the expression. Other expression-oriented languages,
817 such as Ruby, work like this, but it's a bit unusual in the systems programming
818 world. When people first learn about this, they usually assume that it
819 introduces bugs. But because Rust's type system is so strong, and because unit
820 is its own unique type, we have never seen an issue where adding or removing a
821 semicolon in a return position would cause a bug.
822
823 But what about early returns? Rust does have a keyword for that, `return`:
824
825 ```{rust}
826 fn foo(x: int) -> int {
827     if x < 5 { return x; }
828
829     x + 1
830 }
831 ```
832
833 Using a `return` as the last line of a function works, but is considered poor
834 style:
835
836 ```{rust}
837 fn foo(x: int) -> int {
838     if x < 5 { return x; }
839
840     return x + 1;
841 }
842 ```
843
844 There are some additional ways to define functions, but they involve features
845 that we haven't learned about yet, so let's just leave it at that for now.
846
847
848 # Comments
849
850 Now that we have some functions, it's a good idea to learn about comments.
851 Comments are notes that you leave to other programmers to help explain things
852 about your code. The compiler mostly ignores them.
853
854 Rust has two kinds of comments that you should care about: **line comment**s
855 and **doc comment**s.
856
857 ```{rust}
858 // Line comments are anything after '//' and extend to the end of the line.
859
860 let x = 5i; // this is also a line comment.
861
862 // If you have a long explanation for something, you can put line comments next
863 // to each other. Put a space between the // and your comment so that it's
864 // more readable.
865 ```
866
867 The other kind of comment is a doc comment. Doc comments use `///` instead of
868 `//`, and support Markdown notation inside:
869
870 ```{rust}
871 /// `hello` is a function that prints a greeting that is personalized based on
872 /// the name given.
873 ///
874 /// # Arguments
875 ///
876 /// * `name` - The name of the person you'd like to greet.
877 ///
878 /// # Example
879 ///
880 /// ```rust
881 /// let name = "Steve";
882 /// hello(name); // prints "Hello, Steve!"
883 /// ```
884 fn hello(name: &str) {
885     println!("Hello, {}!", name);
886 }
887 ```
888
889 When writing doc comments, adding sections for any arguments, return values,
890 and providing some examples of usage is very, very helpful.
891
892 You can use the [`rustdoc`](rustdoc.html) tool to generate HTML documentation
893 from these doc comments.
894
895 # Compound Data Types
896
897 Rust, like many programming languages, has a number of different data types
898 that are built-in. You've already done some simple work with integers and
899 strings, but next, let's talk about some more complicated ways of storing data.
900
901 ## Tuples
902
903 The first compound data type we're going to talk about are called **tuple**s.
904 Tuples are an ordered list of a fixed size. Like this:
905
906 ```rust
907 let x = (1i, "hello");
908 ```
909
910 The parentheses and commas form this two-length tuple. Here's the same code, but
911 with the type annotated:
912
913 ```rust
914 let x: (int, &str) = (1, "hello");
915 ```
916
917 As you can see, the type of a tuple looks just like the tuple, but with each
918 position having a type name rather than the value. Careful readers will also
919 note that tuples are heterogeneous: we have an `int` and a `&str` in this tuple.
920 You haven't seen `&str` as a type before, and we'll discuss the details of
921 strings later. In systems programming languages, strings are a bit more complex
922 than in other languages. For now, just read `&str` as "a string slice," and
923 we'll learn more soon.
924
925 You can access the fields in a tuple through a **destructuring let**. Here's
926 an example:
927
928 ```rust
929 let (x, y, z) = (1i, 2i, 3i);
930
931 println!("x is {}", x);
932 ```
933
934 Remember before when I said the left-hand side of a `let` statement was more
935 powerful than just assigning a binding? Here we are. We can put a pattern on
936 the left-hand side of the `let`, and if it matches up to the right-hand side,
937 we can assign multiple bindings at once. In this case, `let` 'destructures,'
938 or 'breaks up,' the tuple, and assigns the bits to three bindings.
939
940 This pattern is very powerful, and we'll see it repeated more later.
941
942 There are also a few things you can do with a tuple as a whole, without
943 destructuring. You can assign one tuple into another, if they have the same
944 arity and contained types.
945
946 ```rust
947 let mut x = (1i, 2i); // x: (int, int)
948 let y = (2i, 3i);     // y: (int, int)
949
950 x = y;
951 ```
952
953 You can also check for equality with `==`. Again, this will only compile if the
954 tuples have the same type.
955
956 ```rust
957 let x = (1i, 2i, 3i);
958 let y = (2i, 2i, 4i);
959
960 if x == y {
961     println!("yes");
962 } else {
963     println!("no");
964 }
965 ```
966
967 This will print `no`, because some of the values aren't equal.
968
969 One other use of tuples is to return multiple values from a function:
970
971 ```rust
972 fn next_two(x: int) -> (int, int) { (x + 1i, x + 2i) }
973
974 fn main() {
975     let (x, y) = next_two(5i);
976     println!("x, y = {}, {}", x, y);
977 }
978 ```
979
980 Even though Rust functions can only return one value, a tuple _is_ one value,
981 that happens to be made up of two. You can also see in this example how you
982 can destructure a pattern returned by a function, as well.
983
984 Tuples are a very simple data structure, and so are not often what you want.
985 Let's move on to their bigger sibling, structs.
986
987 ## Structs
988
989 A struct is another form of a 'record type,' just like a tuple. There's a
990 difference: structs give each element that they contain a name, called a
991 'field' or a 'member.' Check it out:
992
993 ```rust
994 struct Point {
995     x: int,
996     y: int,
997 }
998
999 fn main() {
1000     let origin = Point { x: 0i, y: 0i }; // origin: Point
1001
1002     println!("The origin is at ({}, {})", origin.x, origin.y);
1003 }
1004 ```
1005
1006 There's a lot going on here, so let's break it down. We declare a struct with
1007 the `struct` keyword, and then with a name. By convention, structs begin with a
1008 capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`.
1009
1010 We can create an instance of our struct via `let`, as usual, but we use a `key:
1011 value` style syntax to set each field. The order doesn't need to be the same as
1012 in the original declaration.
1013
1014 Finally, because fields have names, we can access the field through dot
1015 notation: `origin.x`.
1016
1017 The values in structs are immutable by default, like other bindings in Rust.
1018 Use `mut` to make them mutable:
1019
1020 ```{rust}
1021 struct Point {
1022     x: int,
1023     y: int,
1024 }
1025
1026 fn main() {
1027     let mut point = Point { x: 0i, y: 0i };
1028
1029     point.x = 5;
1030
1031     println!("The point is at ({}, {})", point.x, point.y);
1032 }
1033 ```
1034
1035 This will print `The point is at (5, 0)`.
1036
1037 ## Tuple Structs and Newtypes
1038
1039 Rust has another data type that's like a hybrid between a tuple and a struct,
1040 called a **tuple struct**. Tuple structs do have a name, but their fields
1041 don't:
1042
1043
1044 ```{rust}
1045 struct Color(int, int, int);
1046 struct Point(int, int, int);
1047 ```
1048
1049 These two will not be equal, even if they have the same values:
1050
1051 ```{rust}
1052 # struct Color(int, int, int);
1053 # struct Point(int, int, int);
1054 let black  = Color(0, 0, 0);
1055 let origin = Point(0, 0, 0);
1056 ```
1057
1058 It is almost always better to use a struct than a tuple struct. We would write
1059 `Color` and `Point` like this instead:
1060
1061 ```{rust}
1062 struct Color {
1063     red: int,
1064     blue: int,
1065     green: int,
1066 }
1067
1068 struct Point {
1069     x: int,
1070     y: int,
1071     z: int,
1072 }
1073 ```
1074
1075 Now, we have actual names, rather than positions. Good names are important,
1076 and with a struct, we have actual names.
1077
1078 There _is_ one case when a tuple struct is very useful, though, and that's a
1079 tuple struct with only one element. We call this a 'newtype,' because it lets
1080 you create a new type that's a synonym for another one:
1081
1082 ```{rust}
1083 struct Inches(int);
1084
1085 let length = Inches(10);
1086
1087 let Inches(integer_length) = length;
1088 println!("length is {} inches", integer_length);
1089 ```
1090
1091 As you can see here, you can extract the inner integer type through a
1092 destructuring `let`.
1093
1094 ## Enums
1095
1096 Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful
1097 feature of Rust, and are used throughout the standard library. This is an enum
1098 that is provided by the Rust standard library:
1099
1100 ```{rust}
1101 enum Ordering {
1102     Less,
1103     Equal,
1104     Greater,
1105 }
1106 ```
1107
1108 An `Ordering` can only be _one_ of `Less`, `Equal`, or `Greater` at any given
1109 time.
1110
1111 Because `Ordering` is provided by the standard library, we can use the `use`
1112 keyword to use it in our code. We'll learn more about `use` later, but it's
1113 used to bring names into scope.
1114
1115 Here's an example of how to use `Ordering`:
1116
1117 ```{rust}
1118 use std::cmp::Ordering;
1119
1120 fn cmp(a: int, b: int) -> Ordering {
1121     if a < b { Ordering::Less }
1122     else if a > b { Ordering::Greater }
1123     else { Ordering::Equal }
1124 }
1125
1126 fn main() {
1127     let x = 5i;
1128     let y = 10i;
1129
1130     let ordering = cmp(x, y); // ordering: Ordering
1131
1132     if ordering == Ordering::Less {
1133         println!("less");
1134     } else if ordering == Ordering::Greater {
1135         println!("greater");
1136     } else if ordering == Ordering::Equal {
1137         println!("equal");
1138     }
1139 }
1140 ```
1141
1142 There's a symbol here we haven't seen before: the double colon (`::`).
1143 This is used to indicate a namesapce. In this case, `Ordering` lives in
1144 the `cmp` submodule of the `std` module. We'll talk more about modules
1145 later in the guide. For now, all you need to know is that you can `use`
1146 things from the standard library if you need them.
1147
1148 Okay, let's talk about the actual code in the example. `cmp` is a function that
1149 compares two things, and returns an `Ordering`. We return either
1150 `Ordering::Less`, `Ordering::Greater`, or `Ordering::Equal`, depending on if
1151 the two values are greater, less, or equal. Note that each variant of the
1152 `enum` is namespaced under the `enum` itself: it's `Ordering::Greater` not
1153 `Greater`.
1154
1155 The `ordering` variable has the type `Ordering`, and so contains one of the
1156 three values. We can then do a bunch of `if`/`else` comparisons to check which
1157 one it is. However, repeated `if`/`else` comparisons get quite tedious. Rust
1158 has a feature that not only makes them nicer to read, but also makes sure that
1159 you never miss a case. Before we get to that, though, let's talk about another
1160 kind of enum: one with values.
1161
1162 This enum has two variants, one of which has a value:
1163
1164 ```{rust}
1165 enum OptionalInt {
1166     Value(int),
1167     Missing,
1168 }
1169 ```
1170
1171 This enum represents an `int` that we may or may not have. In the `Missing`
1172 case, we have no value, but in the `Value` case, we do. This enum is specific
1173 to `int`s, though. We can make it usable by any type, but we haven't quite
1174 gotten there yet!
1175
1176 You can also have any number of values in an enum:
1177
1178 ```{rust}
1179 enum OptionalColor {
1180     Color(int, int, int),
1181     Missing,
1182 }
1183 ```
1184
1185 And you can also have something like this:
1186
1187 ```{rust}
1188 enum StringResult {
1189     StringOK(String),
1190     ErrorReason(String),
1191 }
1192 ```
1193 Where a `StringResult` is either a `StringResult::StringOK`, with the result of
1194 a computation, or an `StringResult::ErrorReason` with a `String` explaining
1195 what caused the computation to fail. These kinds of `enum`s are actually very
1196 useful and are even part of the standard library.
1197
1198 Here is an example of using our `StringResult`:
1199
1200 ```rust
1201 enum StringResult {
1202     StringOK(String),
1203     ErrorReason(String),
1204 }
1205
1206 fn respond(greeting: &str) -> StringResult {
1207     if greeting == "Hello" {
1208         StringResult::StringOK("Good morning!".to_string())
1209     } else {
1210         StringResult::ErrorReason("I didn't understand you!".to_string())
1211     }
1212 }
1213 ```
1214
1215 That's a lot of typing! We can use the `use` keyword to make it shorter:
1216
1217 ```rust
1218 use StringResult::StringOK;
1219 use StringResult::ErrorReason;
1220
1221 enum StringResult {
1222     StringOK(String),
1223     ErrorReason(String),
1224 }
1225
1226 # fn main() {}
1227
1228 fn respond(greeting: &str) -> StringResult {
1229     if greeting == "Hello" {
1230         StringOK("Good morning!".to_string())
1231     } else {
1232         ErrorReason("I didn't understand you!".to_string())
1233     }
1234 }
1235 ```
1236
1237 `use` declarations must come before anything else, which looks a little strange in this example,
1238 since we `use` the variants before we define them. Anyway, in the body of `respond`, we can just
1239 say `StringOK` now, rather than the full `StringResult::StringOK`. Importing variants can be
1240 convenient, but can also cause name conflicts, so do this with caution. It's considered good style
1241 to rarely import variants for this reason.
1242
1243 As you can see, `enum`s with values are quite a powerful tool for data representation,
1244 and can be even more useful when they're generic across types. Before we get to generics,
1245 though, let's talk about how to use them with pattern matching, a tool that will
1246 let us deconstruct this sum type (the type theory term for enums) in a very elegant
1247 way and avoid all these messy `if`/`else`s.
1248
1249 # Match
1250
1251 Often, a simple `if`/`else` isn't enough, because you have more than two
1252 possible options. Also, `else` conditions can get incredibly complicated, so
1253 what's the solution?
1254
1255 Rust has a keyword, `match`, that allows you to replace complicated `if`/`else`
1256 groupings with something more powerful. Check it out:
1257
1258 ```{rust}
1259 let x = 5i;
1260
1261 match x {
1262     1 => println!("one"),
1263     2 => println!("two"),
1264     3 => println!("three"),
1265     4 => println!("four"),
1266     5 => println!("five"),
1267     _ => println!("something else"),
1268 }
1269 ```
1270
1271 `match` takes an expression and then branches based on its value. Each 'arm' of
1272 the branch is of the form `val => expression`. When the value matches, that arm's
1273 expression will be evaluated. It's called `match` because of the term 'pattern
1274 matching', which `match` is an implementation of.
1275
1276 So what's the big advantage here? Well, there are a few. First of all, `match`
1277 enforces 'exhaustiveness checking'. Do you see that last arm, the one with the
1278 underscore (`_`)? If we remove that arm, Rust will give us an error:
1279
1280 ```text
1281 error: non-exhaustive patterns: `_` not covered
1282 ```
1283
1284 In other words, Rust is trying to tell us we forgot a value. Because `x` is an
1285 integer, Rust knows that it can have a number of different values – for example,
1286 `6i`. Without the `_`, however, there is no arm that could match, and so Rust refuses
1287 to compile. `_` acts like a 'catch-all arm'. If none of the other arms match,
1288 the arm with `_` will, and since we have this catch-all arm, we now have an arm
1289 for every possible value of `x`, and so our program will compile successfully.
1290
1291 `match` statements also destructure enums, as well. Remember this code from the
1292 section on enums?
1293
1294 ```{rust}
1295 use std::cmp::Ordering;
1296
1297 fn cmp(a: int, b: int) -> Ordering {
1298     if a < b { Ordering::Less }
1299     else if a > b { Ordering::Greater }
1300     else { Ordering::Equal }
1301 }
1302
1303 fn main() {
1304     let x = 5i;
1305     let y = 10i;
1306
1307     let ordering = cmp(x, y);
1308
1309     if ordering == Ordering::Less {
1310         println!("less");
1311     } else if ordering == Ordering::Greater {
1312         println!("greater");
1313     } else if ordering == Ordering::Equal {
1314         println!("equal");
1315     }
1316 }
1317 ```
1318
1319 We can re-write this as a `match`:
1320
1321 ```{rust}
1322 use std::cmp::Ordering;
1323
1324 fn cmp(a: int, b: int) -> Ordering {
1325     if a < b { Ordering::Less }
1326     else if a > b { Ordering::Greater }
1327     else { Ordering::Equal }
1328 }
1329
1330 fn main() {
1331     let x = 5i;
1332     let y = 10i;
1333
1334     match cmp(x, y) {
1335         Ordering::Less    => println!("less"),
1336         Ordering::Greater => println!("greater"),
1337         Ordering::Equal   => println!("equal"),
1338     }
1339 }
1340 ```
1341
1342 This version has way less noise, and it also checks exhaustively to make sure
1343 that we have covered all possible variants of `Ordering`. With our `if`/`else`
1344 version, if we had forgotten the `Greater` case, for example, our program would
1345 have happily compiled. If we forget in the `match`, it will not. Rust helps us
1346 make sure to cover all of our bases.
1347
1348 `match` expressions also allow us to get the values contained in an `enum`
1349 (also known as destructuring) as follows:
1350
1351 ```{rust}
1352 enum OptionalInt {
1353     Value(int),
1354     Missing,
1355 }
1356
1357 fn main() {
1358     let x = OptionalInt::Value(5);
1359     let y = OptionalInt::Missing;
1360
1361     match x {
1362         OptionalInt::Value(n) => println!("x is {}", n),
1363         OptionalInt::Missing  => println!("x is missing!"),
1364     }
1365
1366     match y {
1367         OptionalInt::Value(n) => println!("y is {}", n),
1368         OptionalInt::Missing  => println!("y is missing!"),
1369     }
1370 }
1371 ```
1372
1373 That is how you can get and use the values contained in `enum`s.
1374 It can also allow us to handle errors or unexpected computations; for example, a
1375 function that is not guaranteed to be able to compute a result (an `int` here)
1376 could return an `OptionalInt`, and we would handle that value with a `match`.
1377 As you can see, `enum` and `match` used together are quite useful!
1378
1379 `match` is also an expression, which means we can use it on the right-hand
1380 side of a `let` binding or directly where an expression is used. We could
1381 also implement the previous line like this:
1382
1383 ```{rust}
1384 use std::cmp::Ordering;
1385
1386 fn cmp(a: int, b: int) -> Ordering {
1387     if a < b { Ordering::Less }
1388     else if a > b { Ordering::Greater }
1389     else { Ordering::Equal }
1390 }
1391
1392 fn main() {
1393     let x = 5i;
1394     let y = 10i;
1395
1396     println!("{}", match cmp(x, y) {
1397         Ordering::Less    => "less",
1398         Ordering::Greater => "greater",
1399         Ordering::Equal   => "equal",
1400     });
1401 }
1402 ```
1403
1404 Sometimes, it's a nice pattern.
1405
1406 # Looping
1407
1408 Looping is the last basic construct that we haven't learned yet in Rust. Rust has
1409 two main looping constructs: `for` and `while`.
1410
1411 ## `for`
1412
1413 The `for` loop is used to loop a particular number of times. Rust's `for` loops
1414 work a bit differently than in other systems languages, however. Rust's `for`
1415 loop doesn't look like this "C-style" `for` loop:
1416
1417 ```{c}
1418 for (x = 0; x < 10; x++) {
1419     printf( "%d\n", x );
1420 }
1421 ```
1422
1423 Instead, it looks like this:
1424
1425 ```{rust}
1426 for x in range(0i, 10i) {
1427     println!("{}", x); // x: int
1428 }
1429 ```
1430
1431 In slightly more abstract terms,
1432
1433 ```{ignore}
1434 for var in expression {
1435     code
1436 }
1437 ```
1438
1439 The expression is an iterator, which we will discuss in more depth later in the
1440 guide. The iterator gives back a series of elements. Each element is one
1441 iteration of the loop. That value is then bound to the name `var`, which is
1442 valid for the loop body. Once the body is over, the next value is fetched from
1443 the iterator, and we loop another time. When there are no more values, the
1444 `for` loop is over.
1445
1446 In our example, `range` is a function that takes a start and an end position,
1447 and gives an iterator over those values. The upper bound is exclusive, though,
1448 so our loop will print `0` through `9`, not `10`.
1449
1450 Rust does not have the "C-style" `for` loop on purpose. Manually controlling
1451 each element of the loop is complicated and error prone, even for experienced C
1452 developers.
1453
1454 We'll talk more about `for` when we cover **iterator**s, later in the Guide.
1455
1456 ## `while`
1457
1458 The other kind of looping construct in Rust is the `while` loop. It looks like
1459 this:
1460
1461 ```{rust}
1462 let mut x = 5u;       // mut x: uint
1463 let mut done = false; // mut done: bool
1464
1465 while !done {
1466     x += x - 3;
1467     println!("{}", x);
1468     if x % 5 == 0 { done = true; }
1469 }
1470 ```
1471
1472 `while` loops are the correct choice when you're not sure how many times
1473 you need to loop.
1474
1475 If you need an infinite loop, you may be tempted to write this:
1476
1477 ```{rust,ignore}
1478 while true {
1479 ```
1480
1481 However, Rust has a dedicated keyword, `loop`, to handle this case:
1482
1483 ```{rust,ignore}
1484 loop {
1485 ```
1486
1487 Rust's control-flow analysis treats this construct differently than a
1488 `while true`, since we know that it will always loop. The details of what
1489 that _means_ aren't super important to understand at this stage, but in
1490 general, the more information we can give to the compiler, the better it
1491 can do with safety and code generation, so you should always prefer
1492 `loop` when you plan to loop infinitely.
1493
1494 ## Ending iteration early
1495
1496 Let's take a look at that `while` loop we had earlier:
1497
1498 ```{rust}
1499 let mut x = 5u;
1500 let mut done = false;
1501
1502 while !done {
1503     x += x - 3;
1504     println!("{}", x);
1505     if x % 5 == 0 { done = true; }
1506 }
1507 ```
1508
1509 We had to keep a dedicated `mut` boolean variable binding, `done`, to know
1510 when we should exit out of the loop. Rust has two keywords to help us with
1511 modifying iteration: `break` and `continue`.
1512
1513 In this case, we can write the loop in a better way with `break`:
1514
1515 ```{rust}
1516 let mut x = 5u;
1517
1518 loop {
1519     x += x - 3;
1520     println!("{}", x);
1521     if x % 5 == 0 { break; }
1522 }
1523 ```
1524
1525 We now loop forever with `loop` and use `break` to break out early.
1526
1527 `continue` is similar, but instead of ending the loop, goes to the next
1528 iteration. This will only print the odd numbers:
1529
1530 ```{rust}
1531 for x in range(0i, 10i) {
1532     if x % 2 == 0 { continue; }
1533
1534     println!("{}", x);
1535 }
1536 ```
1537
1538 Both `continue` and `break` are valid in both kinds of loops.
1539
1540 # Strings
1541
1542 Strings are an important concept for any programmer to master. Rust's string
1543 handling system is a bit different from other languages, due to its systems
1544 focus. Any time you have a data structure of variable size, things can get
1545 tricky, and strings are a re-sizable data structure. That being said, Rust's
1546 strings also work differently than in some other systems languages, such as C.
1547
1548 Let's dig into the details. A **string** is a sequence of Unicode scalar values
1549 encoded as a stream of UTF-8 bytes. All strings are guaranteed to be
1550 validly encoded UTF-8 sequences. Additionally, strings are not null-terminated
1551 and can contain null bytes.
1552
1553 Rust has two main types of strings: `&str` and `String`.
1554
1555 The first kind is a `&str`. This is pronounced a 'string slice.' String literals
1556 are of the type `&str`:
1557
1558 ```{rust}
1559 let string = "Hello there."; // string: &str
1560 ```
1561
1562 This string is statically allocated, meaning that it's saved inside our
1563 compiled program, and exists for the entire duration it runs. The `string`
1564 binding is a reference to this statically allocated string. String slices
1565 have a fixed size, and cannot be mutated.
1566
1567 A `String`, on the other hand, is an in-memory string.  This string is
1568 growable, and is also guaranteed to be UTF-8.
1569
1570 ```{rust}
1571 let mut s = "Hello".to_string(); // mut s: String
1572 println!("{}", s);
1573
1574 s.push_str(", world.");
1575 println!("{}", s);
1576 ```
1577
1578 You can get a `&str` view into a `String` with the `as_slice()` method:
1579
1580 ```{rust}
1581 fn takes_slice(slice: &str) {
1582     println!("Got: {}", slice);
1583 }
1584
1585 fn main() {
1586     let s = "Hello".to_string();
1587     takes_slice(s.as_slice());
1588 }
1589 ```
1590
1591 To compare a String to a constant string, prefer `as_slice()`...
1592
1593 ```{rust}
1594 fn compare(string: String) {
1595     if string.as_slice() == "Hello" {
1596         println!("yes");
1597     }
1598 }
1599 ```
1600
1601 ... over `to_string()`:
1602
1603 ```{rust}
1604 fn compare(string: String) {
1605     if string == "Hello".to_string() {
1606         println!("yes");
1607     }
1608 }
1609 ```
1610
1611 Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
1612 `String` involves allocating memory. No reason to do that unless you have to!
1613
1614 That's the basics of strings in Rust! They're probably a bit more complicated
1615 than you are used to, if you come from a scripting language, but when the
1616 low-level details matter, they really matter. Just remember that `String`s
1617 allocate memory and control their data, while `&str`s are a reference to
1618 another string, and you'll be all set.
1619
1620 # Arrays, Vectors, and Slices
1621
1622 Like many programming languages, Rust has list types to represent a sequence of
1623 things. The most basic is the **array**, a fixed-size list of elements of the
1624 same type. By default, arrays are immutable.
1625
1626 ```{rust}
1627 let a = [1i, 2i, 3i];     // a: [int; 3]
1628 let mut m = [1i, 2i, 3i]; // mut m: [int; 3]
1629 ```
1630
1631 There's a shorthand for initializing each element of an array to the same
1632 value. In this example, each element of `a` will be initialized to `0i`:
1633
1634 ```{rust}
1635 let a = [0i; 20]; // a: [int; 20]
1636 ```
1637
1638 Arrays have type `[T; N]`. We'll talk about this `T` notation later, when we
1639 cover generics.
1640
1641 You can get the number of elements in an array `a` with `a.len()`, and use
1642 `a.iter()` to iterate over them with a for loop. This code will print each
1643 number in order:
1644
1645 ```{rust}
1646 let a = [1i, 2, 3]; // Only the first item needs a type suffix
1647
1648 println!("a has {} elements", a.len());
1649 for e in a.iter() {
1650     println!("{}", e);
1651 }
1652 ```
1653
1654 You can access a particular element of an array with **subscript notation**:
1655
1656 ```{rust}
1657 let names = ["Graydon", "Brian", "Niko"]; // names: [&str, 3]
1658
1659 println!("The second name is: {}", names[1]);
1660 ```
1661
1662 Subscripts start at zero, like in most programming languages, so the first name
1663 is `names[0]` and the second name is `names[1]`. The above example prints
1664 `The second name is: Brian`. If you try to use a subscript that is not in the
1665 array, you will get an error: array access is bounds-checked at run-time. Such
1666 errant access is the source of many bugs in other systems programming
1667 languages.
1668
1669 A **vector** is a dynamic or "growable" array, implemented as the standard
1670 library type [`Vec<T>`](std/vec/) (we'll talk about what the `<T>` means
1671 later). Vectors are to arrays what `String` is to `&str`. You can create them
1672 with the `vec!` macro:
1673
1674 ```{rust}
1675 let v = vec![1i, 2, 3]; // v: Vec<int>
1676 ```
1677
1678 (Notice that unlike the `println!` macro we've used in the past, we use square
1679 brackets `[]` with `vec!`. Rust allows you to use either in either situation,
1680 this is just convention.)
1681
1682 You can get the length of, iterate over, and subscript vectors just like
1683 arrays. In addition, (mutable) vectors can grow automatically:
1684
1685 ```{rust}
1686 let mut nums = vec![1i, 2, 3]; // mut nums: Vec<int>
1687
1688 nums.push(4);
1689
1690 println!("The length of nums is now {}", nums.len());   // Prints 4
1691 ```
1692
1693 Vectors have many more useful methods.
1694
1695 A **slice** is a reference to (or "view" into) an array. They are useful for
1696 allowing safe, efficient access to a portion of an array without copying. For
1697 example, you might want to reference just one line of a file read into memory.
1698 By nature, a slice is not created directly, but from an existing variable.
1699 Slices have a length, can be mutable or not, and in many ways behave like
1700 arrays:
1701
1702 ```{rust}
1703 let a = [0i, 1, 2, 3, 4];
1704 let middle = a.slice(1, 4);     // A slice of a: just the elements [1,2,3]
1705
1706 for e in middle.iter() {
1707     println!("{}", e);          // Prints 1, 2, 3
1708 }
1709 ```
1710
1711 You can also take a slice of a vector, `String`, or `&str`, because they are
1712 backed by arrays. Slices have type `&[T]`, which we'll talk about when we cover
1713 generics.
1714
1715 We have now learned all of the most basic Rust concepts. We're ready to start
1716 building our guessing game, we just need to know one last thing: how to get
1717 input from the keyboard. You can't have a guessing game without the ability to
1718 guess!
1719
1720 # Standard Input
1721
1722 Getting input from the keyboard is pretty easy, but uses some things
1723 we haven't seen before. Here's a simple program that reads some input,
1724 and then prints it back out:
1725
1726 ```{rust,ignore}
1727 fn main() {
1728     println!("Type something!");
1729
1730     let input = std::io::stdin().read_line().ok().expect("Failed to read line");
1731
1732     println!("{}", input);
1733 }
1734 ```
1735
1736 Let's go over these chunks, one by one:
1737
1738 ```{rust,ignore}
1739 std::io::stdin();
1740 ```
1741
1742 This calls a function, `stdin()`, that lives inside the `std::io` module. As
1743 you can imagine, everything in `std` is provided by Rust, the 'standard
1744 library.' We'll talk more about the module system later.
1745
1746 Since writing the fully qualified name all the time is annoying, we can use
1747 the `use` statement to import it in:
1748
1749 ```{rust}
1750 use std::io::stdin;
1751
1752 stdin();
1753 ```
1754
1755 However, it's considered better practice to not import individual functions, but
1756 to import the module, and only use one level of qualification:
1757
1758 ```{rust}
1759 use std::io;
1760
1761 io::stdin();
1762 ```
1763
1764 Let's update our example to use this style:
1765
1766 ```{rust,ignore}
1767 use std::io;
1768
1769 fn main() {
1770     println!("Type something!");
1771
1772     let input = io::stdin().read_line().ok().expect("Failed to read line");
1773
1774     println!("{}", input);
1775 }
1776 ```
1777
1778 Next up:
1779
1780 ```{rust,ignore}
1781 .read_line()
1782 ```
1783
1784 The `read_line()` method can be called on the result of `stdin()` to return
1785 a full line of input. Nice and easy.
1786
1787 ```{rust,ignore}
1788 .ok().expect("Failed to read line");
1789 ```
1790
1791 Do you remember this code?
1792
1793 ```{rust}
1794 enum OptionalInt {
1795     Value(int),
1796     Missing,
1797 }
1798
1799 fn main() {
1800     let x = OptionalInt::Value(5);
1801     let y = OptionalInt::Missing;
1802
1803     match x {
1804         OptionalInt::Value(n) => println!("x is {}", n),
1805         OptionalInt::Missing  => println!("x is missing!"),
1806     }
1807
1808     match y {
1809         OptionalInt::Value(n) => println!("y is {}", n),
1810         OptionalInt::Missing  => println!("y is missing!"),
1811     }
1812 }
1813 ```
1814
1815 We had to match each time to see if we had a value or not. In this case,
1816 though, we _know_ that `x` has a `Value`, but `match` forces us to handle
1817 the `missing` case. This is what we want 99% of the time, but sometimes, we
1818 know better than the compiler.
1819
1820 Likewise, `read_line()` does not return a line of input. It _might_ return a
1821 line of input, though it might also fail to do so. This could happen if our program
1822 isn't running in a terminal, but as part of a cron job, or some other context
1823 where there's no standard input. Because of this, `read_line` returns a type
1824 very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about
1825 `IoResult<T>` yet because it is the **generic** form of our `OptionalInt`.
1826 Until then, you can think of it as being the same thing, just for any type –
1827 not just `int`s.
1828
1829 Rust provides a method on these `IoResult<T>`s called `ok()`, which does the
1830 same thing as our `match` statement but assumes that we have a valid value.
1831 We then call `expect()` on the result, which will terminate our program if we
1832 don't have a valid value. In this case, if we can't get input, our program
1833 doesn't work, so we're okay with that. In most cases, we would want to handle
1834 the error case explicitly. `expect()` allows us to give an error message if
1835 this crash happens.
1836
1837 We will cover the exact details of how all of this works later in the Guide.
1838 For now, this gives you enough of a basic understanding to work with.
1839
1840 Back to the code we were working on! Here's a refresher:
1841
1842 ```{rust,ignore}
1843 use std::io;
1844
1845 fn main() {
1846     println!("Type something!");
1847
1848     let input = io::stdin().read_line().ok().expect("Failed to read line");
1849
1850     println!("{}", input);
1851 }
1852 ```
1853
1854 With long lines like this, Rust gives you some flexibility with the whitespace.
1855 We _could_ write the example like this:
1856
1857 ```{rust,ignore}
1858 use std::io;
1859
1860 fn main() {
1861     println!("Type something!");
1862
1863                                                   // here, we'll show the types at each step
1864
1865     let input = io::stdin()                       // std::io::stdio::StdinReader
1866                   .read_line()                    // IoResult<String>
1867                   .ok()                           // Option<String>
1868                   .expect("Failed to read line"); // String
1869
1870     println!("{}", input);
1871 }
1872 ```
1873
1874 Sometimes, this makes things more readable – sometimes, less. Use your judgement
1875 here.
1876
1877 That's all you need to get basic input from the standard input! It's not too
1878 complicated, but there are a number of small parts.
1879
1880 # Guessing Game
1881
1882 Okay! We've got the basics of Rust down. Let's write a bigger program.
1883
1884 For our first project, we'll implement a classic beginner programming problem:
1885 the guessing game. Here's how it works: Our program will generate a random
1886 integer between one and a hundred. It will then prompt us to enter a guess.
1887 Upon entering our guess, it will tell us if we're too low or too high. Once we
1888 guess correctly, it will congratulate us. Sound good?
1889
1890 ## Set up
1891
1892 Let's set up a new project. Go to your projects directory. Remember how we
1893 had to create our directory structure and a `Cargo.toml` for `hello_world`? Cargo
1894 has a command that does that for us. Let's give it a shot:
1895
1896 ```{bash}
1897 $ cd ~/projects
1898 $ cargo new guessing_game --bin
1899 $ cd guessing_game
1900 ```
1901
1902 We pass the name of our project to `cargo new`, and then the `--bin` flag,
1903 since we're making a binary, rather than a library.
1904
1905 Check out the generated `Cargo.toml`:
1906
1907 ```toml
1908 [package]
1909
1910 name = "guessing_game"
1911 version = "0.0.1"
1912 authors = ["Your Name <you@example.com>"]
1913 ```
1914
1915 Cargo gets this information from your environment. If it's not correct, go ahead
1916 and fix that.
1917
1918 Finally, Cargo generated a "Hello, world!" for us. Check out `src/main.rs`:
1919
1920 ```{rust}
1921 fn main() {
1922     println!("Hello, world!")
1923 }
1924 ```
1925
1926 Let's try compiling what Cargo gave us:
1927
1928 ```{bash}
1929 $ cargo build
1930    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1931 ```
1932
1933 Excellent! Open up your `src/main.rs` again. We'll be writing all of
1934 our code in this file. We'll talk about multiple-file projects later on in the
1935 guide.
1936
1937 Before we move on, let me show you one more Cargo command: `run`. `cargo run`
1938 is kind of like `cargo build`, but it also then runs the produced executable.
1939 Try it out:
1940
1941 ```bash
1942 $ cargo run
1943    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1944      Running `target/guessing_game`
1945 Hello, world!
1946 ```
1947
1948 Great! The `run` command comes in handy when you need to rapidly iterate on a project.
1949 Our game is just such a project, we need to quickly test each iteration before moving on to the next one.
1950
1951 ## Processing a Guess
1952
1953 Let's get to it! The first thing we need to do for our guessing game is
1954 allow our player to input a guess. Put this in your `src/main.rs`:
1955
1956 ```{rust,no_run}
1957 use std::io;
1958
1959 fn main() {
1960     println!("Guess the number!");
1961
1962     println!("Please input your guess.");
1963
1964     let input = io::stdin().read_line()
1965                            .ok()
1966                            .expect("Failed to read line");
1967
1968     println!("You guessed: {}", input);
1969 }
1970 ```
1971
1972 You've seen this code before, when we talked about standard input. We
1973 import the `std::io` module with `use`, and then our `main` function contains
1974 our program's logic. We print a little message announcing the game, ask the
1975 user to input a guess, get their input, and then print it out.
1976
1977 Because we talked about this in the section on standard I/O, I won't go into
1978 more details here. If you need a refresher, go re-read that section.
1979
1980 ## Generating a secret number
1981
1982 Next, we need to generate a secret number. To do that, we need to use Rust's
1983 random number generation, which we haven't talked about yet. Rust includes a
1984 bunch of interesting functions in its standard library. If you need a bit of
1985 code, it's possible that it's already been written for you! In this case,
1986 we do know that Rust has random number generation, but we don't know how to
1987 use it.
1988
1989 Enter the docs. Rust has a page specifically to document the standard library.
1990 You can find that page [here](std/index.html). There's a lot of information on
1991 that page, but the best part is the search bar. Right up at the top, there's
1992 a box that you can enter in a search term. The search is pretty primitive
1993 right now, but is getting better all the time. If you type 'random' in that
1994 box, the page will update to [this one](std/index.html?search=random). The very
1995 first result is a link to [`std::rand::random`](std/rand/fn.random.html). If we
1996 click on that result, we'll be taken to its documentation page.
1997
1998 This page shows us a few things: the type signature of the function, some
1999 explanatory text, and then an example. Let's try to modify our code to add in the
2000 `random` function and see what happens:
2001
2002 ```{rust,ignore}
2003 use std::io;
2004 use std::rand;
2005
2006 fn main() {
2007     println!("Guess the number!");
2008
2009     let secret_number = (rand::random() % 100i) + 1i; // secret_number: int
2010
2011     println!("The secret number is: {}", secret_number);
2012
2013     println!("Please input your guess.");
2014
2015     let input = io::stdin().read_line()
2016                            .ok()
2017                            .expect("Failed to read line");
2018
2019
2020     println!("You guessed: {}", input);
2021 }
2022 ```
2023
2024 The first thing we changed was to `use std::rand`, as the docs
2025 explained.  We then added in a `let` expression to create a variable binding
2026 named `secret_number`, and we printed out its result.
2027
2028 Also, you may wonder why we are using `%` on the result of `rand::random()`.
2029 This operator is called 'modulo', and it returns the remainder of a division.
2030 By taking the modulo of the result of `rand::random()`, we're limiting the
2031 values to be between 0 and 99. Then, we add one to the result, making it from 1
2032 to 100. Using modulo can give you a very, very small bias in the result, but
2033 for this example, it is not important.
2034
2035 Let's try to compile this using `cargo build`:
2036
2037 ```bash
2038 $ cargo build
2039    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2040 src/main.rs:7:26: 7:34 error: the type of this value must be known in this context
2041 src/main.rs:7     let secret_number = (rand::random() % 100i) + 1i;
2042                                        ^~~~~~~~
2043 error: aborting due to previous error
2044 ```
2045
2046 It didn't work! Rust says "the type of this value must be known in this
2047 context." What's up with that? Well, as it turns out, `rand::random()` can
2048 generate many kinds of random values, not just integers. And in this case, Rust
2049 isn't sure what kind of value `random()` should generate. So we have to help
2050 it. With number literals, we just add an `i` onto the end to tell Rust they're
2051 integers, but that does not work with functions. There's a different syntax,
2052 and it looks like this:
2053
2054 ```{rust,ignore}
2055 rand::random::<int>();
2056 ```
2057
2058 This says "please give me a random `int` value." We can change our code to use
2059 this hint:
2060
2061 ```{rust,no_run}
2062 use std::io;
2063 use std::rand;
2064
2065 fn main() {
2066     println!("Guess the number!");
2067
2068     let secret_number = (rand::random::<int>() % 100i) + 1i;
2069
2070     println!("The secret number is: {}", secret_number);
2071
2072     println!("Please input your guess.");
2073
2074     let input = io::stdin().read_line()
2075                            .ok()
2076                            .expect("Failed to read line");
2077
2078
2079     println!("You guessed: {}", input);
2080 }
2081 ```
2082
2083 Try running our new program a few times:
2084
2085 ```bash
2086 $ cargo run
2087    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2088      Running `target/guessing_game`
2089 Guess the number!
2090 The secret number is: 7
2091 Please input your guess.
2092 4
2093 You guessed: 4
2094 $ ./target/guessing_game
2095 Guess the number!
2096 The secret number is: 83
2097 Please input your guess.
2098 5
2099 You guessed: 5
2100 $ ./target/guessing_game
2101 Guess the number!
2102 The secret number is: -29
2103 Please input your guess.
2104 42
2105 You guessed: 42
2106 ```
2107
2108 Wait. Negative 29? We wanted a number between one and a hundred! We have two
2109 options here: we can either ask `random()` to generate an unsigned integer, which
2110 can only be positive, or we can use the `abs()` function. Let's go with the
2111 unsigned integer approach. If we want a random positive number, we should ask for
2112 a random positive number. Our code looks like this now:
2113
2114 ```{rust,no_run}
2115 use std::io;
2116 use std::rand;
2117
2118 fn main() {
2119     println!("Guess the number!");
2120
2121     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2122
2123     println!("The secret number is: {}", secret_number);
2124
2125     println!("Please input your guess.");
2126
2127     let input = io::stdin().read_line()
2128                            .ok()
2129                            .expect("Failed to read line");
2130
2131
2132     println!("You guessed: {}", input);
2133 }
2134 ```
2135
2136 And trying it out:
2137
2138 ```bash
2139 $ cargo run
2140    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2141      Running `target/guessing_game`
2142 Guess the number!
2143 The secret number is: 57
2144 Please input your guess.
2145 3
2146 You guessed: 3
2147 ```
2148
2149 Great! Next up: let's compare our guess to the secret guess.
2150
2151 ## Comparing guesses
2152
2153 If you remember, earlier in the guide, we made a `cmp` function that compared
2154 two numbers. Let's add that in, along with a `match` statement to compare our
2155 guess to the secret number:
2156
2157 ```{rust,ignore}
2158 use std::io;
2159 use std::rand;
2160 use std::cmp::Ordering;
2161
2162 fn main() {
2163     println!("Guess the number!");
2164
2165     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2166
2167     println!("The secret number is: {}", secret_number);
2168
2169     println!("Please input your guess.");
2170
2171     let input = io::stdin().read_line()
2172                            .ok()
2173                            .expect("Failed to read line");
2174
2175
2176     println!("You guessed: {}", input);
2177
2178     match cmp(input, secret_number) {
2179         Ordering::Less    => println!("Too small!"),
2180         Ordering::Greater => println!("Too big!"),
2181         Ordering::Equal   => println!("You win!"),
2182     }
2183 }
2184
2185 fn cmp(a: int, b: int) -> Ordering {
2186     if a < b { Ordering::Less }
2187     else if a > b { Ordering::Greater }
2188     else { Ordering::Equal }
2189 }
2190 ```
2191
2192 If we try to compile, we'll get some errors:
2193
2194 ```bash
2195 $ cargo build
2196    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2197 src/main.rs:20:15: 20:20 error: mismatched types: expected `int` but found `collections::string::String` (expected int but found struct collections::string::String)
2198 src/main.rs:20     match cmp(input, secret_number) {
2199                              ^~~~~
2200 src/main.rs:20:22: 20:35 error: mismatched types: expected `int` but found `uint` (expected int but found uint)
2201 src/main.rs:20     match cmp(input, secret_number) {
2202                                     ^~~~~~~~~~~~~
2203 error: aborting due to 2 previous errors
2204 ```
2205
2206 This often happens when writing Rust programs, and is one of Rust's greatest
2207 strengths. You try out some code, see if it compiles, and Rust tells you that
2208 you've done something wrong. In this case, our `cmp` function works on integers,
2209 but we've given it unsigned integers. In this case, the fix is easy, because
2210 we wrote the `cmp` function! Let's change it to take `uint`s:
2211
2212 ```{rust,ignore}
2213 use std::io;
2214 use std::rand;
2215 use std::cmp::Ordering;
2216
2217 fn main() {
2218     println!("Guess the number!");
2219
2220     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2221
2222     println!("The secret number is: {}", secret_number);
2223
2224     println!("Please input your guess.");
2225
2226     let input = io::stdin().read_line()
2227                            .ok()
2228                            .expect("Failed to read line");
2229
2230
2231     println!("You guessed: {}", input);
2232
2233     match cmp(input, secret_number) {
2234         Ordering::Less    => println!("Too small!"),
2235         Ordering::Greater => println!("Too big!"),
2236         Ordering::Equal   => println!("You win!"),
2237     }
2238 }
2239
2240 fn cmp(a: uint, b: uint) -> Ordering {
2241     if a < b { Ordering::Less }
2242     else if a > b { Ordering::Greater }
2243     else { Ordering::Equal }
2244 }
2245 ```
2246
2247 And try compiling again:
2248
2249 ```bash
2250 $ cargo build
2251    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2252 src/main.rs:20:15: 20:20 error: mismatched types: expected `uint` but found `collections::string::String` (expected uint but found struct collections::string::String)
2253 src/main.rs:20     match cmp(input, secret_number) {
2254                              ^~~~~
2255 error: aborting due to previous error
2256 ```
2257
2258 This error is similar to the last one: we expected to get a `uint`, but we got
2259 a `String` instead! That's because our `input` variable is coming from the
2260 standard input, and you can guess anything. Try it:
2261
2262 ```bash
2263 $ ./target/guessing_game
2264 Guess the number!
2265 The secret number is: 73
2266 Please input your guess.
2267 hello
2268 You guessed: hello
2269 ```
2270
2271 Oops! Also, you'll note that we just ran our program even though it didn't compile.
2272 This works because the older version we did successfully compile was still lying
2273 around. Gotta be careful!
2274
2275 Anyway, we have a `String`, but we need a `uint`. What to do? Well, there's
2276 a function for that:
2277
2278 ```{rust,ignore}
2279 let input = io::stdin().read_line()
2280                        .ok()
2281                        .expect("Failed to read line");
2282 let input_num: Option<uint> = input.parse();
2283 ```
2284
2285 The `parse` function takes in a `&str` value and converts it into something.
2286 We tell it what kind of something with a type hint. Remember our type hint with
2287 `random()`? It looked like this:
2288
2289 ```{rust,ignore}
2290 rand::random::<uint>();
2291 ```
2292
2293 There's an alternate way of providing a hint too, and that's declaring the type
2294 in a `let`:
2295
2296 ```{rust,ignore}
2297 let x: uint = rand::random();
2298 ```
2299
2300 In this case, we say `x` is a `uint` explicitly, so Rust is able to properly
2301 tell `random()` what to generate. In a similar fashion, both of these work:
2302
2303 ```{rust,ignore}
2304 let input_num = "5".parse::<uint>();         // input_num: Option<uint>
2305 let input_num: Option<uint> = "5".parse();   // input_num: Option<uint>
2306 ```
2307
2308 Anyway, with us now converting our input to a number, our code looks like this:
2309
2310 ```{rust,ignore}
2311 use std::io;
2312 use std::rand;
2313 use std::cmp::Ordering;
2314
2315 fn main() {
2316     println!("Guess the number!");
2317
2318     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2319
2320     println!("The secret number is: {}", secret_number);
2321
2322     println!("Please input your guess.");
2323
2324     let input = io::stdin().read_line()
2325                            .ok()
2326                            .expect("Failed to read line");
2327     let input_num: Option<uint> = input.parse();
2328
2329     println!("You guessed: {}", input_num);
2330
2331     match cmp(input_num, secret_number) {
2332         Ordering::Less    => println!("Too small!"),
2333         Ordering::Greater => println!("Too big!"),
2334         Ordering::Equal   => println!("You win!"),
2335     }
2336 }
2337
2338 fn cmp(a: uint, b: uint) -> Ordering {
2339     if a < b { Ordering::Less }
2340     else if a > b { Ordering::Greater }
2341     else { Ordering::Equal }
2342 }
2343 ```
2344
2345 Let's try it out!
2346
2347 ```bash
2348 $ cargo build
2349    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2350 src/main.rs:22:15: 22:24 error: mismatched types: expected `uint` but found `core::option::Option<uint>` (expected uint but found enum core::option::Option)
2351 src/main.rs:22     match cmp(input_num, secret_number) {
2352                              ^~~~~~~~~
2353 error: aborting due to previous error
2354 ```
2355
2356 Oh yeah! Our `input_num` has the type `Option<uint>`, rather than `uint`. We
2357 need to unwrap the Option. If you remember from before, `match` is a great way
2358 to do that. Try this code:
2359
2360 ```{rust,no_run}
2361 use std::io;
2362 use std::rand;
2363 use std::cmp::Ordering;
2364
2365 fn main() {
2366     println!("Guess the number!");
2367
2368     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2369
2370     println!("The secret number is: {}", secret_number);
2371
2372     println!("Please input your guess.");
2373
2374     let input = io::stdin().read_line()
2375                            .ok()
2376                            .expect("Failed to read line");
2377     let input_num: Option<uint> = input.parse();
2378
2379     let num = match input_num {
2380         Some(num) => num,
2381         None      => {
2382             println!("Please input a number!");
2383             return;
2384         }
2385     };
2386
2387
2388     println!("You guessed: {}", num);
2389
2390     match cmp(num, secret_number) {
2391         Ordering::Less    => println!("Too small!"),
2392         Ordering::Greater => println!("Too big!"),
2393         Ordering::Equal   => println!("You win!"),
2394     }
2395 }
2396
2397 fn cmp(a: uint, b: uint) -> Ordering {
2398     if a < b { Ordering::Less }
2399     else if a > b { Ordering::Greater }
2400     else { Ordering::Equal }
2401 }
2402 ```
2403
2404 We use a `match` to either give us the `uint` inside of the `Option`, or else
2405 print an error message and return. Let's give this a shot:
2406
2407 ```bash
2408 $ cargo run
2409    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2410      Running `target/guessing_game`
2411 Guess the number!
2412 The secret number is: 17
2413 Please input your guess.
2414 5
2415 Please input a number!
2416 ```
2417
2418 Uh, what? But we did!
2419
2420 ... actually, we didn't. See, when you get a line of input from `stdin()`,
2421 you get all the input. Including the `\n` character from you pressing Enter.
2422 Therefore, `parse()` sees the string `"5\n"` and says "nope, that's not a
2423 number; there's non-number stuff in there!" Luckily for us, `&str`s have an easy
2424 method we can use defined on them: `trim()`. One small modification, and our
2425 code looks like this:
2426
2427 ```{rust,no_run}
2428 use std::io;
2429 use std::rand;
2430 use std::cmp::Ordering;
2431
2432 fn main() {
2433     println!("Guess the number!");
2434
2435     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2436
2437     println!("The secret number is: {}", secret_number);
2438
2439     println!("Please input your guess.");
2440
2441     let input = io::stdin().read_line()
2442                            .ok()
2443                            .expect("Failed to read line");
2444     let input_num: Option<uint> = input.trim().parse();
2445
2446     let num = match input_num {
2447         Some(num) => num,
2448         None      => {
2449             println!("Please input a number!");
2450             return;
2451         }
2452     };
2453
2454
2455     println!("You guessed: {}", num);
2456
2457     match cmp(num, secret_number) {
2458         Ordering::Less    => println!("Too small!"),
2459         Ordering::Greater => println!("Too big!"),
2460         Ordering::Equal   => println!("You win!"),
2461     }
2462 }
2463
2464 fn cmp(a: uint, b: uint) -> Ordering {
2465     if a < b { Ordering::Less }
2466     else if a > b { Ordering::Greater }
2467     else { Ordering::Equal }
2468 }
2469 ```
2470
2471 Let's try it!
2472
2473 ```bash
2474 $ cargo run
2475    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2476      Running `target/guessing_game`
2477 Guess the number!
2478 The secret number is: 58
2479 Please input your guess.
2480   76
2481 You guessed: 76
2482 Too big!
2483 ```
2484
2485 Nice! You can see I even added spaces before my guess, and it still figured
2486 out that I guessed 76. Run the program a few times, and verify that guessing
2487 the number works, as well as guessing a number too small.
2488
2489 The Rust compiler helped us out quite a bit there! This technique is called
2490 "lean on the compiler", and it's often useful when working on some code. Let
2491 the error messages help guide you towards the correct types.
2492
2493 Now we've got most of the game working, but we can only make one guess. Let's
2494 change that by adding loops!
2495
2496 ## Looping
2497
2498 As we already discussed, the `loop` keyword gives us an infinite loop.
2499 Let's add that in:
2500
2501 ```{rust,no_run}
2502 use std::io;
2503 use std::rand;
2504 use std::cmp::Ordering;
2505
2506 fn main() {
2507     println!("Guess the number!");
2508
2509     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2510
2511     println!("The secret number is: {}", secret_number);
2512
2513     loop {
2514
2515         println!("Please input your guess.");
2516
2517         let input = io::stdin().read_line()
2518                                .ok()
2519                                .expect("Failed to read line");
2520         let input_num: Option<uint> = input.trim().parse();
2521
2522         let num = match input_num {
2523             Some(num) => num,
2524             None      => {
2525                 println!("Please input a number!");
2526                 return;
2527             }
2528         };
2529
2530
2531         println!("You guessed: {}", num);
2532
2533         match cmp(num, secret_number) {
2534             Ordering::Less    => println!("Too small!"),
2535             Ordering::Greater => println!("Too big!"),
2536             Ordering::Equal   => println!("You win!"),
2537         }
2538     }
2539 }
2540
2541 fn cmp(a: uint, b: uint) -> Ordering {
2542     if a < b { Ordering::Less }
2543     else if a > b { Ordering::Greater }
2544     else { Ordering::Equal }
2545 }
2546 ```
2547
2548 And try it out. But wait, didn't we just add an infinite loop? Yup. Remember
2549 that `return`? If we give a non-number answer, we'll `return` and quit. Observe:
2550
2551 ```bash
2552 $ cargo run
2553    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2554      Running `target/guessing_game`
2555 Guess the number!
2556 The secret number is: 59
2557 Please input your guess.
2558 45
2559 You guessed: 45
2560 Too small!
2561 Please input your guess.
2562 60
2563 You guessed: 60
2564 Too big!
2565 Please input your guess.
2566 59
2567 You guessed: 59
2568 You win!
2569 Please input your guess.
2570 quit
2571 Please input a number!
2572 ```
2573
2574 Ha! `quit` actually quits. As does any other non-number input. Well, this is
2575 suboptimal to say the least. First, let's actually quit when you win the game:
2576
2577 ```{rust,no_run}
2578 use std::io;
2579 use std::rand;
2580 use std::cmp::Ordering;
2581
2582 fn main() {
2583     println!("Guess the number!");
2584
2585     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2586
2587     println!("The secret number is: {}", secret_number);
2588
2589     loop {
2590
2591         println!("Please input your guess.");
2592
2593         let input = io::stdin().read_line()
2594                                .ok()
2595                                .expect("Failed to read line");
2596         let input_num: Option<uint> = input.trim().parse();
2597
2598         let num = match input_num {
2599             Some(num) => num,
2600             None      => {
2601                 println!("Please input a number!");
2602                 return;
2603             }
2604         };
2605
2606
2607         println!("You guessed: {}", num);
2608
2609         match cmp(num, secret_number) {
2610             Ordering::Less    => println!("Too small!"),
2611             Ordering::Greater => println!("Too big!"),
2612             Ordering::Equal   => {
2613                 println!("You win!");
2614                 return;
2615             },
2616         }
2617     }
2618 }
2619
2620 fn cmp(a: uint, b: uint) -> Ordering {
2621     if a < b { Ordering::Less }
2622     else if a > b { Ordering::Greater }
2623     else { Ordering::Equal }
2624 }
2625 ```
2626
2627 By adding the `return` line after the `You win!`, we'll exit the program when
2628 we win. We have just one more tweak to make: when someone inputs a non-number,
2629 we don't want to quit, we just want to ignore it. Change that `return` to
2630 `continue`:
2631
2632
2633 ```{rust,no_run}
2634 use std::io;
2635 use std::rand;
2636 use std::cmp::Ordering;
2637
2638 fn main() {
2639     println!("Guess the number!");
2640
2641     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2642
2643     println!("The secret number is: {}", secret_number);
2644
2645     loop {
2646
2647         println!("Please input your guess.");
2648
2649         let input = io::stdin().read_line()
2650                                .ok()
2651                                .expect("Failed to read line");
2652         let input_num: Option<uint> = input.trim().parse();
2653
2654         let num = match input_num {
2655             Some(num) => num,
2656             None      => {
2657                 println!("Please input a number!");
2658                 continue;
2659             }
2660         };
2661
2662
2663         println!("You guessed: {}", num);
2664
2665         match cmp(num, secret_number) {
2666             Ordering::Less    => println!("Too small!"),
2667             Ordering::Greater => println!("Too big!"),
2668             Ordering::Equal   => {
2669                 println!("You win!");
2670                 return;
2671             },
2672         }
2673     }
2674 }
2675
2676 fn cmp(a: uint, b: uint) -> Ordering {
2677     if a < b { Ordering::Less }
2678     else if a > b { Ordering::Greater }
2679     else { Ordering::Equal }
2680 }
2681 ```
2682
2683 Now we should be good! Let's try:
2684
2685 ```bash
2686 $ cargo run
2687    Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2688      Running `target/guessing_game`
2689 Guess the number!
2690 The secret number is: 61
2691 Please input your guess.
2692 10
2693 You guessed: 10
2694 Too small!
2695 Please input your guess.
2696 99
2697 You guessed: 99
2698 Too big!
2699 Please input your guess.
2700 foo
2701 Please input a number!
2702 Please input your guess.
2703 61
2704 You guessed: 61
2705 You win!
2706 ```
2707
2708 Awesome! With one tiny last tweak, we have finished the guessing game. Can you
2709 think of what it is? That's right, we don't want to print out the secret number.
2710 It was good for testing, but it kind of ruins the game. Here's our final source:
2711
2712 ```{rust,no_run}
2713 use std::io;
2714 use std::rand;
2715 use std::cmp::Ordering;
2716
2717 fn main() {
2718     println!("Guess the number!");
2719
2720     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2721
2722     loop {
2723
2724         println!("Please input your guess.");
2725
2726         let input = io::stdin().read_line()
2727                                .ok()
2728                                .expect("Failed to read line");
2729         let input_num: Option<uint> = input.trim().parse();
2730
2731         let num = match input_num {
2732             Some(num) => num,
2733             None      => {
2734                 println!("Please input a number!");
2735                 continue;
2736             }
2737         };
2738
2739
2740         println!("You guessed: {}", num);
2741
2742         match cmp(num, secret_number) {
2743             Ordering::Less    => println!("Too small!"),
2744             Ordering::Greater => println!("Too big!"),
2745             Ordering::Equal   => {
2746                 println!("You win!");
2747                 return;
2748             },
2749         }
2750     }
2751 }
2752
2753 fn cmp(a: uint, b: uint) -> Ordering {
2754     if a < b { Ordering::Less }
2755     else if a > b { Ordering::Greater }
2756     else { Ordering::Equal }
2757 }
2758 ```
2759
2760 ## Complete!
2761
2762 At this point, you have successfully built the Guessing Game! Congratulations!
2763
2764 You've now learned the basic syntax of Rust. All of this is relatively close to
2765 various other programming languages you have used in the past. These
2766 fundamental syntactical and semantic elements will form the foundation for the
2767 rest of your Rust education.
2768
2769 Now that you're an expert at the basics, it's time to learn about some of
2770 Rust's more unique features.
2771
2772 # Crates and Modules
2773
2774 Rust features a strong module system, but it works a bit differently than in
2775 other programming languages. Rust's module system has two main components:
2776 **crate**s and **module**s.
2777
2778 A crate is Rust's unit of independent compilation. Rust always compiles one
2779 crate at a time, producing either a library or an executable. However, executables
2780 usually depend on libraries, and many libraries depend on other libraries as well.
2781 To support this, crates can depend on other crates.
2782
2783 Each crate contains a hierarchy of modules. This tree starts off with a single
2784 module, called the **crate root**. Within the crate root, we can declare other
2785 modules, which can contain other modules, as deeply as you'd like.
2786
2787 Note that we haven't mentioned anything about files yet. Rust does not impose a
2788 particular relationship between your filesystem structure and your module
2789 structure. That said, there is a conventional approach to how Rust looks for
2790 modules on the file system, but it's also overridable.
2791
2792 Enough talk, let's build something! Let's make a new project called `modules`.
2793
2794 ```{bash,ignore}
2795 $ cd ~/projects
2796 $ cargo new modules --bin
2797 $ cd modules
2798 ```
2799
2800 Let's double check our work by compiling:
2801
2802 ```{bash}
2803 $ cargo run
2804    Compiling modules v0.0.1 (file:///home/you/projects/modules)
2805      Running `target/modules`
2806 Hello, world!
2807 ```
2808
2809 Excellent! We already have a single crate here: our `src/main.rs` is a crate.
2810 Everything in that file is in the crate root. A crate that generates an executable
2811 defines a `main` function inside its root, as we've done here.
2812
2813 Let's define a new module inside our crate. Edit `src/main.rs` to look like this:
2814
2815 ```
2816 fn main() {
2817     println!("Hello, world!")
2818 }
2819
2820 mod hello {
2821     fn print_hello() {
2822         println!("Hello, world!")
2823     }
2824 }
2825 ```
2826
2827 We now have a module named `hello` inside of our crate root. Modules use
2828 `snake_case` naming, like functions and variable bindings.
2829
2830 Inside the `hello` module, we've defined a `print_hello` function. This will
2831 also print out our "hello world" message. Modules allow you to split up your
2832 program into nice neat boxes of functionality, grouping common things together,
2833 and keeping different things apart. It's kinda like having a set of shelves:
2834 a place for everything and everything in its place.
2835
2836 To call our `print_hello` function, we use the double colon (`::`):
2837
2838 ```{rust,ignore}
2839 hello::print_hello();
2840 ```
2841
2842 You've seen this before, with `io::stdin()` and `rand::random()`. Now you know
2843 how to make your own. However, crates and modules have rules about
2844 **visibility**, which controls who exactly may use the functions defined in a
2845 given module. By default, everything in a module is private, which means that
2846 it can only be used by other functions in the same module. This will not
2847 compile:
2848
2849 ```{rust,ignore}
2850 fn main() {
2851     hello::print_hello();
2852 }
2853
2854 mod hello {
2855     fn print_hello() {
2856         println!("Hello, world!")
2857     }
2858 }
2859 ```
2860
2861 It gives an error:
2862
2863 ```bash
2864    Compiling modules v0.0.1 (file:///home/you/projects/modules)
2865 src/main.rs:2:5: 2:23 error: function `print_hello` is private
2866 src/main.rs:2     hello::print_hello();
2867                   ^~~~~~~~~~~~~~~~~~
2868 ```
2869
2870 To make it public, we use the `pub` keyword:
2871
2872 ```{rust}
2873 fn main() {
2874     hello::print_hello();
2875 }
2876
2877 mod hello {
2878     pub fn print_hello() {
2879         println!("Hello, world!")
2880     }
2881 }
2882 ```
2883
2884 Usage of the `pub` keyword is sometimes called 'exporting', because
2885 we're making the function available for other modules. This will work:
2886
2887 ```bash
2888 $ cargo run
2889    Compiling modules v0.0.1 (file:///home/you/projects/modules)
2890      Running `target/modules`
2891 Hello, world!
2892 ```
2893
2894 Nice! There are more things we can do with modules, including moving them into
2895 their own files. This is enough detail for now.
2896
2897 # Testing
2898
2899 Traditionally, testing has not been a strong suit of most systems programming
2900 languages. Rust, however, has very basic testing built into the language
2901 itself.  While automated testing cannot prove that your code is bug-free, it is
2902 useful for verifying that certain behaviors work as intended.
2903
2904 Here's a very basic test:
2905
2906 ```{rust}
2907 #[test]
2908 fn is_one_equal_to_one() {
2909     assert_eq!(1i, 1i);
2910 }
2911 ```
2912
2913 You may notice something new: that `#[test]`. Before we get into the mechanics
2914 of testing, let's talk about attributes.
2915
2916 ## Attributes
2917
2918 Rust's testing system uses **attribute**s to mark which functions are tests.
2919 Attributes can be placed on any Rust **item**. Remember how most things in
2920 Rust are an expression, but `let` is not? Item declarations are also not
2921 expressions. Here's a list of things that qualify as an item:
2922
2923 * functions
2924 * modules
2925 * type definitions
2926 * structures
2927 * enumerations
2928 * static items
2929 * traits
2930 * implementations
2931
2932 You haven't learned about all of these things yet, but that's the list. As
2933 you can see, functions are at the top of it.
2934
2935 Attributes can appear in three ways:
2936
2937 1. A single identifier, the attribute name. `#[test]` is an example of this.
2938 2. An identifier followed by an equals sign (`=`) and a literal. `#[cfg=test]`
2939    is an example of this.
2940 3. An identifier followed by a parenthesized list of sub-attribute arguments.
2941    `#[cfg(unix, target_word_size = "32")]` is an example of this, where one of
2942     the sub-arguments is of the second kind.
2943
2944 There are a number of different kinds of attributes, enough that we won't go
2945 over them all here. Before we talk about the testing-specific attributes, I
2946 want to call out one of the most important kinds of attributes: stability
2947 markers.
2948
2949 ## Stability attributes
2950
2951 Rust provides six attributes to indicate the stability level of various
2952 parts of your library. The six levels are:
2953
2954 * deprecated: This item should no longer be used. No guarantee of backwards
2955   compatibility.
2956 * experimental: This item was only recently introduced or is otherwise in a
2957   state of flux. It may change significantly, or even be removed. No guarantee
2958   of backwards-compatibility.
2959 * unstable: This item is still under development and requires more testing to
2960   be considered stable. No guarantee of backwards-compatibility.
2961 * stable: This item is considered stable, and will not change significantly.
2962   Guarantee of backwards-compatibility.
2963 * frozen: This item is very stable, and is unlikely to change. Guarantee of
2964   backwards-compatibility.
2965 * locked: This item will never change unless a serious bug is found. Guarantee
2966   of backwards-compatibility.
2967
2968 All of Rust's standard library uses these attribute markers to communicate
2969 their relative stability, and you should use them in your code, as well.
2970 There's an associated attribute, `warn`, that allows you to warn when you
2971 import an item marked with certain levels: deprecated, experimental and
2972 unstable. For now, only deprecated warns by default, but this will change once
2973 the standard library has been stabilized.
2974
2975 You can use the `warn` attribute like this:
2976
2977 ```{rust,ignore}
2978 #![warn(unstable)]
2979 ```
2980
2981 And later, when you import a crate:
2982
2983 ```{rust,ignore}
2984 extern crate some_crate;
2985 ```
2986
2987 You'll get a warning if you use something marked unstable.
2988
2989 You may have noticed an exclamation point in the `warn` attribute declaration.
2990 The `!` in this attribute means that this attribute applies to the enclosing
2991 item, rather than to the item that follows the attribute. This `warn`
2992 attribute declaration applies to the enclosing crate itself, rather than
2993 to whatever item statement follows it:
2994
2995 ```{rust,ignore}
2996 // applies to the crate we're in
2997 #![warn(unstable)]
2998
2999 extern crate some_crate;
3000
3001 // applies to the following `fn`.
3002 #[test]
3003 fn a_test() {
3004   // ...
3005 }
3006 ```
3007
3008 ## Writing tests
3009
3010 Let's write a very simple crate in a test-driven manner. You know the drill by
3011 now: make a new project:
3012
3013 ```{bash,ignore}
3014 $ cd ~/projects
3015 $ cargo new testing --bin
3016 $ cd testing
3017 ```
3018
3019 And try it out:
3020
3021 ```bash
3022 $ cargo run
3023    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3024      Running `target/testing`
3025 Hello, world!
3026 ```
3027
3028 Great. Rust's infrastructure supports tests in two sorts of places, and they're
3029 for two kinds of tests: you include **unit test**s inside of the crate itself,
3030 and you place **integration test**s inside a `tests` directory. "Unit tests"
3031 are small tests that test one focused unit; "integration tests" test multiple
3032 units in integration. That being said, this is a social convention – they're no
3033 different in syntax. Let's make a `tests` directory:
3034
3035 ```{bash,ignore}
3036 $ mkdir tests
3037 ```
3038
3039 Next, let's create an integration test in `tests/lib.rs`:
3040
3041 ```{rust,no_run}
3042 #[test]
3043 fn foo() {
3044     assert!(false);
3045 }
3046 ```
3047
3048 It doesn't matter what you name your test functions, though it's nice if
3049 you give them descriptive names. You'll see why in a moment. We then use a
3050 macro, `assert!`, to assert that something is true. In this case, we're giving
3051 it `false`, so this test should fail. Let's try it!
3052
3053 ```bash
3054 $ cargo test
3055    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3056 /home/you/projects/testing/src/main.rs:1:1: 3:2 warning: function is never used: `main`, #[warn(dead_code)] on by default
3057 /home/you/projects/testing/src/main.rs:1 fn main() {
3058 /home/you/projects/testing/src/main.rs:2     println!("Hello, world!")
3059 /home/you/projects/testing/src/main.rs:3 }
3060      Running target/lib-654ce120f310a3a5
3061
3062 running 1 test
3063 test foo ... FAILED
3064
3065 failures:
3066
3067 ---- foo stdout ----
3068         thread 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
3069
3070
3071
3072 failures:
3073     foo
3074
3075 test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
3076
3077 thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
3078 ```
3079
3080 Lots of output! Let's break this down:
3081
3082 ```bash
3083 $ cargo test
3084    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3085 ```
3086
3087 You can run all of your tests with `cargo test`. This runs both your tests in
3088 `tests`, as well as the tests you put inside of your crate.
3089
3090 ```text
3091 /home/you/projects/testing/src/main.rs:1:1: 3:2 warning: function is never used: `main`, #[warn(dead_code)] on by default
3092 /home/you/projects/testing/src/main.rs:1 fn main() {
3093 /home/you/projects/testing/src/main.rs:2     println!("Hello, world!")
3094 /home/you/projects/testing/src/main.rs:3 }
3095 ```
3096
3097 Rust has a **lint** called 'warn on dead code' used by default. A lint is a
3098 bit of code that checks your code, and can tell you things about it. In this
3099 case, Rust is warning us that we've written some code that's never used: our
3100 `main` function. Of course, since we're running tests, we don't use `main`.
3101 We'll turn this lint off for just this function soon. For now, just ignore this
3102 output.
3103
3104 ```text
3105      Running target/lib-654ce120f310a3a5
3106
3107 running 1 test
3108 test foo ... FAILED
3109 ```
3110
3111 Now we're getting somewhere. Remember when we talked about naming our tests
3112 with good names? This is why. Here, it says 'test foo' because we called our
3113 test 'foo'. If we had given it a good name, it'd be more clear which test
3114 failed, especially as we accumulate more tests.
3115
3116 ```text
3117 failures:
3118
3119 ---- foo stdout ----
3120         thread 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
3121
3122
3123
3124 failures:
3125     foo
3126
3127 test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
3128
3129 thread '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:243
3130 ```
3131
3132 After all the tests run, Rust will show us any output from our failed tests.
3133 In this instance, Rust tells us that our assertion failed, with false. This was
3134 what we expected.
3135
3136 Whew! Let's fix our test:
3137
3138 ```{rust}
3139 #[test]
3140 fn foo() {
3141     assert!(true);
3142 }
3143 ```
3144
3145 And then try to run our tests again:
3146
3147 ```bash
3148 $ cargo test
3149    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3150      Running target/lib-654ce120f310a3a5
3151
3152 running 1 test
3153 test foo ... ok
3154
3155 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3156
3157      Running target/testing-6d7518593c7c3ee5
3158
3159 running 0 tests
3160
3161 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3162 ```
3163
3164 Nice! Our test passes, as we expected. Note how we didn't get the
3165 `main` warning this time? This is because `src/main.rs` didn't
3166 need recompiling, but we'll get that warning again if we
3167 change (and recompile) that file. Let's get rid of that
3168 warning; change your `src/main.rs` to look like this:
3169
3170 ```{rust}
3171 #[cfg(not(test))]
3172 fn main() {
3173     println!("Hello, world!")
3174 }
3175 ```
3176
3177 This attribute combines two things: `cfg` and `not`. The `cfg` attribute allows
3178 you to conditionally compile code based on something. The following item will
3179 only be compiled if the configuration says it's true. And when Cargo compiles
3180 our tests, it sets things up so that `cfg(test)` is true. But we want to only
3181 include `main` when it's _not_ true. So we use `not` to negate things:
3182 `cfg(not(test))` will only compile our code when the `cfg(test)` is false.
3183
3184 With this attribute, we won't get the warning (even
3185 though `src/main.rs` gets recompiled this time):
3186
3187 ```bash
3188 $ cargo test
3189    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3190      Running target/lib-654ce120f310a3a5
3191
3192 running 1 test
3193 test foo ... ok
3194
3195 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3196
3197      Running target/testing-6d7518593c7c3ee5
3198
3199 running 0 tests
3200
3201 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3202 ```
3203
3204 Nice. Okay, let's write a real test now. Change your `tests/lib.rs`
3205 to look like this:
3206
3207 ```{rust,ignore}
3208 #[test]
3209 fn math_checks_out() {
3210     let result = add_three_times_four(5i);
3211
3212     assert_eq!(32i, result);
3213 }
3214 ```
3215
3216 And try to run the test:
3217
3218 ```bash
3219 $ cargo test
3220    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3221 /home/you/projects/testing/tests/lib.rs:3:18: 3:38 error: unresolved name `add_three_times_four`.
3222 /home/you/projects/testing/tests/lib.rs:3     let result = add_three_times_four(5i);
3223                                                            ^~~~~~~~~~~~~~~~~~~~
3224 error: aborting due to previous error
3225 Build failed, waiting for other jobs to finish...
3226 Could not compile `testing`.
3227
3228 To learn more, run the command again with `--verbose`.
3229 ```
3230
3231 Rust can't find this function. That makes sense, as we didn't write it yet!
3232
3233 In order to share this code with our tests, we'll need to make a library crate.
3234 This is also just good software design: as we mentioned before, it's a good idea
3235 to put most of your functionality into a library crate, and have your executable
3236 crate use that library. This allows for code reuse.
3237
3238 To do that, we'll need to make a new module. Make a new file, `src/lib.rs`,
3239 and put this in it:
3240
3241 ```{rust}
3242 # fn main() {}
3243 pub fn add_three_times_four(x: int) -> int {
3244     (x + 3) * 4
3245 }
3246 ```
3247
3248 We're calling this file `lib.rs`, because Cargo uses that filename as the crate
3249 root by convention.
3250
3251 We'll then need to use this crate in our `src/main.rs`:
3252
3253 ```{rust,ignore}
3254 extern crate testing;
3255
3256 #[cfg(not(test))]
3257 fn main() {
3258     println!("Hello, world!")
3259 }
3260 ```
3261
3262 Finally, let's import this function in our `tests/lib.rs`:
3263
3264 ```{rust,ignore}
3265 extern crate testing;
3266 use testing::add_three_times_four;
3267
3268 #[test]
3269 fn math_checks_out() {
3270     let result = add_three_times_four(5i);
3271
3272     assert_eq!(32i, result);
3273 }
3274 ```
3275
3276 Let's give it a run:
3277
3278 ```bash
3279 $ cargo test
3280    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3281      Running target/lib-654ce120f310a3a5
3282
3283 running 1 test
3284 test math_checks_out ... ok
3285
3286 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3287
3288      Running target/testing-6d7518593c7c3ee5
3289
3290 running 0 tests
3291
3292 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3293
3294      Running target/testing-8a94b31f7fd2e8fe
3295
3296 running 0 tests
3297
3298 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3299
3300    Doc-tests testing
3301
3302 running 0 tests
3303
3304 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3305 ```
3306
3307 Great! One test passed. We've got an integration test showing that our public
3308 method works, but maybe we want to test some of the internal logic as well.
3309 While this function is simple, if it were more complicated, you can imagine
3310 we'd need more tests. Let's break it up into two helper functions and write
3311 some unit tests to test those.
3312
3313 Change your `src/lib.rs` to look like this:
3314
3315 ```{rust,ignore}
3316 pub fn add_three_times_four(x: int) -> int {
3317     times_four(add_three(x))
3318 }
3319
3320 fn add_three(x: int) -> int { x + 3 }
3321
3322 fn times_four(x: int) -> int { x * 4 }
3323 ```
3324
3325 If you run `cargo test`, you should get the same output:
3326
3327 ```bash
3328 $ cargo test
3329    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3330      Running target/lib-654ce120f310a3a5
3331
3332 running 1 test
3333 test math_checks_out ... ok
3334
3335 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3336
3337      Running target/testing-6d7518593c7c3ee5
3338
3339 running 0 tests
3340
3341 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3342
3343      Running target/testing-8a94b31f7fd2e8fe
3344
3345 running 0 tests
3346
3347 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3348
3349    Doc-tests testing
3350
3351 running 0 tests
3352
3353 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3354 ```
3355
3356 If we tried to write a test for these two new functions, it wouldn't
3357 work. For example:
3358
3359 ```{rust,ignore}
3360 extern crate testing;
3361 use testing::add_three_times_four;
3362 use testing::add_three;
3363
3364 #[test]
3365 fn math_checks_out() {
3366     let result = add_three_times_four(5i);
3367
3368     assert_eq!(32i, result);
3369 }
3370
3371 #[test]
3372 fn test_add_three() {
3373     let result = add_three(5i);
3374
3375     assert_eq!(8i, result);
3376 }
3377 ```
3378
3379 We'd get this error:
3380
3381 ```text
3382    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3383 /home/you/projects/testing/tests/lib.rs:3:5: 3:24 error: function `add_three` is private
3384 /home/you/projects/testing/tests/lib.rs:3 use testing::add_three;
3385                                               ^~~~~~~~~~~~~~~~~~~
3386 ```
3387
3388 Right. It's private. So external, integration tests won't work. We need a
3389 unit test. Open up your `src/lib.rs` and add this:
3390
3391 ```{rust,ignore}
3392 pub fn add_three_times_four(x: int) -> int {
3393     times_four(add_three(x))
3394 }
3395
3396 fn add_three(x: int) -> int { x + 3 }
3397
3398 fn times_four(x: int) -> int { x * 4 }
3399
3400 #[cfg(test)]
3401 mod test {
3402     use super::add_three;
3403     use super::times_four;
3404
3405     #[test]
3406     fn test_add_three() {
3407         let result = add_three(5i);
3408
3409         assert_eq!(8i, result);
3410     }
3411
3412     #[test]
3413     fn test_times_four() {
3414         let result = times_four(5i);
3415
3416         assert_eq!(20i, result);
3417     }
3418 }
3419 ```
3420
3421 Let's give it a shot:
3422
3423 ```bash
3424 $ cargo test
3425    Compiling testing v0.0.1 (file:///home/you/projects/testing)
3426      Running target/lib-654ce120f310a3a5
3427
3428 running 1 test
3429 test math_checks_out ... ok
3430
3431 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3432
3433      Running target/testing-6d7518593c7c3ee5
3434
3435 running 0 tests
3436
3437 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3438
3439      Running target/testing-8a94b31f7fd2e8fe
3440
3441 running 2 tests
3442 test test::test_times_four ... ok
3443 test test::test_add_three ... ok
3444
3445 test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured
3446
3447    Doc-tests testing
3448
3449 running 0 tests
3450
3451 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3452 ```
3453
3454 Cool! We now have two tests of our internal functions. You'll note that there
3455 are three sets of output now: one for `src/main.rs`, one for `src/lib.rs`, and
3456 one for `tests/lib.rs`. There's one interesting thing that we haven't talked
3457 about yet, and that's these lines:
3458
3459 ```{rust,ignore}
3460 use super::add_three;
3461 use super::times_four;
3462 ```
3463
3464 Because we've made a nested module, we can import functions from the parent
3465 module by using `super`. Sub-modules are allowed to 'see' private functions in
3466 the parent.
3467
3468 We've now covered the basics of testing. Rust's tools are primitive, but they
3469 work well in the simple cases. There are some Rustaceans working on building
3470 more complicated frameworks on top of all of this, but they're just starting
3471 out.
3472
3473 # Pointers
3474
3475 In systems programming, pointers are an incredibly important topic. Rust has a
3476 very rich set of pointers, and they operate differently than in many other
3477 languages. They are important enough that we have a specific [Pointer
3478 Guide](guide-pointers.html) that goes into pointers in much detail. In fact,
3479 while you're currently reading this guide, which covers the language in broad
3480 overview, there are a number of other guides that put a specific topic under a
3481 microscope. You can find the list of guides on the [documentation index
3482 page](index.html#guides).
3483
3484 In this section, we'll assume that you're familiar with pointers as a general
3485 concept. If you aren't, please read the [introduction to
3486 pointers](guide-pointers.html#an-introduction) section of the Pointer Guide,
3487 and then come back here. We'll wait.
3488
3489 Got the gist? Great. Let's talk about pointers in Rust.
3490
3491 ## References
3492
3493 The most primitive form of pointer in Rust is called a **reference**.
3494 References are created using the ampersand (`&`). Here's a simple
3495 reference:
3496
3497 ```{rust}
3498 let x = 5i;
3499 let y = &x;
3500 ```
3501
3502 `y` is a reference to `x`. To dereference (get the value being referred to
3503 rather than the reference itself) `y`, we use the asterisk (`*`):
3504
3505 ```{rust}
3506 let x = 5i;
3507 let y = &x;
3508
3509 assert_eq!(5i, *y);
3510 ```
3511
3512 Like any `let` binding, references are immutable by default.
3513
3514 You can declare that functions take a reference:
3515
3516 ```{rust}
3517 fn add_one(x: &int) -> int { *x + 1 }
3518
3519 fn main() {
3520     assert_eq!(6, add_one(&5));
3521 }
3522 ```
3523
3524 As you can see, we can make a reference from a literal by applying `&` as well.
3525 Of course, in this simple function, there's not a lot of reason to take `x` by
3526 reference. It's just an example of the syntax.
3527
3528 Because references are immutable, you can have multiple references that
3529 **alias** (point to the same place):
3530
3531 ```{rust}
3532 let x = 5i;
3533 let y = &x;
3534 let z = &x;
3535 ```
3536
3537 We can make a mutable reference by using `&mut` instead of `&`:
3538
3539 ```{rust}
3540 let mut x = 5i;
3541 let y = &mut x;
3542 ```
3543
3544 Note that `x` must also be mutable. If it isn't, like this:
3545
3546 ```{rust,ignore}
3547 let x = 5i;
3548 let y = &mut x;
3549 ```
3550
3551 Rust will complain:
3552
3553 ```text
3554 error: cannot borrow immutable local variable `x` as mutable
3555  let y = &mut x;
3556               ^
3557 ```
3558
3559 We don't want a mutable reference to immutable data! This error message uses a
3560 term we haven't talked about yet, 'borrow'. We'll get to that in just a moment.
3561
3562 This simple example actually illustrates a lot of Rust's power: Rust has
3563 prevented us, at compile time, from breaking our own rules. Because Rust's
3564 references check these kinds of rules entirely at compile time, there's no
3565 runtime overhead for this safety.  At runtime, these are the same as a raw
3566 machine pointer, like in C or C++.  We've just double-checked ahead of time
3567 that we haven't done anything dangerous.
3568
3569 Rust will also prevent us from creating two mutable references that alias.
3570 This won't work:
3571
3572 ```{rust,ignore}
3573 let mut x = 5i;
3574 let y = &mut x;
3575 let z = &mut x;
3576 ```
3577
3578 It gives us this error:
3579
3580 ```text
3581 error: cannot borrow `x` as mutable more than once at a time
3582      let z = &mut x;
3583                   ^
3584 note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3585      let y = &mut x;
3586                   ^
3587 note: previous borrow ends here
3588  fn main() {
3589      let mut x = 5i;
3590      let y = &mut x;
3591      let z = &mut x;
3592  }
3593  ^
3594 ```
3595
3596 This is a big error message. Let's dig into it for a moment. There are three
3597 parts: the error and two notes. The error says what we expected, we cannot have
3598 two mutable pointers that point to the same memory.
3599
3600 The two notes give some extra context. Rust's error messages often contain this
3601 kind of extra information when the error is complex. Rust is telling us two
3602 things: first, that the reason we cannot **borrow** `x` as `z` is that we
3603 previously borrowed `x` as `y`. The second note shows where `y`'s borrowing
3604 ends.
3605
3606 Wait, borrowing?
3607
3608 In order to truly understand this error, we have to learn a few new concepts:
3609 **ownership**, **borrowing**, and **lifetimes**.
3610
3611 ## Ownership, borrowing, and lifetimes
3612
3613 Whenever a resource of some kind is created, something must be responsible
3614 for destroying that resource as well. Given that we're discussing pointers
3615 right now, let's discuss this in the context of memory allocation, though
3616 it applies to other resources as well.
3617
3618 When you allocate heap memory, you need a mechanism to free that memory. Many
3619 languages use a garbage collector to handle deallocation. This is a valid,
3620 time-tested strategy, but it's not without its drawbacks: it adds overhead, and
3621 can lead to unpredictable pauses in execution. Because the programmer does not
3622 have to think as much about deallocation, allocation becomes something
3623 commonplace, leading to more memory usage. And if you need precise control
3624 over when something is deallocated, leaving it up to your runtime can make this
3625 difficult.
3626
3627 Rust chooses a different path, and that path is called **ownership**. Any
3628 binding that creates a resource is the **owner** of that resource.
3629
3630 Being an owner affords you some privileges:
3631
3632 1. You control when that resource is deallocated.
3633 2. You may lend that resource, immutably, to as many borrowers as you'd like.
3634 3. You may lend that resource, mutably, to a single borrower.
3635
3636 But it also comes with some restrictions:
3637
3638 1. If someone is borrowing your resource (either mutably or immutably), you may
3639    not mutate the resource or mutably lend it to someone.
3640 2. If someone is mutably borrowing your resource, you may not lend it out at
3641    all (mutably or immutably) or access it in any way.
3642
3643 What's up with all this 'lending' and 'borrowing'? When you allocate memory,
3644 you get a pointer to that memory. This pointer allows you to manipulate said
3645 memory. If you are the owner of a pointer, then you may allow another
3646 binding to temporarily borrow that pointer, and then they can manipulate the
3647 memory. The length of time that the borrower is borrowing the pointer
3648 from you is called a **lifetime**.
3649
3650 If two distinct bindings share a pointer, and the memory that pointer points to
3651 is immutable, then there are no problems. But if it's mutable, the result of
3652 changing it can vary unpredictably depending on who happens to access it first,
3653 which is called a **race condition**. To avoid this, if someone wants to mutate
3654 something that they've borrowed from you, you must not have lent out that
3655 pointer to anyone else.
3656
3657 Rust has a sophisticated system called the **borrow checker** to make sure that
3658 everyone plays by these rules. At compile time, it verifies that none of these
3659 rules are broken. If our program compiles successfully, Rust can guarantee it
3660 is free of data races and other memory errors, and there is no runtime overhead
3661 for any of this. The borrow checker works only at compile time. If the borrow
3662 checker did find a problem, it will report an error and your program will
3663 refuse to compile.
3664
3665 That's a lot to take in. It's also one of the _most_ important concepts in
3666 all of Rust. Let's see this syntax in action:
3667
3668 ```{rust}
3669 {
3670     let x = 5i; // x is the owner of this integer, which is memory on the stack.
3671
3672     // other code here...
3673
3674 } // privilege 1: when x goes out of scope, this memory is deallocated
3675
3676 /// this function borrows an integer. It's given back automatically when the
3677 /// function returns.
3678 fn foo(x: &int) -> &int { x }
3679
3680 {
3681     // x is the owner of the integer, which is memory on the stack.
3682     let x = 5i;
3683
3684     // privilege 2: you may lend that resource to as many borrowers as you like
3685     let y = &x;
3686     let z = &x;
3687
3688     foo(&x); // functions can borrow too!
3689
3690     let a = &x; // we can do this alllllll day!
3691 }
3692
3693 {
3694     // x is the owner of this integer, which is memory on the stack.
3695     let mut x = 5i;
3696
3697     // privilege 3: you may lend that resource to a single borrower, mutably
3698     let y = &mut x;
3699 }
3700 ```
3701
3702 If you are a borrower, you get a few privileges as well, but must also obey a
3703 restriction:
3704
3705 1. If the borrow is immutable, you may read the data the pointer points to.
3706 2. If the borrow is mutable, you may read and write the data the pointer points to.
3707 3. You may lend the pointer to someone else, **BUT**
3708 4. When you do so, they must return it before you can give your own borrow back.
3709
3710 This last requirement can seem odd, but it also makes sense. If you have to
3711 return something, and you've lent it to someone, they need to give it back to
3712 you for you to give it back! If we didn't, then the owner could deallocate
3713 the memory, and the person we've loaned it out to would have a pointer to
3714 invalid memory. This is called a 'dangling pointer'.
3715
3716 Let's re-examine the error that led us to talk about all of this, which was a
3717 violation of the restrictions placed on owners who lend something out mutably.
3718 The code:
3719
3720 ```{rust,ignore}
3721 let mut x = 5i;
3722 let y = &mut x;
3723 let z = &mut x;
3724 ```
3725
3726 The error:
3727
3728 ```text
3729 error: cannot borrow `x` as mutable more than once at a time
3730      let z = &mut x;
3731                   ^
3732 note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3733      let y = &mut x;
3734                   ^
3735 note: previous borrow ends here
3736  fn main() {
3737      let mut x = 5i;
3738      let y = &mut x;
3739      let z = &mut x;
3740  }
3741  ^
3742 ```
3743
3744 This error comes in three parts. Let's go over each in turn.
3745
3746 ```text
3747 error: cannot borrow `x` as mutable more than once at a time
3748      let z = &mut x;
3749                   ^
3750 ```
3751
3752 This error states the restriction: you cannot lend out something mutable more
3753 than once at the same time. The borrow checker knows the rules!
3754
3755 ```text
3756 note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3757      let y = &mut x;
3758                   ^
3759 ```
3760
3761 Some compiler errors come with notes to help you fix the error. This error comes
3762 with two notes, and this is the first. This note informs us of exactly where
3763 the first mutable borrow occurred. The error showed us the second. So now we
3764 see both parts of the problem. It also alludes to rule #3, by reminding us that
3765 we can't change `x` until the borrow is over.
3766
3767 ```text
3768 note: previous borrow ends here
3769  fn main() {
3770      let mut x = 5i;
3771      let y = &mut x;
3772      let z = &mut x;
3773  }
3774  ^
3775 ```
3776
3777 Here's the second note, which lets us know where the first borrow would be over.
3778 This is useful, because if we wait to try to borrow `x` after this borrow is
3779 over, then everything will work.
3780
3781 For more advanced patterns, please consult the [Ownership
3782 Guide](guide-ownership.html).  You'll also learn what this type signature with
3783 the `'a` syntax is:
3784
3785 ```{rust,ignore}
3786 pub fn as_maybe_owned(&self) -> MaybeOwned<'a> { ... }
3787 ```
3788
3789 ## Boxes
3790
3791 Most of the types we've seen so far have a fixed size or number of components.
3792 The compiler needs this fact to lay out values in memory. However, some data
3793 structures, such as a linked list, do not have a fixed size. You might think to
3794 implement a linked list with an enum that's either a `Node` or the end of the
3795 list (`Nil`), like this:
3796
3797 ```{rust,ignore}
3798 enum List {             // error: illegal recursive enum type
3799     Node(u32, List),
3800     Nil
3801 }
3802 ```
3803
3804 But the compiler complains that the type is recursive, that is, it could be
3805 arbitrarily large. To remedy this, Rust provides a fixed-size container called
3806 a **box** that can hold any type. You can box up any value with the `box`
3807 keyword. Our boxed List gets the type `Box<List>` (more on the notation when we
3808 get to generics):
3809
3810 ```{rust}
3811 enum List {
3812     Node(u32, Box<List>),
3813     Nil
3814 }
3815
3816 fn main() {
3817     let list = List::Node(0, box List::Node(1, box List::Nil));
3818 }
3819 ```
3820
3821 A box dynamically allocates memory to hold its contents. The great thing about
3822 Rust is that that memory is *automatically*, *efficiently*, and *predictably*
3823 deallocated when you're done with the box.
3824
3825 A box is a pointer type, and you access what's inside using the `*` operator,
3826 just like regular references. This (rather silly) example dynamically allocates
3827 an integer `5` and makes `x` a pointer to it:
3828
3829 ```{rust}
3830 {
3831     let x = box 5i;
3832     println!("{}", *x);     // Prints 5
3833 }
3834 ```
3835
3836 The great thing about boxes is that we don't have to manually free this
3837 allocation! Instead, when `x` reaches the end of its lifetime – in this case,
3838 when it goes out of scope at the end of the block – Rust `free`s `x`. This
3839 isn't because Rust has a garbage collector (it doesn't). Instead, by tracking
3840 the ownership and lifetime of a variable (with a little help from you, the
3841 programmer), the compiler knows precisely when it is no longer used.
3842
3843 The Rust code above will do the same thing as the following C code:
3844
3845 ```{c,ignore}
3846 {
3847     int *x = (int *)malloc(sizeof(int));
3848     if (!x) abort();
3849     *x = 5;
3850     printf("%d\n", *x);
3851     free(x);
3852 }
3853 ```
3854
3855 We get the benefits of manual memory management, while ensuring we don't
3856 introduce any bugs. We can't forget to `free` our memory.
3857
3858 Boxes are the sole owner of their contents, so you cannot take a mutable
3859 reference to them and then use the original box:
3860
3861 ```{rust,ignore}
3862 let mut x = box 5i;
3863 let y = &mut x;
3864
3865 *x; // you might expect 5, but this is actually an error
3866 ```
3867
3868 This gives us this error:
3869
3870 ```text
3871 error: cannot use `*x` because it was mutably borrowed
3872  *x;
3873  ^~
3874 note: borrow of `x` occurs here
3875  let y = &mut x;
3876               ^
3877 ```
3878
3879 As long as `y` is borrowing the contents, we cannot use `x`. After `y` is
3880 done borrowing the value, we can use it again. This works fine:
3881
3882 ```{rust}
3883 let mut x = box 5i;
3884
3885 {
3886     let y = &mut x;
3887 } // y goes out of scope at the end of the block
3888
3889 *x;
3890 ```
3891
3892 Boxes are simple and efficient pointers to dynamically allocated values with a
3893 single owner. They are useful for tree-like structures where the lifetime of a
3894 child depends solely on the lifetime of its (single) parent. If you need a
3895 value that must persist as long as any of several referrers, read on.
3896
3897 ## Rc and Arc
3898
3899 Sometimes you need a variable that is referenced from multiple places
3900 (immutably!), lasting as long as any of those places, and disappearing when it
3901 is no longer referenced. For instance, in a graph-like data structure, a node
3902 might be referenced from all of its neighbors. In this case, it is not possible
3903 for the compiler to determine ahead of time when the value can be freed – it
3904 needs a little run-time support.
3905
3906 Rust's **Rc** type provides shared ownership of a dynamically allocated value
3907 that is automatically freed at the end of its last owner's lifetime. (`Rc`
3908 stands for 'reference counted', referring to the way these library types are
3909 implemented.) This provides more flexibility than single-owner boxes, but has
3910 some runtime overhead.
3911
3912 To create an `Rc` value, use `Rc::new()`. To create a second owner, use the
3913 `.clone()` method:
3914
3915 ```{rust}
3916 use std::rc::Rc;
3917
3918 let x = Rc::new(5i);
3919 let y = x.clone();
3920
3921 println!("{} {}", *x, *y);      // Prints 5 5
3922 ```
3923
3924 The `Rc` will live as long as any of its owners are alive. After that, the
3925 memory will be `free`d.
3926
3927 **Arc** is an 'atomically reference counted' value, identical to `Rc` except
3928 that ownership can be safely shared among multiple threads. Why two types?
3929 `Arc` has more overhead, so if you're not in a multi-threaded scenario, you
3930 don't have to pay the price.
3931
3932 If you use `Rc` or `Arc`, you have to be careful about introducing cycles. If
3933 you have two `Rc`s that point to each other, they will happily keep each other
3934 alive forever, creating a memory leak. To learn more, check out [the section on
3935 `Rc` and `Arc` in the pointers guide](guide-pointers.html#rc-and-arc).
3936
3937 # Patterns
3938
3939 We've made use of patterns a few times in the guide: first with `let` bindings,
3940 then with `match` statements. Let's go on a whirlwind tour of all of the things
3941 patterns can do!
3942
3943 A quick refresher: you can match against literals directly, and `_` acts as an
3944 'any' case:
3945
3946 ```{rust}
3947 let x = 1i;
3948
3949 match x {
3950     1 => println!("one"),
3951     2 => println!("two"),
3952     3 => println!("three"),
3953     _ => println!("anything"),
3954 }
3955 ```
3956
3957 You can match multiple patterns with `|`:
3958
3959 ```{rust}
3960 let x = 1i;
3961
3962 match x {
3963     1 | 2 => println!("one or two"),
3964     3 => println!("three"),
3965     _ => println!("anything"),
3966 }
3967 ```
3968
3969 You can match a range of values with `...`:
3970
3971 ```{rust}
3972 let x = 1i;
3973
3974 match x {
3975     1 ... 5 => println!("one through five"),
3976     _ => println!("anything"),
3977 }
3978 ```
3979
3980 Ranges are mostly used with integers and single characters.
3981
3982 If you're matching multiple things, via a `|` or a `...`, you can bind
3983 the value to a name with `@`:
3984
3985 ```{rust}
3986 let x = 1i;
3987
3988 match x {
3989     e @ 1 ... 5 => println!("got a range element {}", e),
3990     _ => println!("anything"),
3991 }
3992 ```
3993
3994 If you're matching on an enum which has variants, you can use `..` to
3995 ignore the value and type in the variant:
3996
3997 ```{rust}
3998 enum OptionalInt {
3999     Value(int),
4000     Missing,
4001 }
4002
4003 let x = OptionalInt::Value(5i);
4004
4005 match x {
4006     OptionalInt::Value(..) => println!("Got an int!"),
4007     OptionalInt::Missing   => println!("No such luck."),
4008 }
4009 ```
4010
4011 You can introduce **match guards** with `if`:
4012
4013 ```{rust}
4014 enum OptionalInt {
4015     Value(int),
4016     Missing,
4017 }
4018
4019 let x = OptionalInt::Value(5i);
4020
4021 match x {
4022     OptionalInt::Value(i) if i > 5 => println!("Got an int bigger than five!"),
4023     OptionalInt::Value(..) => println!("Got an int!"),
4024     OptionalInt::Missing   => println!("No such luck."),
4025 }
4026 ```
4027
4028 If you're matching on a pointer, you can use the same syntax as you declared it
4029 with. First, `&`:
4030
4031 ```{rust}
4032 let x = &5i;
4033
4034 match x {
4035     &val => println!("Got a value: {}", val),
4036 }
4037 ```
4038
4039 Here, the `val` inside the `match` has type `int`. In other words, the left-hand
4040 side of the pattern destructures the value. If we have `&5i`, then in `&val`, `val`
4041 would be `5i`.
4042
4043 If you want to get a reference, use the `ref` keyword:
4044
4045 ```{rust}
4046 let x = 5i;
4047
4048 match x {
4049     ref r => println!("Got a reference to {}", r),
4050 }
4051 ```
4052
4053 Here, the `r` inside the `match` has the type `&int`. In other words, the `ref`
4054 keyword _creates_ a reference, for use in the pattern. If you need a mutable
4055 reference, `ref mut` will work in the same way:
4056
4057 ```{rust}
4058 let mut x = 5i;
4059
4060 match x {
4061     ref mut mr => println!("Got a mutable reference to {}", mr),
4062 }
4063 ```
4064
4065 If you have a struct, you can destructure it inside of a pattern:
4066
4067 ```{rust}
4068 # #![allow(non_shorthand_field_patterns)]
4069 struct Point {
4070     x: int,
4071     y: int,
4072 }
4073
4074 let origin = Point { x: 0i, y: 0i };
4075
4076 match origin {
4077     Point { x: x, y: y } => println!("({},{})", x, y),
4078 }
4079 ```
4080
4081 If we only care about some of the values, we don't have to give them all names:
4082
4083 ```{rust}
4084 # #![allow(non_shorthand_field_patterns)]
4085 struct Point {
4086     x: int,
4087     y: int,
4088 }
4089
4090 let origin = Point { x: 0i, y: 0i };
4091
4092 match origin {
4093     Point { x: x, .. } => println!("x is {}", x),
4094 }
4095 ```
4096
4097 You can do this kind of match on any member, not just the first:
4098
4099 ```{rust}
4100 # #![allow(non_shorthand_field_patterns)]
4101 struct Point {
4102     x: int,
4103     y: int,
4104 }
4105
4106 let origin = Point { x: 0i, y: 0i };
4107
4108 match origin {
4109     Point { y: y, .. } => println!("y is {}", y),
4110 }
4111 ```
4112
4113 If you want to match against a slice or array, you can use `[]`:
4114
4115 ```{rust}
4116 fn main() {
4117     let v = vec!["match_this", "1"];
4118
4119     match v.as_slice() {
4120         ["match_this", second] => println!("The second element is {}", second),
4121         _ => {},
4122     }
4123 }
4124 ```
4125
4126 Whew! That's a lot of different ways to match things, and they can all be
4127 mixed and matched, depending on what you're doing:
4128
4129 ```{rust,ignore}
4130 match x {
4131     Foo { x: Some(ref name), y: None } => ...
4132 }
4133 ```
4134
4135 Patterns are very powerful.  Make good use of them.
4136
4137 # Method Syntax
4138
4139 Functions are great, but if you want to call a bunch of them on some data, it
4140 can be awkward. Consider this code:
4141
4142 ```{rust,ignore}
4143 baz(bar(foo(x)));
4144 ```
4145
4146 We would read this left-to right, and so we see 'baz bar foo.' But this isn't the
4147 order that the functions would get called in, that's inside-out: 'foo bar baz.'
4148 Wouldn't it be nice if we could do this instead?
4149
4150 ```{rust,ignore}
4151 x.foo().bar().baz();
4152 ```
4153
4154 Luckily, as you may have guessed with the leading question, you can! Rust provides
4155 the ability to use this **method call syntax** via the `impl` keyword.
4156
4157 Here's how it works:
4158
4159 ```{rust}
4160 struct Circle {
4161     x: f64,
4162     y: f64,
4163     radius: f64,
4164 }
4165
4166 impl Circle {
4167     fn area(&self) -> f64 {
4168         std::f64::consts::PI * (self.radius * self.radius)
4169     }
4170 }
4171
4172 fn main() {
4173     let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };
4174     println!("{}", c.area());
4175 }
4176 ```
4177
4178 This will print `12.566371`.
4179
4180 We've made a struct that represents a circle. We then write an `impl` block,
4181 and inside it, define a method, `area`. Methods take a  special first
4182 parameter, `&self`. There are three variants: `self`, `&self`, and `&mut self`.
4183 You can think of this first parameter as being the `x` in `x.foo()`. The three
4184 variants correspond to the three kinds of things `x` could be: `self` if it's
4185 just a value on the stack, `&self` if it's a reference, and `&mut self` if it's
4186 a mutable reference. We should default to using `&self`, as it's the most
4187 common.
4188
4189 Finally, as you may remember, the value of the area of a circle is `π*r²`.
4190 Because we took the `&self` parameter to `area`, we can use it just like any
4191 other parameter. Because we know it's a `Circle`, we can access the `radius`
4192 just like we would with any other struct. An import of π and some
4193 multiplications later, and we have our area.
4194
4195 You can also define methods that do not take a `self` parameter. Here's a
4196 pattern that's very common in Rust code:
4197
4198 ```{rust}
4199 # #![allow(non_shorthand_field_patterns)]
4200 struct Circle {
4201     x: f64,
4202     y: f64,
4203     radius: f64,
4204 }
4205
4206 impl Circle {
4207     fn new(x: f64, y: f64, radius: f64) -> Circle {
4208         Circle {
4209             x: x,
4210             y: y,
4211             radius: radius,
4212         }
4213     }
4214 }
4215
4216 fn main() {
4217     let c = Circle::new(0.0, 0.0, 2.0);
4218 }
4219 ```
4220
4221 This **static method** builds a new `Circle` for us. Note that static methods
4222 are called with the `Struct::method()` syntax, rather than the `ref.method()`
4223 syntax.
4224
4225 # Closures
4226
4227 So far, we've made lots of functions in Rust, but we've given them all names.
4228 Rust also allows us to create anonymous functions. Rust's anonymous
4229 functions are called **closure**s. By themselves, closures aren't all that
4230 interesting, but when you combine them with functions that take closures as
4231 arguments, really powerful things are possible.
4232
4233 Let's make a closure:
4234
4235 ```{rust}
4236 let add_one = |x| { 1i + x };
4237
4238 println!("The sum of 5 plus 1 is {}.", add_one(5i));
4239 ```
4240
4241 We create a closure using the `|...| { ... }` syntax, and then we create a
4242 binding so we can use it later. Note that we call the function using the
4243 binding name and two parentheses, just like we would for a named function.
4244
4245 Let's compare syntax. The two are pretty close:
4246
4247 ```{rust}
4248 let add_one = |x: int| -> int { 1i + x };
4249 fn  add_one   (x: int) -> int { 1i + x }
4250 ```
4251
4252 As you may have noticed, closures infer their argument and return types, so you
4253 don't need to declare one. This is different from named functions, which
4254 default to returning unit (`()`).
4255
4256 There's one big difference between a closure and named functions, and it's in
4257 the name: a closure "closes over its environment." What does that mean? It means
4258 this:
4259
4260 ```{rust}
4261 fn main() {
4262     let x = 5i;
4263
4264     let printer = || { println!("x is: {}", x); };
4265
4266     printer(); // prints "x is: 5"
4267 }
4268 ```
4269
4270 The `||` syntax means this is an anonymous closure that takes no arguments.
4271 Without it, we'd just have a block of code in `{}`s.
4272
4273 In other words, a closure has access to variables in the scope where it's
4274 defined. The closure borrows any variables it uses, so this will error:
4275
4276 ```{rust,ignore}
4277 fn main() {
4278     let mut x = 5i;
4279
4280     let printer = || { println!("x is: {}", x); };
4281
4282     x = 6i; // error: cannot assign to `x` because it is borrowed
4283 }
4284 ```
4285
4286 ## Moving closures
4287
4288 Rust has a second type of closure, called a **moving closure**. Moving
4289 closures are indicated using the `move` keyword (e.g., `move || x *
4290 x`). The difference between a moving closure and an ordinary closure
4291 is that a moving closure always takes ownership of all variables that
4292 it uses. Ordinary closures, in contrast, just create a reference into
4293 the enclosing stack frame. Moving closures are most useful with Rust's
4294 concurrency features, and so we'll just leave it at this for
4295 now. We'll talk about them more in the "Threads" section of the guide.
4296
4297 ## Accepting closures as arguments
4298
4299 Closures are most useful as an argument to another function. Here's an example:
4300
4301 ```{rust}
4302 fn twice(x: int, f: |int| -> int) -> int {
4303     f(x) + f(x)
4304 }
4305
4306 fn main() {
4307     let square = |x: int| { x * x };
4308
4309     twice(5i, square); // evaluates to 50
4310 }
4311 ```
4312
4313 Let's break the example down, starting with `main`:
4314
4315 ```{rust}
4316 let square = |x: int| { x * x };
4317 ```
4318
4319 We've seen this before. We make a closure that takes an integer, and returns
4320 its square.
4321
4322 ```{rust}
4323 # fn twice(x: int, f: |int| -> int) -> int { f(x) + f(x) }
4324 # let square = |x: int| { x * x };
4325 twice(5i, square); // evaluates to 50
4326 ```
4327
4328 This line is more interesting. Here, we call our function, `twice`, and we pass
4329 it two arguments: an integer, `5`, and our closure, `square`. This is just like
4330 passing any other two variable bindings to a function, but if you've never
4331 worked with closures before, it can seem a little complex. Just think: "I'm
4332 passing two variables: one is an int, and one is a function."
4333
4334 Next, let's look at how `twice` is defined:
4335
4336 ```{rust,ignore}
4337 fn twice(x: int, f: |int| -> int) -> int {
4338 ```
4339
4340 `twice` takes two arguments, `x` and `f`. That's why we called it with two
4341 arguments. `x` is an `int`, we've done that a ton of times. `f` is a function,
4342 though, and that function takes an `int` and returns an `int`. Notice
4343 how the `|int| -> int` syntax looks a lot like our definition of `square`
4344 above, if we added the return type in:
4345
4346 ```{rust}
4347 let square = |x: int| -> int { x * x };
4348 //           |int|    -> int
4349 ```
4350
4351 This function takes an `int` and returns an `int`.
4352
4353 This is the most complicated function signature we've seen yet! Give it a read
4354 a few times until you can see how it works. It takes a teeny bit of practice, and
4355 then it's easy.
4356
4357 Finally, `twice` returns an `int` as well.
4358
4359 Okay, let's look at the body of `twice`:
4360
4361 ```{rust}
4362 fn twice(x: int, f: |int| -> int) -> int {
4363   f(x) + f(x)
4364 }
4365 ```
4366
4367 Since our closure is named `f`, we can call it just like we called our closures
4368 before, and we pass in our `x` argument to each one, hence the name `twice`.
4369
4370 If you do the math, `(5 * 5) + (5 * 5) == 50`, so that's the output we get.
4371
4372 Play around with this concept until you're comfortable with it. Rust's standard
4373 library uses lots of closures where appropriate, so you'll be using
4374 this technique a lot.
4375
4376 If we didn't want to give `square` a name, we could just define it inline.
4377 This example is the same as the previous one:
4378
4379 ```{rust}
4380 fn twice(x: int, f: |int| -> int) -> int {
4381     f(x) + f(x)
4382 }
4383
4384 fn main() {
4385     twice(5i, |x: int| { x * x }); // evaluates to 50
4386 }
4387 ```
4388
4389 A named function's name can be used wherever you'd use a closure. Another
4390 way of writing the previous example:
4391
4392 ```{rust}
4393 fn twice(x: int, f: |int| -> int) -> int {
4394     f(x) + f(x)
4395 }
4396
4397 fn square(x: int) -> int { x * x }
4398
4399 fn main() {
4400     twice(5i, square); // evaluates to 50
4401 }
4402 ```
4403
4404 Doing this is not particularly common, but it's useful every once in a while.
4405
4406 That's all you need to get the hang of closures! Closures are a little bit
4407 strange at first, but once you're used to them, you'll miss them
4408 in other languages. Passing functions to other functions is
4409 incredibly powerful, as you will see in the following chapter about iterators.
4410
4411 # Iterators
4412
4413 Let's talk about loops.
4414
4415 Remember Rust's `for` loop? Here's an example:
4416
4417 ```{rust}
4418 for x in range(0i, 10i) {
4419     println!("{}", x);
4420 }
4421 ```
4422
4423 Now that you know more Rust, we can talk in detail about how this works. The
4424 `range` function returns an **iterator**. An iterator is something that we can
4425 call the `.next()` method on repeatedly, and it gives us a sequence of things.
4426
4427 Like this:
4428
4429 ```{rust}
4430 let mut range = range(0i, 10i);
4431
4432 loop {
4433     match range.next() {
4434         Some(x) => {
4435             println!("{}", x);
4436         },
4437         None => { break }
4438     }
4439 }
4440 ```
4441
4442 We make a mutable binding to the return value of `range`, which is our iterator.
4443 We then `loop`, with an inner `match`. This `match` is used on the result of
4444 `range.next()`, which gives us a reference to the next value of the iterator.
4445 `next` returns an `Option<int>`, in this case, which will be `Some(int)` when
4446 we have a value and `None` once we run out. If we get `Some(int)`, we print it
4447 out, and if we get `None`, we `break` out of the loop.
4448
4449 This code sample is basically the same as our `for` loop version. The `for`
4450 loop is just a handy way to write this `loop`/`match`/`break` construct.
4451
4452 `for` loops aren't the only thing that uses iterators, however. Writing your
4453 own iterator involves implementing the `Iterator` trait. While doing that is
4454 outside of the scope of this guide, Rust provides a number of useful iterators
4455 to accomplish various tasks. Before we talk about those, we should talk about a
4456 Rust anti-pattern. And that's `range`.
4457
4458 Yes, we just talked about how `range` is cool. But `range` is also very
4459 primitive. For example, if you needed to iterate over the contents of
4460 a vector, you may be tempted to write this:
4461
4462 ```{rust}
4463 let nums = vec![1i, 2i, 3i];
4464
4465 for i in range(0u, nums.len()) {
4466     println!("{}", nums[i]);
4467 }
4468 ```
4469
4470 This is strictly worse than using an actual iterator. The `.iter()` method on
4471 vectors returns an iterator that iterates through a reference to each element
4472 of the vector in turn. So write this:
4473
4474 ```{rust}
4475 let nums = vec![1i, 2i, 3i];
4476
4477 for num in nums.iter() {
4478     println!("{}", num);
4479 }
4480 ```
4481
4482 There are two reasons for this. First, this more directly expresses what we
4483 mean. We iterate through the entire vector, rather than iterating through
4484 indexes, and then indexing the vector. Second, this version is more efficient:
4485 the first version will have extra bounds checking because it used indexing,
4486 `nums[i]`. But since we yield a reference to each element of the vector in turn
4487 with the iterator, there's no bounds checking in the second example. This is
4488 very common with iterators: we can ignore unnecessary bounds checks, but still
4489 know that we're safe.
4490
4491 There's another detail here that's not 100% clear because of how `println!`
4492 works. `num` is actually of type `&int`. That is, it's a reference to an `int`,
4493 not an `int` itself. `println!` handles the dereferencing for us, so we don't
4494 see it. This code works fine too:
4495
4496 ```{rust}
4497 let nums = vec![1i, 2i, 3i];
4498
4499 for num in nums.iter() {
4500     println!("{}", *num);
4501 }
4502 ```
4503
4504 Now we're explicitly dereferencing `num`. Why does `iter()` give us references?
4505 Well, if it gave us the data itself, we would have to be its owner, which would
4506 involve making a copy of the data and giving us the copy. With references,
4507 we're just borrowing a reference to the data, and so it's just passing
4508 a reference, without needing to do the copy.
4509
4510 So, now that we've established that `range` is often not what you want, let's
4511 talk about what you do want instead.
4512
4513 There are three broad classes of things that are relevant here: iterators,
4514 **iterator adapters**, and **consumers**. Here's some definitions:
4515
4516 * 'iterators' give you a sequence of values.
4517 * 'iterator adapters' operate on an iterator, producing a new iterator with a
4518   different output sequence.
4519 * 'consumers' operate on an iterator, producing some final set of values.
4520
4521 Let's talk about consumers first, since you've already seen an iterator,
4522 `range`.
4523
4524 ## Consumers
4525
4526 A 'consumer' operates on an iterator, returning some kind of value or values.
4527 The most common consumer is `collect()`. This code doesn't quite compile,
4528 but it shows the intention:
4529
4530 ```{rust,ignore}
4531 let one_to_one_hundred = range(1i, 101i).collect();
4532 ```
4533
4534 As you can see, we call `collect()` on our iterator. `collect()` takes
4535 as many values as the iterator will give it, and returns a collection
4536 of the results. So why won't this compile? Rust can't determine what
4537 type of things you want to collect, and so you need to let it know.
4538 Here's the version that does compile:
4539
4540 ```{rust}
4541 let one_to_one_hundred = range(1i, 101i).collect::<Vec<int>>();
4542 ```
4543
4544 If you remember, the `::<>` syntax allows us to give a type hint,
4545 and so we tell it that we want a vector of integers.
4546
4547 `collect()` is the most common consumer, but there are others too. `find()`
4548 is one:
4549
4550 ```{rust}
4551 let greater_than_forty_two = range(0i, 100i)
4552                              .find(|x| *x > 42);
4553
4554 match greater_than_forty_two {
4555     Some(_) => println!("We got some numbers!"),
4556     None    => println!("No numbers found :("),
4557 }
4558 ```
4559
4560 `find` takes a closure, and works on a reference to each element of an
4561 iterator. This closure returns `true` if the element is the element we're
4562 looking for, and `false` otherwise. Because we might not find a matching
4563 element, `find` returns an `Option` rather than the element itself.
4564
4565 Another important consumer is `fold`. Here's what it looks like:
4566
4567 ```{rust}
4568 let sum = range(1i, 4i)
4569               .fold(0i, |sum, x| sum + x);
4570 ```
4571
4572 `fold()` is a consumer that looks like this:
4573 `fold(base, |accumulator, element| ...)`. It takes two arguments: the first
4574 is an element called the "base". The second is a closure that itself takes two
4575 arguments: the first is called the "accumulator," and the second is an
4576 "element." Upon each iteration, the closure is called, and the result is the
4577 value of the accumulator on the next iteration. On the first iteration, the
4578 base is the value of the accumulator.
4579
4580 Okay, that's a bit confusing. Let's examine the values of all of these things
4581 in this iterator:
4582
4583 | base | accumulator | element | closure result |
4584 |------|-------------|---------|----------------|
4585 | 0i   | 0i          | 1i      | 1i             |
4586 | 0i   | 1i          | 2i      | 3i             |
4587 | 0i   | 3i          | 3i      | 6i             |
4588
4589 We called `fold()` with these arguments:
4590
4591 ```{rust}
4592 # range(1i, 4i)
4593 .fold(0i, |sum, x| sum + x);
4594 ```
4595
4596 So, `0i` is our base, `sum` is our accumulator, and `x` is our element.  On the
4597 first iteration, we set `sum` to `0i`, and `x` is the first element of `nums`,
4598 `1i`. We then add `sum` and `x`, which gives us `0i + 1i = 1i`. On the second
4599 iteration, that value becomes our accumulator, `sum`, and the element is
4600 the second element of the array, `2i`. `1i + 2i = 3i`, and so that becomes
4601 the value of the accumulator for the last iteration. On that iteration,
4602 `x` is the last element, `3i`, and `3i + 3i = 6i`, which is our final
4603 result for our sum. `1 + 2 + 3 = 6`, and that's the result we got.
4604
4605 Whew. `fold` can be a bit strange the first few times you see it, but once it
4606 clicks, you can use it all over the place. Any time you have a list of things,
4607 and you want a single result, `fold` is appropriate.
4608
4609 Consumers are important due to one additional property of iterators we haven't
4610 talked about yet: laziness. Let's talk some more about iterators, and you'll
4611 see why consumers matter.
4612
4613 ## Iterators
4614
4615 As we've said before, an iterator is something that we can call the
4616 `.next()` method on repeatedly, and it gives us a sequence of things.
4617 Because you need to call the method, this means that iterators
4618 are **lazy** and don't need to generate all of the values upfront.
4619 This code, for example, does not actually generate the numbers
4620 `1-100`, and just creates a value that represents the sequence:
4621
4622 ```{rust}
4623 let nums = range(1i, 100i);
4624 ```
4625
4626 Since we didn't do anything with the range, it didn't generate the sequence.
4627 Let's add the consumer:
4628
4629 ```{rust}
4630 let nums = range(1i, 100i).collect::<Vec<int>>();
4631 ```
4632
4633 Now, `collect()` will require that `range()` give it some numbers, and so
4634 it will do the work of generating the sequence.
4635
4636 `range` is one of two basic iterators that you'll see. The other is `iter()`,
4637 which you've used before. `iter()` can turn a vector into a simple iterator
4638 that gives you each element in turn:
4639
4640 ```{rust}
4641 let nums = [1i, 2i, 3i];
4642
4643 for num in nums.iter() {
4644    println!("{}", num);
4645 }
4646 ```
4647
4648 These two basic iterators should serve you well. There are some more
4649 advanced iterators, including ones that are infinite. Like `count`:
4650
4651 ```{rust}
4652 std::iter::count(1i, 5i);
4653 ```
4654
4655 This iterator counts up from one, adding five each time. It will give
4656 you a new integer every time, forever (well, technically, until it reaches the
4657 maximum number representable by an `int`). But since iterators are lazy,
4658 that's okay! You probably don't want to use `collect()` on it, though...
4659
4660 That's enough about iterators. Iterator adapters are the last concept
4661 we need to talk about with regards to iterators. Let's get to it!
4662
4663 ## Iterator adapters
4664
4665 "Iterator adapters" take an iterator and modify it somehow, producing
4666 a new iterator. The simplest one is called `map`:
4667
4668 ```{rust,ignore}
4669 range(1i, 100i).map(|x| x + 1i);
4670 ```
4671
4672 `map` is called upon another iterator, and produces a new iterator where each
4673 element reference has the closure it's been given as an argument called on it.
4674 So this would give us the numbers from `2-100`. Well, almost! If you
4675 compile the example, you'll get a warning:
4676
4677 ```text
4678 warning: unused result which must be used: iterator adaptors are lazy and
4679          do nothing unless consumed, #[warn(unused_must_use)] on by default
4680  range(1i, 100i).map(|x| x + 1i);
4681  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4682 ```
4683
4684 Laziness strikes again! That closure will never execute. This example
4685 doesn't print any numbers:
4686
4687 ```{rust,ignore}
4688 range(1i, 100i).map(|x| println!("{}", x));
4689 ```
4690
4691 If you are trying to execute a closure on an iterator for its side effects,
4692 just use `for` instead.
4693
4694 There are tons of interesting iterator adapters. `take(n)` will return an
4695 iterator over the next `n` elements of the original iterator, note that this
4696 has no side effect on the original iterator. Let's try it out with our infinite
4697 iterator from before, `count()`:
4698
4699 ```{rust}
4700 for i in std::iter::count(1i, 5i).take(5) {
4701     println!("{}", i);
4702 }
4703 ```
4704
4705 This will print
4706
4707 ```text
4708 1
4709 6
4710 11
4711 16
4712 21
4713 ```
4714
4715 `filter()` is an adapter that takes a closure as an argument. This closure
4716 returns `true` or `false`. The new iterator `filter()` produces
4717 only the elements that that closure returns `true` for:
4718
4719 ```{rust}
4720 for i in range(1i, 100i).filter(|&x| x % 2 == 0) {
4721     println!("{}", i);
4722 }
4723 ```
4724
4725 This will print all of the even numbers between one and a hundred.
4726 (Note that because `filter` doesn't consume the elements that are
4727 being iterated over, it is passed a reference to each element, and
4728 thus the filter predicate uses the `&x` pattern to extract the integer
4729 itself.)
4730
4731 You can chain all three things together: start with an iterator, adapt it
4732 a few times, and then consume the result. Check it out:
4733
4734 ```{rust}
4735 range(1i, 1000i)
4736     .filter(|&x| x % 2 == 0)
4737     .filter(|&x| x % 3 == 0)
4738     .take(5)
4739     .collect::<Vec<int>>();
4740 ```
4741
4742 This will give you a vector containing `6`, `12`, `18`, `24`, and `30`.
4743
4744 This is just a small taste of what iterators, iterator adapters, and consumers
4745 can help you with. There are a number of really useful iterators, and you can
4746 write your own as well. Iterators provide a safe, efficient way to manipulate
4747 all kinds of lists. They're a little unusual at first, but if you play with
4748 them, you'll get hooked. For a full list of the different iterators and
4749 consumers, check out the [iterator module documentation](std/iter/index.html).
4750
4751 # Generics
4752
4753 Sometimes, when writing a function or data type, we may want it to work for
4754 multiple types of arguments. For example, remember our `OptionalInt` type?
4755
4756 ```{rust}
4757 enum OptionalInt {
4758     Value(int),
4759     Missing,
4760 }
4761 ```
4762
4763 If we wanted to also have an `OptionalFloat64`, we would need a new enum:
4764
4765 ```{rust}
4766 enum OptionalFloat64 {
4767     Valuef64(f64),
4768     Missingf64,
4769 }
4770 ```
4771
4772 Such repetition is unfortunate. Luckily, Rust has a feature that gives us a
4773 better way: **generics**. Generics are called **parametric polymorphism** in
4774 type theory, which means that they are types or functions that have multiple
4775 forms over a given parameter ("parametric").
4776
4777 Let's see how generics help us escape `OptionalInt`. `Option` is already
4778 provided in Rust's standard library and looks like this:
4779
4780 ```rust
4781 enum Option<T> {
4782     Some(T),
4783     None,
4784 }
4785 ```
4786
4787 The `<T>` part, which you've seen a few times before, indicates that this is a
4788 generic data type. `T` is called a **type parameter**. When we create instances
4789 of `Option`, we need to provide a concrete type in place of the type
4790 parameter. For example, if we wanted something like our `OptionalInt`, we would
4791 need to instantiate an `Option<int>`. Inside the declaration of our enum,
4792 wherever we see a `T`, we replace it with the type specified (or inferred by the
4793 the compiler).
4794
4795 ```{rust}
4796 let x: Option<int> = Some(5i);
4797 ```
4798
4799 In this particular `Option`, `T` has the value of `int`. On the right-hand side
4800 of the binding, we do make a `Some(T)`, where `T` is `5i`.  Since that's an
4801 `int`, the two sides match, and Rust is happy. If they didn't match, we'd get an
4802 error:
4803
4804 ```{rust,ignore}
4805 let x: Option<f64> = Some(5i);
4806 // error: mismatched types: expected `core::option::Option<f64>`,
4807 // found `core::option::Option<int>` (expected f64, found int)
4808 ```
4809
4810 That doesn't mean we can't make `Option<T>`s that hold an `f64`! They just have to
4811 match up:
4812
4813 ```{rust}
4814 let x: Option<int> = Some(5i);
4815 let y: Option<f64> = Some(5.0f64);
4816 ```
4817
4818 Generics don't have to only be generic over one type. Consider Rust's built-in
4819 `Result<T, E>` type:
4820
4821 ```{rust}
4822 enum Result<T, E> {
4823     Ok(T),
4824     Err(E),
4825 }
4826 ```
4827
4828 This type is generic over _two_ types: `T` and `E`. By the way, the capital letters
4829 can be any letter you'd like. We could define `Result<T, E>` as:
4830
4831 ```{rust}
4832 enum Result<H, N> {
4833     Ok(H),
4834     Err(N),
4835 }
4836 ```
4837
4838 Convention says that the first generic parameter should be `T`, for "type," and
4839 that we use `E` for "error."
4840
4841 The `Result<T, E>` type is intended to be used to return the result of a
4842 computation and to have the ability to return an error if it didn't work
4843 out. Here's an example:
4844
4845 ```{rust}
4846 let x: Result<f64, String> = Ok(2.3f64);
4847 let y: Result<f64, String> = Err("There was an error.".to_string());
4848 ```
4849
4850 This particular `Result` will return an `f64` upon success and a `String` if
4851 there's a failure. Let's write a function that uses `Result<T, E>`:
4852
4853 ```{rust}
4854 fn inverse(x: f64) -> Result<f64, String> {
4855     if x == 0.0f64 { return Err("x cannot be zero!".to_string()); }
4856
4857     Ok(1.0f64 / x)
4858 }
4859 ```
4860
4861 We want to indicate that `inverse(0.0f64)` is undefined or is an erroneous usage
4862 of the function, so we check to make sure that we weren't passed zero. If we
4863 were, we return an `Err` with a message. If it's okay, we return an `Ok` with
4864 the answer.
4865
4866 Why does this matter? Well, remember how `match` does exhaustive matches?
4867 Here's how this function gets used:
4868
4869 ```{rust}
4870 # fn inverse(x: f64) -> Result<f64, String> {
4871 # if x == 0.0f64 { return Err("x cannot be zero!".to_string()); }
4872 # Ok(1.0f64 / x)
4873 # }
4874 let x = inverse(25.0f64);
4875
4876 match x {
4877     Ok(x) => println!("The inverse of 25 is {}", x),
4878     Err(msg) => println!("Error: {}", msg),
4879 }
4880 ```
4881
4882 The `match` enforces that we handle the `Err` case. In addition, because the
4883 answer is wrapped up in an `Ok`, we can't just use the result without doing
4884 the match:
4885
4886 ```{rust,ignore}
4887 let x = inverse(25.0f64);
4888 println!("{}", x + 2.0f64); // error: binary operation `+` cannot be applied
4889            // to type `core::result::Result<f64,collections::string::String>`
4890 ```
4891
4892 This function is great, but there's one other problem: it only works for 64 bit
4893 floating point values. If we wanted to handle 32 bit floating point values we'd
4894 have to write this:
4895
4896 ```{rust}
4897 fn inverse32(x: f32) -> Result<f32, String> {
4898     if x == 0.0f32 { return Err("x cannot be zero!".to_string()); }
4899
4900     Ok(1.0f32 / x)
4901 }
4902 ```
4903
4904 What we need is a **generic function**. We can do that with Rust! However, it
4905 won't _quite_ work yet. We need to talk about syntax. A first attempt at a
4906 generic version of `inverse` might look something like this:
4907
4908 ```{rust,ignore}
4909 fn inverse<T>(x: T) -> Result<T, String> {
4910     if x == 0.0 { return Err("x cannot be zero!".to_string()); }
4911
4912     Ok(1.0 / x)
4913 }
4914 ```
4915
4916 Just like how we had `Option<T>`, we use a similar syntax for `inverse<T>`.  We
4917 can then use `T` inside the rest of the signature: `x` has type `T`, and half of
4918 the `Result` has type `T`. However, if we try to compile that example, we'll get
4919 some errors:
4920
4921 ```text
4922 error: binary operation `==` cannot be applied to type `T`
4923      if x == 0.0 { return Err("x cannot be zero!".to_string()); }
4924                 ^~~~~~~~
4925 error: mismatched types: expected `_`, found `T` (expected floating-point variable, found type parameter)
4926      Ok(1.0 / x)
4927               ^
4928 error: mismatched types: expected `core::result::Result<T, collections::string::String>`, found `core::result::Result<_, _>` (expected type parameter, found floating-point variable)
4929      Ok(1.0 / x)
4930      ^~~~~~~~~~~
4931 ```
4932
4933 The problem is that `T` is unconstrained: it can be _any_ type. It could be a
4934 `String`, and the expression `1.0 / x` has no meaning if `x` is a `String`. It
4935 may be a type that doesn't implement `==`, and the first line would be
4936 wrong. What do we do?
4937
4938 To fix this example, we need to learn about another Rust feature: **traits**.
4939
4940 # Traits
4941
4942 Our discussion of **traits** begins with the `impl` keyword. We used it before
4943 to specify methods.
4944
4945 ```{rust}
4946 struct Circle {
4947     x: f64,
4948     y: f64,
4949     radius: f64,
4950 }
4951
4952 impl Circle {
4953     fn area(&self) -> f64 {
4954         std::f64::consts::PI * (self.radius * self.radius)
4955     }
4956 }
4957 ```
4958
4959 We define a trait in terms of its methods. We then `impl` a trait `for` a type
4960 (or many types).
4961
4962 ```{rust}
4963 struct Circle {
4964     x: f64,
4965     y: f64,
4966     radius: f64,
4967 }
4968
4969 trait HasArea {
4970     fn area(&self) -> f64;
4971 }
4972
4973 impl HasArea for Circle {
4974     fn area(&self) -> f64 {
4975         std::f64::consts::PI * (self.radius * self.radius)
4976     }
4977 }
4978 ```
4979
4980 The `trait` block defines only type signatures. When we `impl` a trait, we use
4981 `impl Trait for Item`, rather than just `impl Item`.
4982
4983 The first of the three errors we got with our generic `inverse` function was
4984 this:
4985
4986 ```text
4987 error: binary operation `==` cannot be applied to type `T`
4988 ```
4989
4990 We can use traits to constrain generic type parameters. Consider this function,
4991 which does not compile, and gives us a similar error:
4992
4993 ```{rust,ignore}
4994 fn print_area<T>(shape: T) {
4995     println!("This shape has an area of {}", shape.area());
4996 }
4997 ```
4998
4999 Rust complains:
5000
5001 ```text
5002 error: type `T` does not implement any method in scope named `area`
5003 ```
5004
5005 Because `T` can be any type, we can't be sure that it implements the `area`
5006 method. But we can add a **trait constraint** to our generic `T`, ensuring that
5007 we can only compile the function if it's called with types which `impl` the
5008 `HasArea` trait:
5009
5010 ```{rust}
5011 # trait HasArea {
5012 #     fn area(&self) -> f64;
5013 # }
5014 fn print_area<T: HasArea>(shape: T) {
5015     println!("This shape has an area of {}", shape.area());
5016 }
5017 ```
5018
5019 The syntax `<T: HasArea>` means "any type that implements the HasArea trait."
5020 Because traits define method signatures, we can be sure that any type which
5021 implements `HasArea` will have an `area` method.
5022
5023 Here's an extended example of how this works:
5024
5025 ```{rust}
5026 trait HasArea {
5027     fn area(&self) -> f64;
5028 }
5029
5030 struct Circle {
5031     x: f64,
5032     y: f64,
5033     radius: f64,
5034 }
5035
5036 impl HasArea for Circle {
5037     fn area(&self) -> f64 {
5038         std::f64::consts::PI * (self.radius * self.radius)
5039     }
5040 }
5041
5042 struct Square {
5043     x: f64,
5044     y: f64,
5045     side: f64,
5046 }
5047
5048 impl HasArea for Square {
5049     fn area(&self) -> f64 {
5050         self.side * self.side
5051     }
5052 }
5053
5054 fn print_area<T: HasArea>(shape: T) {
5055     println!("This shape has an area of {}", shape.area());
5056 }
5057
5058 fn main() {
5059     let c = Circle {
5060         x: 0.0f64,
5061         y: 0.0f64,
5062         radius: 1.0f64,
5063     };
5064
5065     let s = Square {
5066         x: 0.0f64,
5067         y: 0.0f64,
5068         side: 1.0f64,
5069     };
5070
5071     print_area(c);
5072     print_area(s);
5073 }
5074 ```
5075
5076 This program outputs:
5077
5078 ```text
5079 This shape has an area of 3.141593
5080 This shape has an area of 1
5081 ```
5082
5083 As you can see, `print_area` is now generic, but also ensures that we
5084 have passed in the correct types. If we pass in an incorrect type:
5085
5086 ```{rust,ignore}
5087 print_area(5i);
5088 ```
5089
5090 We get a compile-time error:
5091
5092 ```text
5093 error: failed to find an implementation of trait main::HasArea for int
5094 ```
5095
5096 So far, we've only added trait implementations to structs, but you can
5097 implement a trait for any type. So technically, we _could_ implement
5098 `HasArea` for `int`:
5099
5100 ```{rust}
5101 trait HasArea {
5102     fn area(&self) -> f64;
5103 }
5104
5105 impl HasArea for int {
5106     fn area(&self) -> f64 {
5107         println!("this is silly");
5108
5109         *self as f64
5110     }
5111 }
5112
5113 5i.area();
5114 ```
5115
5116 It is considered poor style to implement methods on such primitive types, even
5117 though it is possible.
5118
5119 ## Scoped Method Resolution and Orphan `impl`s
5120
5121 There are two restrictions for implementing traits that prevent this from
5122 getting out of hand.
5123
5124 1. **Scope-based Method Resolution**: Traits must be `use`d in any scope where
5125    you wish to use the trait's methods
5126 2. **No Orphan `impl`s**: Either the trait or the type you're writing the `impl`
5127    for must be inside your crate.
5128
5129 If we organize our crate differently by using modules, we'll need to ensure both
5130 of the conditions are satisfied. Don't worry, you can lean on the compiler since
5131 it won't let you get away with violating them.
5132
5133 ```{rust}
5134 use shapes::HasArea; // satisfies #1
5135
5136 mod shapes {
5137     use std::f64::consts;
5138
5139     pub trait HasArea {
5140         fn area(&self) -> f64;
5141     }
5142
5143     pub struct Circle {
5144         pub x: f64,
5145         pub y: f64,
5146         pub radius: f64,
5147     }
5148
5149     impl HasArea for Circle {
5150         fn area(&self) -> f64 {
5151             consts::PI * (self.radius * self.radius)
5152         }
5153     }
5154 }
5155
5156 fn main() {
5157     // use shapes::HasArea; // This would satisfy #1, too
5158     let c = shapes::Circle {
5159         x: 0.0f64,
5160         y: 0.0f64,
5161         radius: 1.0f64,
5162     };
5163
5164     println!("{}", c.area());
5165 }
5166 ```
5167
5168 Requiring us to `use` traits whose methods we want means that even if someone
5169 does something bad like add methods to `int`, it won't affect us, unless you
5170 `use` that trait.
5171
5172 The second condition allows us to `impl` built-in `trait`s for types we define,
5173 or allows us to `impl` our own `trait`s for built-in types, but restricts us
5174 from mixing and matching third party or built-in `impl`s with third party or
5175 built-in types.
5176
5177 We could `impl` the `HasArea` trait for `int`, because `HasArea` is in our
5178 crate. But if we tried to implement `Float`, a standard library `trait`, for
5179 `int`, we could not, because neither the `trait` nor the `type` are in our
5180 crate.
5181
5182 ## Monomorphization
5183
5184 One last thing about generics and traits: the compiler performs
5185 **monomorphization** on generic functions so they are statically dispatched. To
5186 see what that means, let's take a look at `print_area` again:
5187
5188 ```{rust,ignore}
5189 fn print_area<T: HasArea>(shape: T) {
5190     println!("This shape has an area of {}", shape.area());
5191 }
5192
5193 fn main() {
5194     let c = Circle { ... };
5195
5196     let s = Square { ... };
5197
5198     print_area(c);
5199     print_area(s);
5200 }
5201 ```
5202
5203 Because we have called `print_area` with two different types in place of its
5204 type paramater `T`, Rust will generate two versions of the function with the
5205 appropriate concrete types, replacing the call sites with calls to the concrete
5206 implementations. In other words, the compiler will actually compile something
5207 more like this:
5208
5209 ```{rust,ignore}
5210 fn __print_area_circle(shape: Circle) {
5211     println!("This shape has an area of {}", shape.area());
5212 }
5213
5214 fn __print_area_square(shape: Square) {
5215     println!("This shape has an area of {}", shape.area());
5216 }
5217
5218 fn main() {
5219     let c = Circle { ... };
5220
5221     let s = Square { ... };
5222
5223     __print_area_circle(c);
5224     __print_area_square(s);
5225 }
5226 ```
5227
5228 These names are for illustration; the compiler will generate its own cryptic
5229 names for internal uses. The point is that there is no runtime overhead of
5230 deciding which version to call. The function to be called is determined
5231 statically, at compile time. Thus, generic functions are **statically
5232 dispatched**. The downside is that we have two similar functions, so our binary
5233 is larger.
5234
5235 # Threads
5236
5237 Concurrency and parallelism are topics that are of increasing interest to a
5238 broad subsection of software developers. Modern computers are often multi-core,
5239 to the point that even embedded devices like cell phones have more than one
5240 processor. Rust's semantics lend themselves very nicely to solving a number of
5241 issues that programmers have with concurrency. Many concurrency errors that are
5242 runtime errors in other languages are compile-time errors in Rust.
5243
5244 Rust's concurrency primitive is called a **thread**. It's worth noting that
5245 threads are implemented as a library, and not part of the language. This means
5246 that in the future, other concurrency libraries can be written for Rust to help
5247 in specific scenarios. Here's an example of creating a thread:
5248
5249 ```{rust,ignore}
5250 spawn(move || {
5251     println!("Hello from a thread!");
5252 });
5253 ```
5254
5255 The `spawn` function takes a closure as an argument, and runs that
5256 closure in a new thread. Typically, you will want to use a moving
5257 closure, so that the closure takes ownership of any variables that it
5258 touches.  This implies that those variables are not usable from the
5259 parent thread after the child thread is spawned:
5260
5261 ```{rust,ignore}
5262 let mut x = vec![1i, 2i, 3i];
5263
5264 spawn(move || {
5265     println!("The value of x[0] is: {}", x[0]);
5266 });
5267
5268 println!("The value of x[0] is: {}", x[0]); // error: use of moved value: `x`
5269 ```
5270
5271 `x` is now owned by the closure, and so we can't use it anymore. Many
5272 other languages would let us do this, but it's not safe to do
5273 so. Rust's borrow checker catches the error.
5274
5275 If threads were only able to capture these values, they wouldn't be very useful.
5276 Luckily, threads can communicate with each other through **channel**s. Channels
5277 work like this:
5278
5279 ```{rust,ignore}
5280 let (tx, rx) = channel();
5281
5282 spawn(move || {
5283     tx.send("Hello from a thread!".to_string());
5284 });
5285
5286 let message = rx.recv();
5287 println!("{}", message);
5288 ```
5289
5290 The `channel()` function returns two endpoints: a `Receiver<T>` and a
5291 `Sender<T>`. You can use the `.send()` method on the `Sender<T>` end, and
5292 receive the message on the `Receiver<T>` side with the `recv()` method.  This
5293 method blocks until it gets a message. There's a similar method, `.try_recv()`,
5294 which returns an `Result<T, TryRecvError>` and does not block.
5295
5296 If you want to send messages to the thread as well, create two channels!
5297
5298 ```{rust,ignore}
5299 let (tx1, rx1) = channel();
5300 let (tx2, rx2) = channel();
5301
5302 spawn(move || {
5303     tx1.send("Hello from a thread!".to_string());
5304     let message = rx2.recv();
5305     println!("{}", message);
5306 });
5307
5308 let message = rx1.recv();
5309 println!("{}", message);
5310
5311 tx2.send("Goodbye from main!".to_string());
5312 ```
5313
5314 The closure has one sending end and one receiving end, and the main thread has
5315 one of each as well. Now they can talk back and forth in whatever way they
5316 wish.
5317
5318 Notice as well that because `Sender` and `Receiver` are generic, while you can
5319 pass any kind of information through the channel, the ends are strongly typed.
5320 If you try to pass a string, and then an integer, Rust will complain.
5321
5322 ## Futures
5323
5324 With these basic primitives, many different concurrency patterns can be
5325 developed. Rust includes some of these types in its standard library. For
5326 example, if you wish to compute some value in the background, `Future` is
5327 a useful thing to use:
5328
5329 ```{rust}
5330 # #![allow(deprecated)]
5331 use std::sync::Future;
5332
5333 let mut delayed_value = Future::spawn(move || {
5334     // just return anything for examples' sake
5335
5336     12345i
5337 });
5338 println!("value = {}", delayed_value.get());
5339 ```
5340
5341 Calling `Future::spawn` works just like `spawn()`: it takes a
5342 closure. In this case, though, you don't need to mess with the
5343 channel: just have the closure return the value.
5344
5345 `Future::spawn` will return a value which we can bind with `let`. It needs
5346 to be mutable, because once the value is computed, it saves a copy of the
5347 value, and if it were immutable, it couldn't update itself.
5348
5349 The future will go on processing in the background, and when we need
5350 the final value, we can call `get()` on it. This will block until the
5351 result is done, but if it's finished computing in the background,
5352 we'll just get the value immediately.
5353
5354 ## Success and failure
5355
5356 Threads don't always succeed, they can also panic. A thread that wishes to panic
5357 can call the `panic!` macro, passing a message:
5358
5359 ```{rust,ignore}
5360 spawn(move || {
5361     panic!("Nope.");
5362 });
5363 ```
5364
5365 If a thread panics, it is not possible for it to recover. However, it can
5366 notify other thread that it has panicked. We can do this with `thread::try`:
5367
5368 ```{rust,ignore}
5369 use std::thread;
5370 use std::rand;
5371
5372 let result = thread::try(move || {
5373     if rand::random() {
5374         println!("OK");
5375     } else {
5376         panic!("oops!");
5377     }
5378 });
5379 ```
5380
5381 This thread will randomly panic or succeed. `thread::try` returns a `Result`
5382 type, so we can handle the response like any other computation that may
5383 fail.
5384
5385 # Macros
5386
5387 One of Rust's most advanced features is its system of **macro**s. While
5388 functions allow you to provide abstractions over values and operations, macros
5389 allow you to provide abstractions over syntax. Do you wish Rust had the ability
5390 to do something that it can't currently do? You may be able to write a macro
5391 to extend Rust's capabilities.
5392
5393 You've already used one macro extensively: `println!`. When we invoke
5394 a Rust macro, we need to use the exclamation mark (`!`). There are two reasons
5395 why this is so: the first is that it makes it clear when you're using a
5396 macro. The second is that macros allow for flexible syntax, and so Rust must
5397 be able to tell where a macro starts and ends. The `!(...)` helps with this.
5398
5399 Let's talk some more about `println!`. We could have implemented `println!` as
5400 a function, but it would be worse. Why? Well, what macros allow you to do
5401 is write code that generates more code. So when we call `println!` like this:
5402
5403 ```{rust}
5404 let x = 5i;
5405 println!("x is: {}", x);
5406 ```
5407
5408 The `println!` macro does a few things:
5409
5410 1. It parses the string to find any `{}`s.
5411 2. It checks that the number of `{}`s matches the number of other arguments.
5412 3. It generates a bunch of Rust code, taking this in mind.
5413
5414 What this means is that you get type checking at compile time, because
5415 Rust will generate code that takes all of the types into account. If
5416 `println!` was a function, it could still do this type checking, but it
5417 would happen at run time rather than compile time.
5418
5419 We can check this out using a special flag to `rustc`. Put this code in a file
5420 called `print.rs`:
5421
5422 ```{rust}
5423 fn main() {
5424     let x = 5i;
5425     println!("x is: {}", x);
5426 }
5427 ```
5428
5429 You can have the macros expanded like this: `rustc --pretty=expanded print.rs`, which will
5430 give us this huge result:
5431
5432 ```{rust,ignore}
5433 #![feature(phase)]
5434 #![no_std]
5435 #![feature(globs)]
5436 #[phase(plugin, link)]
5437 extern crate "std" as std;
5438 extern crate "native" as rt;
5439 #[prelude_import]
5440 use std::prelude::*;
5441 fn main() {
5442     let x = 5i;
5443     match (&x,) {
5444         (__arg0,) => {
5445             #[inline]
5446             #[allow(dead_code)]
5447             static __STATIC_FMTSTR: [&'static str, ..1u] = ["x is: "];
5448             let __args_vec =
5449                 &[::std::fmt::argument(::std::fmt::secret_show, __arg0)];
5450             let __args =
5451                 unsafe {
5452                     ::std::fmt::Arguments::new(__STATIC_FMTSTR, __args_vec)
5453                 };
5454             ::std::io::stdio::println_args(&__args)
5455         }
5456     };
5457 }
5458 ```
5459
5460 Whew! This isn't too terrible. You can see that we still `let x = 5i`,
5461 but then things get a little bit hairy. Three more bindings get set: a
5462 static format string, an argument vector, and the arguments. We then
5463 invoke the `println_args` function with the generated arguments.
5464
5465 This is the code that Rust actually compiles. You can see all of the extra
5466 information that's here. We get all of the type safety and options that it
5467 provides, but at compile time, and without needing to type all of this out.
5468 This is how macros are powerful: without them you would need to type all of
5469 this by hand to get a type-checked `println`.
5470
5471 For more on macros, please consult [the Macros Guide](guide-macros.html).
5472 Macros are a very advanced and still slightly experimental feature, but they don't
5473 require a deep understanding to be called, since they look just like functions. The
5474 Guide can help you if you want to write your own.
5475
5476 # Unsafe
5477
5478 Finally, there's one more Rust concept that you should be aware of: `unsafe`.
5479 There are two circumstances where Rust's safety provisions don't work well.
5480 The first is when interfacing with C code, and the second is when building
5481 certain kinds of abstractions.
5482
5483 Rust has support for [FFI](http://en.wikipedia.org/wiki/Foreign_function_interface)
5484 (which you can read about in the [FFI Guide](guide-ffi.html)), but can't guarantee
5485 that the C code will be safe. Therefore, Rust marks such functions with the `unsafe`
5486 keyword, which indicates that the function may not behave properly.
5487
5488 Second, if you'd like to create some sort of shared-memory data structure, Rust
5489 won't allow it, because memory must be owned by a single owner. However, if
5490 you're planning on making access to that shared memory safe – such as with a
5491 mutex – _you_ know that it's safe, but Rust can't know. Writing an `unsafe`
5492 block allows you to ask the compiler to trust you. In this case, the _internal_
5493 implementation of the mutex is considered unsafe, but the _external_ interface
5494 we present is safe. This allows it to be effectively used in normal Rust, while
5495 being able to implement functionality that the compiler can't double check for
5496 us.
5497
5498 Doesn't an escape hatch undermine the safety of the entire system? Well, if
5499 Rust code segfaults, it _must_ be because of unsafe code somewhere. By
5500 annotating exactly where that is, you have a significantly smaller area to
5501 search.
5502
5503 We haven't even talked about any examples here, and that's because I want to
5504 emphasize that you should not be writing unsafe code unless you know exactly
5505 what you're doing. The vast majority of Rust developers will only interact with
5506 it when doing FFI, and advanced library authors may use it to build certain
5507 kinds of abstraction.
5508
5509 # Conclusion
5510
5511 We covered a lot of ground here. When you've mastered everything in this Guide,
5512 you will have a firm grasp of basic Rust development. There's a whole lot more
5513 out there, we've just covered the surface. There's tons of topics that you can
5514 dig deeper into, and we've built specialized guides for many of them. To learn
5515 more, dig into the [full documentation index](index.html).
5516
5517 Happy hacking!