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