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