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