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