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