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