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