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