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