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