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