]> git.lizzy.rs Git - rust.git/blob - src/doc/guide.md
Add a few more derivings to AST types
[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 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 http://www.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](http://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 http://www.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 = [ "someone@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 That's it! We've successfully built `hello_world` with Cargo. Even though our
358 program is simple, it's using much of the real tooling that you'll use for the
359 rest of your Rust career.
360
361 Now that you've got the tools down, let's actually learn more about the Rust
362 language itself. These are the basics that will serve you well through the rest
363 of your time with Rust.
364
365 # Variable bindings
366
367 The first thing we'll learn about are 'variable bindings.' They look like this:
368
369 ```{rust}
370 let x = 5i;
371 ```
372
373 In many languages, this is called a 'variable.' But Rust's variable bindings
374 have a few tricks up their sleeves. Rust has a very powerful feature called
375 'pattern matching' that we'll get into detail with later, but the left
376 hand side of a `let` expression is a full pattern, not just a variable name.
377 This means we can do things like:
378
379 ```{rust}
380 let (x, y) = (1i, 2i);
381 ```
382
383 After this expression is evaluated, `x` will be one, and `y` will be two.
384 Patterns are really powerful, but this is about all we can do with them so far.
385 So let's just keep this in the back of our minds as we go forward.
386
387 By the way, in these examples, `i` indicates that the number is an integer.
388
389 Rust is a statically typed language, which means that we specify our types up
390 front. So why does our first example compile? Well, Rust has this thing called
391 "[Hindley-Milner type
392 inference](http://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system)",
393 named after some really smart type theorists. If you clicked that link, don't
394 be scared: what this means for you is that Rust will attempt to infer the types
395 in your program, and it's pretty good at it. If it can infer the type, Rust
396 doesn't require you to actually type it out.
397
398 We can add the type if we want to. Types come after a colon (`:`):
399
400 ```{rust}
401 let x: int = 5;
402 ```
403
404 If I asked you to read this out loud to the rest of the class, you'd say "`x`
405 is a binding with the type `int` and the value `five`."
406
407 By default, bindings are **immutable**. This code will not compile:
408
409 ```{ignore}
410 let x = 5i;
411 x = 10i;
412 ```
413
414 It will give you this error:
415
416 ```{ignore,notrust}
417 error: re-assignment of immutable variable `x`
418      x = 10i;
419      ^~~~~~~
420 ```
421
422 If you want a binding to be mutable, you can use `mut`:
423
424 ```{rust}
425 let mut x = 5i;
426 x = 10i;
427 ```
428
429 There is no single reason that bindings are immutable by default, but we can
430 think about it through one of Rust's primary focuses: safety. If you forget to
431 say `mut`, the compiler will catch it, and let you know that you have mutated
432 something you may not have cared to mutate. If bindings were mutable by
433 default, the compiler would not be able to tell you this. If you _did_ intend
434 mutation, then the solution is quite easy: add `mut`.
435
436 There are other good reasons to avoid mutable state when possible, but they're
437 out of the scope of this guide. In general, you can often avoid explicit
438 mutation, and so it is preferable in Rust. That said, sometimes, mutation is
439 what you need, so it's not verboten.
440
441 Let's get back to bindings. Rust variable bindings have one more aspect that
442 differs from other languages: bindings are required to be initialized with a
443 value before you're allowed to use it. If we try...
444
445 ```{ignore}
446 let x;
447 ```
448
449 ...we'll get an error:
450
451 ```{ignore}
452 src/guessing_game.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type
453 src/guessing_game.rs:2     let x;
454                                ^
455 ```
456
457 Giving it a type will compile, though:
458
459 ```{ignore}
460 let x: int;
461 ```
462
463 Let's try it out. Change your `src/guessing_game.rs` file to look like this:
464
465 ```{rust}
466 fn main() {
467     let x: int;
468
469     println!("Hello world!");
470 }
471 ```
472
473 You can use `cargo build` on the command line to build it. You'll get a warning,
474 but it will still print "Hello, world!":
475
476 ```{ignore,notrust}
477    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
478 src/guessing_game.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
479 src/guessing_game.rs:2     let x: int;
480                                ^
481 ```
482
483 Rust warns us that we never use the variable binding, but since we never use it,
484 no harm, no foul. Things change if we try to actually use this `x`, however. Let's
485 do that. Change your program to look like this:
486
487 ```{rust,ignore}
488 fn main() {
489     let x: int;
490
491     println!("The value of x is: {}", x);
492 }
493 ```
494
495 And try to build it. You'll get an error:
496
497 ```{bash}
498 $ cargo build
499    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
500 src/guessing_game.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
501 src/guessing_game.rs:4     println!("The value of x is: {}", x);
502                                                              ^
503 note: in expansion of format_args!
504 <std macros>:2:23: 2:77 note: expansion site
505 <std macros>:1:1: 3:2 note: in expansion of println!
506 src/guessing_game.rs:4:5: 4:42 note: expansion site
507 error: aborting due to previous error
508 Could not execute process `rustc src/guessing_game.rs --crate-type bin --out-dir /home/you/projects/guessing_game/target -L /home/you/projects/guessing_game/target -L /home/you/projects/guessing_game/target/deps` (status=101)
509 ```
510
511 Rust will not let us use a value that has not been initialized. So why let us
512 declare a binding without initializing it? You'd think our first example would
513 have errored. Well, Rust is smarter than that. Before we get to that, let's talk
514 about this stuff we've added to `println!`.
515
516 If you include two curly braces (`{}`, some call them moustaches...) in your
517 string to print, Rust will interpret this as a request to interpolate some sort
518 of value. **String interpolation** is a computer science term that means "stick
519 in the middle of a string." We add a comma, and then `x`, to indicate that we
520 want `x` to be the value we're interpolating. The comma is used to separate
521 arguments we pass to functions and macros, if you're passing more than one.
522
523 When you just use the double curly braces, Rust will attempt to display the
524 value in a meaningful way by checking out its type. If you want to specify the
525 format in a more detailed manner, there are a [wide number of options
526 available](/std/fmt/index.html). For now, we'll just stick to the default:
527 integers aren't very complicated to print.
528
529 So, we've cleared up all of the confusion around bindings, with one exception:
530 why does Rust let us declare a variable binding without an initial value if we
531 must initialize the binding before we use it? And how does it know that we have
532 or have not initialized the binding? For that, we need to learn our next
533 concept: `if`.
534
535 # If
536
537 Rust's take on `if` is not particularly complex, but it's much more like the
538 `if` you'll find in a dynamically typed language than in a more traditional
539 systems language. So let's talk about it, to make sure you grasp the nuances.
540
541 `if` is a specific form of a more general concept, the 'branch.' The name comes
542 from a branch in a tree: a decision point, where depending on a choice,
543 multiple paths can be taken.
544
545 In the case of `if`, there is one choice that leads down two paths:
546
547 ```rust
548 let x = 5i;
549
550 if x == 5i {
551     println!("x is five!");
552 }
553 ```
554
555 If we changed the value of `x` to something else, this line would not print.
556 More specifically, if the expression after the `if` evaluates to `true`, then
557 the block is executed. If it's `false`, then it is not.
558
559 If you want something to happen in the `false` case, use an `else`:
560
561 ```
562 let x = 5i;
563
564 if x == 5i {
565     println!("x is five!");
566 } else {
567     println!("x is not five :(");
568 }
569 ```
570
571 This is all pretty standard. However, you can also do this:
572
573
574 ```
575 let x = 5i;
576
577 let y = if x == 5i {
578     10i
579 } else {
580     15i
581 };
582 ```
583
584 Which we can (and probably should) write like this:
585
586 ```
587 let x = 5i;
588
589 let y = if x == 5i { 10i } else { 15i };
590 ```
591
592 This reveals two interesting things about Rust: it is an expression-based
593 language, and semicolons are different than in other 'curly brace and
594 semicolon'-based languages. These two things are related.
595
596 ## Expressions vs. Statements
597
598 Rust is primarily an expression based language. There are only two kinds of
599 statements, and everything else is an expression.
600
601 So what's the difference? Expressions return a value, and statements do not.
602 In many languages, `if` is a statement, and therefore, `let x = if ...` would
603 make no sense. But in Rust, `if` is an expression, which means that it returns
604 a value. We can then use this value to initialize the binding.
605
606 Speaking of which, bindings are a kind of the first of Rust's two statements.
607 The proper name is a **declaration statement**. So far, `let` is the only kind
608 of declaration statement we've seen. Let's talk about that some more.
609
610 In some languages, variable bindings can be written as expressions, not just
611 statements. Like Ruby:
612
613 ```{ruby}
614 x = y = 5
615 ```
616
617 In Rust, however, using `let` to introduce a binding is _not_ an expression. The
618 following will produce a compile-time error:
619
620 ```{ignore}
621 let x = (let y = 5i); // found `let` in ident position
622 ```
623
624 The compiler is telling us here that it was expecting to see the beginning of
625 an expression, and a `let` can only begin a statement, not an expression.
626
627 Note that assigning to an already-bound variable (e.g. `y = 5i`) is still an
628 expression, although its value is not particularly useful. Unlike C, where an
629 assignment evaluates to the assigned value (e.g. `5i` in the previous example),
630 in Rust the value of an assignment is the unit type `()` (which we'll cover later).
631
632 The second kind of statement in Rust is the **expression statement**. Its
633 purpose is to turn any expression into a statement. In practical terms, Rust's
634 grammar expects statements to follow other statements. This means that you use
635 semicolons to separate expressions from each other. This means that Rust
636 looks a lot like most other languages that require you to use semicolons
637 at the end of every line, and you will see semicolons at the end of almost
638 every line of Rust code you see.
639
640 What is this exception that makes us say 'almost?' You saw it already, in this
641 code:
642
643 ```
644 let x = 5i;
645
646 let y: int = if x == 5i { 10i } else { 15i };
647 ```
648
649 Note that I've added the type annotation to `y`, to specify explicitly that I
650 want `y` to be an integer.
651
652 This is not the same as this, which won't compile:
653
654 ```{ignore}
655 let x = 5i;
656
657 let y: int = if x == 5 { 10i; } else { 15i; };
658 ```
659
660 Note the semicolons after the 10 and 15. Rust will give us the following error:
661
662 ```{ignore,notrust}
663 error: mismatched types: expected `int` but found `()` (expected int but found ())
664 ```
665
666 We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a
667 special type in Rust's type system. `()` is different than `null` in other
668 languages, because `()` is distinct from other types. For example, in C, `null`
669 is a valid value for a variable of type `int`. In Rust, `()` is _not_ a valid
670 value for a variable of type `int`. It's only a valid value for variables of
671 the type `()`, which aren't very useful. Remember how we said statements don't
672 return a value? Well, that's the purpose of unit in this case. The semicolon
673 turns any expression into a statement by throwing away its value and returning
674 unit instead.
675
676 There's one more time in which you won't see a semicolon at the end of a line
677 of Rust code. For that, we'll need our next concept: functions.
678
679 # Functions
680
681 You've already seen one function so far, the `main` function:
682
683 ```{rust}
684 fn main() {
685 }
686 ```
687
688 This is the simplest possible function declaration. As we mentioned before,
689 `fn` says 'this is a function,' followed by the name, some parenthesis because
690 this function takes no arguments, and then some curly braces to indicate the
691 body. Here's a function named `foo`:
692
693 ```{rust}
694 fn foo() {
695 }
696 ```
697
698 So, what about taking arguments? Here's a function that prints a number:
699
700 ```{rust}
701 fn print_number(x: int) {
702     println!("x is: {}", x);
703 }
704 ```
705
706 Here's a complete program that uses `print_number`:
707
708 ```{rust}
709 fn main() {
710     print_number(5);
711 }
712
713 fn print_number(x: int) {
714     println!("x is: {}", x);
715 }
716 ```
717
718 As you can see, function arguments work very similar to `let` declarations:
719 you add a type to the argument name, after a colon.
720
721 Here's a complete program that adds two numbers together and prints them:
722
723 ```{rust}
724 fn main() {
725     print_sum(5, 6);
726 }
727
728 fn print_sum(x: int, y: int) {
729     println!("sum is: {}", x + y);
730 }
731 ```
732
733 You separate arguments with a comma, both when you call the function, as well
734 as when you declare it.
735
736 Unlike `let`, you _must_ declare the types of function arguments. This does
737 not work:
738
739 ```{ignore}
740 fn print_number(x, y) {
741     println!("x is: {}", x + y);
742 }
743 ```
744
745 You get this error:
746
747 ```{ignore,notrust}
748 hello.rs:5:18: 5:19 error: expected `:` but found `,`
749 hello.rs:5 fn print_number(x, y) {
750 ```
751
752 This is a deliberate design decision. While full-program inference is possible,
753 languages which have it, like Haskell, often suggest that documenting your
754 types explicitly is a best-practice. We agree that forcing functions to declare
755 types while allowing for inference inside of function bodies is a wonderful
756 compromise between full inference and no inference.
757
758 What about returning a value? Here's a function that adds one to an integer:
759
760 ```{rust}
761 fn add_one(x: int) -> int {
762     x + 1
763 }
764 ```
765
766 Rust functions return exactly one value, and you declare the type after an
767 'arrow', which is a dash (`-`) followed by a greater-than sign (`>`).
768
769 You'll note the lack of a semicolon here. If we added it in:
770
771 ```{ignore}
772 fn add_one(x: int) -> int {
773     x + 1;
774 }
775 ```
776
777 We would get an error:
778
779 ```{ignore,notrust}
780 error: not all control paths return a value
781 fn add_one(x: int) -> int {
782      x + 1;
783 }
784
785 note: consider removing this semicolon:
786      x + 1;
787           ^
788 ```
789
790 Remember our earlier discussions about semicolons and `()`? Our function claims
791 to return an `int`, but with a semicolon, it would return `()` instead. Rust
792 realizes this probably isn't what we want, and suggests removing the semicolon.
793
794 This is very much like our `if` statement before: the result of the block
795 (`{}`) is the value of the expression. Other expression-oriented languages,
796 such as Ruby, work like this, but it's a bit unusual in the systems programming
797 world. When people first learn about this, they usually assume that it
798 introduces bugs. But because Rust's type system is so strong, and because unit
799 is its own unique type, we have never seen an issue where adding or removing a
800 semicolon in a return position would cause a bug.
801
802 But what about early returns? Rust does have a keyword for that, `return`:
803
804 ```{rust}
805 fn foo(x: int) -> int {
806     if x < 5 { return x; }
807
808     x + 1
809 }
810 ```
811
812 Using a `return` as the last line of a function works, but is considered poor
813 style:
814
815 ```{rust}
816 fn foo(x: int) -> int {
817     if x < 5 { return x; }
818
819     return x + 1;
820 }
821 ```
822
823 There are some additional ways to define functions, but they involve features
824 that we haven't learned about yet, so let's just leave it at that for now.
825
826
827 # Comments
828
829 Now that we have some functions, it's a good idea to learn about comments.
830 Comments are notes that you leave to other programmers to help explain things
831 about your code. The compiler mostly ignores them.
832
833 Rust has two kinds of comments that you should care about: **line comment**s
834 and **doc comment**s.
835
836 ```{rust}
837 // Line comments are anything after '//' and extend to the end of the line.
838
839 let x = 5i; // this is also a line comment.
840
841 // If you have a long explanation for something, you can put line comments next
842 // to each other. Put a space between the // and your comment so that it's
843 // more readable.
844 ```
845
846 The other kind of comment is a doc comment. Doc comments use `///` instead of
847 `//`, and support Markdown notation inside:
848
849 ```{rust}
850 /// `hello` is a function that prints a greeting that is personalized based on
851 /// the name given.
852 ///
853 /// # Arguments
854 ///
855 /// * `name` - The name of the person you'd like to greet.
856 ///
857 /// # Example
858 ///
859 /// ```rust
860 /// let name = "Steve";
861 /// hello(name); // prints "Hello, Steve!"
862 /// ```
863 fn hello(name: &str) {
864     println!("Hello, {}!", name);
865 }
866 ```
867
868 When writing doc comments, adding sections for any arguments, return values,
869 and providing some examples of usage is very, very helpful.
870
871 You can use the `rustdoc` tool to generate HTML documentation from these doc
872 comments. We will talk more about `rustdoc` when we get to modules, as
873 generally, you want to export documentation for a full module.
874
875 # Compound Data Types
876
877 Rust, like many programming languages, has a number of different data types
878 that are built-in. You've already done some simple work with integers and
879 strings, but next, let's talk about some more complicated ways of storing data.
880
881 ## Tuples
882
883 The first compound data type we're going to talk about are called **tuple**s.
884 Tuples are an ordered list of a fixed size. Like this:
885
886 ```rust
887 let x = (1i, "hello");
888 ```
889
890 The parenthesis and commas form this two-length tuple. Here's the same code, but
891 with the type annotated:
892
893 ```rust
894 let x: (int, &str) = (1, "hello");
895 ```
896
897 As you can see, the type of a tuple looks just like the tuple, but with each
898 position having a type name rather than the value. Careful readers will also
899 note that tuples are heterogeneous: we have an `int` and a `&str` in this tuple.
900 You haven't seen `&str` as a type before, and we'll discuss the details of
901 strings later. In systems programming languages, strings are a bit more complex
902 than in other languages. For now, just read `&str` as "a string slice," and
903 we'll learn more soon.
904
905 You can access the fields in a tuple through a **destructuring let**. Here's
906 an example:
907
908 ```rust
909 let (x, y, z) = (1i, 2i, 3i);
910
911 println!("x is {}", x);
912 ```
913
914 Remember before when I said the left hand side of a `let` statement was more
915 powerful than just assigning a binding? Here we are. We can put a pattern on
916 the left hand side of the `let`, and if it matches up to the right hand side,
917 we can assign multiple bindings at once. In this case, `let` 'destructures,'
918 or 'breaks up,' the tuple, and assigns the bits to three bindings.
919
920 This pattern is very powerful, and we'll see it repeated more later.
921
922 The last thing to say about tuples is that they are only equivalent if
923 the arity, types, and values are all identical.
924
925 ```rust
926 let x = (1i, 2i, 3i);
927 let y = (2i, 3i, 4i);
928
929 if x == y {
930     println!("yes");
931 } else {
932     println!("no");
933 }
934 ```
935
936 This will print `no`, as the values aren't equal.
937
938 One other use of tuples is to return multiple values from a function:
939
940 ```rust
941 fn next_two(x: int) -> (int, int) { (x + 1i, x + 2i) }
942
943 fn main() {
944     let (x, y) = next_two(5i);
945     println!("x, y = {}, {}", x, y);
946 }
947 ```
948
949 Even though Rust functions can only return one value, a tuple _is_ one value,
950 that happens to be made up of two. You can also see in this example how you
951 can destructure a pattern returned by a function, as well.
952
953 Tuples are a very simple data structure, and so are not often what you want.
954 Let's move on to their bigger sibling, structs.
955
956 ## Structs
957
958 A struct is another form of a 'record type,' just like a tuple. There's a
959 difference: structs give each element that they contain a name, called a
960 'field' or a 'member.' Check it out:
961
962 ```rust
963 struct Point {
964     x: int,
965     y: int,
966 }
967
968 fn main() {
969     let origin = Point { x: 0i, y:  0i };
970
971     println!("The origin is at ({}, {})", origin.x, origin.y);
972 }
973 ```
974
975 There's a lot going on here, so let's break it down. We declare a struct with
976 the `struct` keyword, and then with a name. By convention, structs begin with a
977 capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`.
978
979 We can create an instance of our struct via `let`, as usual, but we use a `key:
980 value` style syntax to set each field. The order doesn't need to be the same as
981 in the original declaration.
982
983 Finally, because fields have names, we can access the field through dot
984 notation: `origin.x`.
985
986 The values in structs are immutable, like other bindings in Rust. However, you
987 can use `mut` to make them mutable:
988
989 ```rust
990 struct Point {
991     x: int,
992     y: int,
993 }
994
995 fn main() {
996     let mut point = Point { x: 0i, y:  0i };
997
998     point.x = 5;
999
1000     println!("The point is at ({}, {})", point.x, point.y);
1001 }
1002 ```
1003
1004 This will print `The point is at (5, 0)`.
1005
1006 ## Tuple Structs and Newtypes
1007
1008 Rust has another data type that's like a hybrid between a tuple and a struct,
1009 called a **tuple struct**. Tuple structs do have a name, but their fields
1010 don't:
1011
1012
1013 ```
1014 struct Color(int, int, int);
1015 struct Point(int, int, int);
1016 ```
1017
1018 These two will not be equal, even if they have the same values:
1019
1020 ```{rust,ignore}
1021 let black  = Color(0, 0, 0);
1022 let origin = Point(0, 0, 0);
1023 ```
1024
1025 It is almost always better to use a struct than a tuple struct. We would write
1026 `Color` and `Point` like this instead:
1027
1028 ```rust
1029 struct Color {
1030     red: int,
1031     blue: int,
1032     green: int,
1033 }
1034
1035 struct Point {
1036     x: int,
1037     y: int,
1038     z: int,
1039 }
1040 ```
1041
1042 Now, we have actual names, rather than positions. Good names are important,
1043 and with a struct, we have actual names.
1044
1045 There _is_ one case when a tuple struct is very useful, though, and that's a
1046 tuple struct with only one element. We call this a 'newtype,' because it lets
1047 you create a new type that's a synonym for another one:
1048
1049 ```
1050 struct Inches(int);
1051 struct Centimeters(int);
1052
1053 let length = Inches(10);
1054
1055 let Inches(integer_length) = length;
1056 println!("length is {} inches", integer_length);
1057 ```
1058
1059 As you can see here, you can extract the inner integer type through a
1060 destructuring `let`.
1061
1062 ## Enums
1063
1064 Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful
1065 feature of Rust, and are used throughout the standard library. Enums look
1066 like this:
1067
1068 ```
1069 enum Ordering {
1070     Less,
1071     Equal,
1072     Greater,
1073 }
1074 ```
1075
1076 This is an enum that is provided by the Rust standard library. An `Ordering`
1077 can only be _one_ of `Less`, `Equal`, or `Greater` at any given time. Here's
1078 an example:
1079
1080 ```rust
1081 fn cmp(a: int, b: int) -> Ordering {
1082     if a < b { Less }
1083     else if a > b { Greater }
1084     else { Equal }
1085 }
1086
1087 fn main() {
1088     let x = 5i;
1089     let y = 10i;
1090
1091     let ordering = cmp(x, y);
1092
1093     if ordering == Less {
1094         println!("less");
1095     } else if ordering == Greater {
1096         println!("greater");
1097     } else if ordering == Equal {
1098         println!("equal");
1099     }
1100 }
1101 ```
1102
1103 `cmp` is a function that compares two things, and returns an `Ordering`. We
1104 return either `Less`, `Greater`, or `Equal`, depending on if the two values
1105 are greater, less, or equal.
1106
1107 The `ordering` variable has the type `Ordering`, and so contains one of the
1108 three values. We can then do a bunch of `if`/`else` comparisons to check
1109 which one it is.
1110
1111 However, repeated `if`/`else` comparisons get quite tedious. Rust has a feature
1112 that not only makes them nicer to read, but also makes sure that you never
1113 miss a case. Before we get to that, though, let's talk about another kind of
1114 enum: one with values.
1115
1116 This enum has two variants, one of which has a value:
1117
1118 ```{rust}
1119 enum OptionalInt {
1120     Value(int),
1121     Missing,
1122 }
1123
1124 fn main() {
1125     let x = Value(5);
1126     let y = Missing;
1127
1128     match x {
1129         Value(n) => println!("x is {:d}", n),
1130         Missing  => println!("x is missing!"),
1131     }
1132
1133     match y {
1134         Value(n) => println!("y is {:d}", n),
1135         Missing  => println!("y is missing!"),
1136     }
1137 }
1138 ```
1139
1140 This enum represents an `int` that we may or may not have. In the `Missing`
1141 case, we have no value, but in the `Value` case, we do. This enum is specific
1142 to `int`s, though. We can make it usable by any type, but we haven't quite
1143 gotten there yet!
1144
1145 You can have any number of values in an enum:
1146
1147 ```
1148 enum OptionalColor {
1149     Color(int, int, int),
1150     Missing
1151 }
1152 ```
1153
1154 Enums with values are quite useful, but as I mentioned, they're even more
1155 useful when they're generic across types. But before we get to generics, let's
1156 talk about how to fix this big `if`/`else` statements we've been writing. We'll
1157 do that with `match`.
1158
1159 # Match
1160
1161 Often, a simple `if`/`else` isn't enough, because you have more than two
1162 possible options. And `else` conditions can get incredibly complicated. So
1163 what's the solution?
1164
1165 Rust has a keyword, `match`, that allows you to replace complicated `if`/`else`
1166 groupings with something more powerful. Check it out:
1167
1168 ```rust
1169 let x = 5i;
1170
1171 match x {
1172     1 => println!("one"),
1173     2 => println!("two"),
1174     3 => println!("three"),
1175     4 => println!("four"),
1176     5 => println!("five"),
1177     _ => println!("something else"),
1178 }
1179 ```
1180
1181 `match` takes an expression, and then branches based on its value. Each 'arm' of
1182 the branch is of the form `val => expression`. When the value matches, that arm's
1183 expression will be evaluated. It's called `match` because of the term 'pattern
1184 matching,' which `match` is an implementation of.
1185
1186 So what's the big advantage here? Well, there are a few. First of all, `match`
1187 does 'exhaustiveness checking.' Do you see that last arm, the one with the
1188 underscore (`_`)? If we remove that arm, Rust will give us an error:
1189
1190 ```{ignore,notrust}
1191 error: non-exhaustive patterns: `_` not covered
1192 ```
1193
1194 In other words, Rust is trying to tell us we forgot a value. Because `x` is an
1195 integer, Rust knows that it can have a number of different values. For example,
1196 `6i`. But without the `_`, there is no arm that could match, and so Rust refuses
1197 to compile. `_` is sort of like a catch-all arm. If none of the other arms match,
1198 the arm with `_` will. And since we have this catch-all arm, we now have an arm
1199 for every possible value of `x`, and so our program will now compile.
1200
1201 `match` statements also destructure enums, as well. Remember this code from the
1202 section on enums?
1203
1204 ```{rust}
1205 fn cmp(a: int, b: int) -> Ordering {
1206     if a < b { Less }
1207     else if a > b { Greater }
1208     else { Equal }
1209 }
1210
1211 fn main() {
1212     let x = 5i;
1213     let y = 10i;
1214
1215     let ordering = cmp(x, y);
1216
1217     if ordering == Less {
1218         println!("less");
1219     } else if ordering == Greater {
1220         println!("greater");
1221     } else if ordering == Equal {
1222         println!("equal");
1223     }
1224 }
1225 ```
1226
1227 We can re-write this as a `match`:
1228
1229 ```{rust}
1230 fn cmp(a: int, b: int) -> Ordering {
1231     if a < b { Less }
1232     else if a > b { Greater }
1233     else { Equal }
1234 }
1235
1236 fn main() {
1237     let x = 5i;
1238     let y = 10i;
1239
1240     match cmp(x, y) {
1241         Less    => println!("less"),
1242         Greater => println!("greater"),
1243         Equal   => println!("equal"),
1244     }
1245 }
1246 ```
1247
1248 This version has way less noise, and it also checks exhaustively to make sure
1249 that we have covered all possible variants of `Ordering`. With our `if`/`else`
1250 version, if we had forgotten the `Greater` case, for example, our program would
1251 have happily compiled. If we forget in the `match`, it will not. Rust helps us
1252 make sure to cover all of our bases.
1253
1254 `match` is also an expression, which means we can use it on the right hand side
1255 of a `let` binding. We could also implement the previous line like this:
1256
1257 ```{rust}
1258 fn cmp(a: int, b: int) -> Ordering {
1259     if a < b { Less }
1260     else if a > b { Greater }
1261     else { Equal }
1262 }
1263
1264 fn main() {
1265     let x = 5i;
1266     let y = 10i;
1267
1268     let result = match cmp(x, y) {
1269         Less    => "less",
1270         Greater => "greater",
1271         Equal   => "equal",
1272     };
1273
1274     println!("{}", result);
1275 }
1276 ```
1277
1278 In this case, it doesn't make a lot of sense, as we are just making a temporary
1279 string where we don't need to, but sometimes, it's a nice pattern.
1280
1281 # Looping
1282
1283 Looping is the last basic construct that we haven't learned yet in Rust. Rust has
1284 two main looping constructs: `for` and `while`.
1285
1286 ## `for`
1287
1288 The `for` loop is used to loop a particular number of times. Rust's `for` loops
1289 work a bit differently than in other systems languages, however. Rust's `for`
1290 loop doesn't look like this C `for` loop:
1291
1292 ```{ignore,c}
1293 for (x = 0; x < 10; x++) {
1294     printf( "%d\n", x );
1295 }
1296 ```
1297
1298 It looks like this:
1299
1300 ```{rust}
1301 for x in range(0i, 10i) {
1302     println!("{:d}", x);
1303 }
1304 ```
1305
1306 In slightly more abstract terms,
1307
1308 ```{ignore,notrust}
1309 for var in expression {
1310     code
1311 }
1312 ```
1313
1314 The expression is an iterator, which we will discuss in more depth later in the
1315 guide. The iterator gives back a series of elements. Each element is one
1316 iteration of the loop. That value is then bound to the name `var`, which is
1317 valid for the loop body. Once the body is over, the next value is fetched from
1318 the iterator, and we loop another time. When there are no more values, the
1319 `for` loop is over.
1320
1321 In our example, the `range` function is a function, provided by Rust, that
1322 takes a start and an end position, and gives an iterator over those values. The
1323 upper bound is exclusive, though, so our loop will print `0` through `9`, not
1324 `10`.
1325
1326 Rust does not have the "C style" `for` loop on purpose. Manually controlling
1327 each element of the loop is complicated and error prone, even for experienced C
1328 developers. There's an old joke that goes, "There are two hard problems in
1329 computer science: naming things, cache invalidation, and off-by-one errors."
1330 The joke, of course, being that the setup says "two hard problems" but then
1331 lists three things. This happens quite a bit with "C style" `for` loops.
1332
1333 We'll talk more about `for` when we cover **vector**s, later in the Guide.
1334
1335 ## `while`
1336
1337 The other kind of looping construct in Rust is the `while` loop. It looks like
1338 this:
1339
1340 ```{rust}
1341 let mut x = 5u;
1342 let mut done = false;
1343
1344 while !done {
1345     x += x - 3;
1346     println!("{}", x);
1347     if x % 5 == 0 { done = true; }
1348 }
1349 ```
1350
1351 `while` loops are the correct choice when you're not sure how many times
1352 you need to loop. 
1353
1354 If you need an infinite loop, you may be tempted to write this:
1355
1356 ```{rust,ignore}
1357 while true {
1358 ```
1359
1360 Rust has a dedicated keyword, `loop`, to handle this case:
1361
1362 ```{rust,ignore}
1363 loop {
1364 ```
1365
1366 Rust's control-flow analysis treats this construct differently than a
1367 `while true`, since we know that it will always loop. The details of what
1368 that _means_ aren't super important to understand at this stage, but in
1369 general, the more information we can give to the compiler, the better it
1370 can do with safety and code generation. So you should always prefer
1371 `loop` when you plan to loop infinitely.
1372
1373 ## Ending iteration early
1374
1375 Let's take a look at that `while` loop we had earlier:
1376
1377 ```{rust}
1378 let mut x = 5u;
1379 let mut done = false;
1380
1381 while !done {
1382     x += x - 3;
1383     println!("{}", x);
1384     if x % 5 == 0 { done = true; }
1385 }
1386 ```
1387
1388 We had to keep a dedicated `mut` boolean variable binding, `done`, to know
1389 when we should skip out of the loop. Rust has two keywords to help us with
1390 modifying iteration: `break` and `continue`.
1391
1392 In this case, we can write the loop in a better way with `break`:
1393
1394 ```{rust}
1395 let mut x = 5u;
1396
1397 loop {
1398     x += x - 3;
1399     println!("{}", x);
1400     if x % 5 == 0 { break; }
1401 }
1402 ```
1403
1404 We now loop forever with `loop`, and use `break` to break out early.
1405
1406 `continue` is similar, but instead of ending the loop, goes to the next
1407 iteration: This will only print the odd numbers:
1408
1409 ```
1410 for x in range(0i, 10i) {
1411     if x % 2 == 0 { continue; }
1412
1413     println!("{:d}", x);
1414 }
1415 ```
1416
1417 Both `continue` and `break` are valid in both kinds of loops.
1418
1419 We have now learned all of the most basic Rust concepts. We're ready to start
1420 building our guessing game, but we need to know how to do one last thing first:
1421 get input from the keyboard. You can't have a guessing game without the ability
1422 to guess!
1423
1424 # Standard Input
1425
1426 Getting input from the keyboard is pretty easy, but uses some things
1427 we haven't seen before. Here's a simple program that reads some input,
1428 and then prints it back out:
1429
1430 ```{rust,ignore}
1431 use std::io;
1432
1433 fn main() {
1434     println!("Type something!");
1435
1436     let input = std::io::stdin().read_line().ok().expect("Failed to read line");
1437
1438     println!("{}", input);
1439 }
1440 ```
1441
1442 Let's go over these chunks, one by one:
1443
1444 ```{rust,ignore}
1445 std::io::stdin();
1446 ```
1447
1448 This calls a function, `stdin()`, that lives inside the `std::io` module. As
1449 you can imagine, everything in `std` is provided by Rust, the 'standard
1450 library.' We'll talk more about the module system later.
1451
1452 Since writing the fully qualified name all the time is annoying, we can use
1453 the `use` statement to import it in:
1454
1455 ```{rust}
1456 use std::io::stdin;
1457
1458 stdin();
1459 ```
1460
1461 However, it's considered better practice to not import individual functions, but
1462 to import the module, and only use one level of qualification:
1463
1464 ```{rust}
1465 use std::io;
1466
1467 io::stdin();
1468 ```
1469
1470 Let's update our example to use this style:
1471
1472 ```{rust,ignore}
1473 use std::io;
1474
1475 fn main() {
1476     println!("Type something!");
1477
1478     let input = io::stdin().read_line().ok().expect("Failed to read line");
1479
1480     println!("{}", input);
1481 }
1482 ```
1483
1484 Next up:
1485
1486 ```{rust,ignore}
1487 .read_line()
1488 ```
1489
1490 The `read_line()` method can be called on the result of `stdin()` to return
1491 a full line of input. Nice and easy.
1492
1493 ```{rust,ignore}
1494 .ok().expect("Failed to read line");
1495 ```
1496
1497 Do you remember this code? 
1498
1499 ```
1500 enum OptionalInt {
1501     Value(int),
1502     Missing,
1503 }
1504
1505 fn main() {
1506     let x = Value(5);
1507     let y = Missing;
1508
1509     match x {
1510         Value(n) => println!("x is {:d}", n),
1511         Missing  => println!("x is missing!"),
1512     }
1513
1514     match y {
1515         Value(n) => println!("y is {:d}", n),
1516         Missing  => println!("y is missing!"),
1517     }
1518 }
1519 ```
1520
1521 We had to match each time, to see if we had a value or not. In this case,
1522 though, we _know_ that `x` has a `Value`. But `match` forces us to handle
1523 the `missing` case. This is what we want 99% of the time, but sometimes, we
1524 know better than the compiler.
1525
1526 Likewise, `read_line()` does not return a line of input. It _might_ return a
1527 line of input. It might also fail to do so. This could happen if our program
1528 isn't running in a terminal, but as part of a cron job, or some other context
1529 where there's no standard input. Because of this, `read_line` returns a type
1530 very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about
1531 `IoResult<T>` yet because it is the **generic** form of our `OptionalInt`.
1532 Until then, you can think of it as being the same thing, just for any type, not
1533 just `int`s.
1534
1535 Rust provides a method on these `IoResult<T>`s called `ok()`, which does the
1536 same thing as our `match` statement, but assuming that we have a valid value.
1537 If we don't, it will terminate our program. In this case, if we can't get
1538 input, our program doesn't work, so we're okay with that. In most cases, we
1539 would want to handle the error case explicitly. The result of `ok()` has a
1540 method, `expect()`, which allows us to give an error message if this crash
1541 happens.
1542
1543 We will cover the exact details of how all of this works later in the Guide.
1544 For now, this gives you enough of a basic understanding to work with.
1545
1546 Back to the code we were working on! Here's a refresher:
1547
1548 ```{rust,ignore}
1549 use std::io;
1550
1551 fn main() {
1552     println!("Type something!");
1553
1554     let input = io::stdin().read_line().ok().expect("Failed to read line");
1555
1556     println!("{}", input);
1557 }
1558 ```
1559
1560 With long lines like this, Rust gives you some flexibility with the whitespace.
1561 We _could_ write the example like this:
1562
1563 ```{rust,ignore}
1564 use std::io;
1565
1566 fn main() {
1567     println!("Type something!");
1568
1569     let input = io::stdin()
1570                   .read_line()
1571                   .ok()
1572                   .expect("Failed to read line");
1573
1574     println!("{}", input);
1575 }
1576 ```
1577
1578 Sometimes, this makes things more readable. Sometimes, less. Use your judgement
1579 here.
1580
1581 That's all you need to get basic input from the standard input! It's not too
1582 complicated, but there are a number of small parts.
1583
1584 # Guessing Game
1585
1586 Okay! We've got the basics of Rust down. Let's write a bigger program.
1587
1588 For our first project, we'll implement a classic beginner programming problem:
1589 the guessing game. Here's how it works: Our program will generate a random
1590 integer between one and a hundred. It will then prompt us to enter a guess.
1591 Upon entering our guess, it will tell us if we're too low or too high. Once we
1592 guess correctly, it will congratulate us, and print the number of guesses we've
1593 taken to the screen. Sound good?
1594
1595 ## Set up
1596
1597 Let's set up a new project. Go to your projects directory, and make a new
1598 directory for the project, as well as a `src` directory for our code:
1599
1600 ```{bash}
1601 $ cd ~/projects
1602 $ mkdir guessing_game
1603 $ cd guessing_game
1604 $ mkdir src
1605 ```
1606
1607 Great. Next, let's make a `Cargo.toml` file so Cargo knows how to build our
1608 project:
1609
1610 ```{ignore}
1611 [package]
1612
1613 name = "guessing_game"
1614 version = "0.1.0"
1615 authors = [ "someone@example.com" ]
1616
1617 [[bin]]
1618
1619 name = "guessing_game"
1620 ```
1621
1622 Finally, we need our source file. Let's just make it hello world for now, so we
1623 can check that our setup works. In `src/guessing_game.rs`:
1624
1625 ```{rust}
1626 fn main() {
1627     println!("Hello world!");
1628 }
1629 ```
1630
1631 Let's make sure that worked:
1632
1633 ```{bash}
1634 $ cargo build
1635    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
1636 $
1637 ```
1638
1639 Excellent! Open up your `src/guessing_game.rs` again. We'll be writing all of
1640 our code in this file. We'll talk about multiple-file projects later on in the
1641 guide.
1642
1643 ## Processing a Guess
1644
1645 Let's get to it! The first thing we need to do for our guessing game is
1646 allow our player to input a guess. Put this in your `src/guessing_game.rs`:
1647
1648 ```{rust,no_run}
1649 use std::io;
1650
1651 fn main() {
1652     println!("Guess the number!");
1653
1654     println!("Please input your guess.");
1655
1656     let input = io::stdin().read_line()
1657                            .ok()
1658                            .expect("Failed to read line");
1659
1660     println!("You guessed: {}", input);
1661 }
1662 ```
1663
1664 You've seen this code before, when we talked about standard input. We
1665 import the `std::io` module with `use`, and then our `main` function contains
1666 our program's logic. We print a little message announcing the game, ask the
1667 user to input a guess, get their input, and then print it out.
1668
1669 Because we talked about this in the section on standard I/O, I won't go into
1670 more details here. If you need a refresher, go re-read that section.
1671
1672 ## Generating a secret number
1673
1674 Next, we need to generate a secret number. To do that, we need to use Rust's
1675 random number generation, which we haven't talked about yet. Rust includes a
1676 bunch of interesting functions in its standard library. If you need a bit of
1677 code, it's possible that it's already been written for you! In this case,
1678 we do know that Rust has random number generation, but we don't know how to
1679 use it.
1680
1681 Enter the docs. Rust has a page specifically to document the standard library.
1682 You can find that page [here](std/index.html). There's a lot of information on
1683 that page, but the best part is the search bar. Right up at the top, there's
1684 a box that you can enter in a search term. The search is pretty primitive
1685 right now, but is getting better all the time. If you type 'random' in that
1686 box, the page will update to [this
1687 one](http://doc.rust-lang.org/std/index.html?search=random). The very first
1688 result is a link to
1689 [std::rand::random](http://doc.rust-lang.org/std/rand/fn.random.html). If we
1690 click on that result, we'll be taken to its documentation page.
1691
1692 This page shows us a few things: the type signature of the function, some
1693 explanatory text, and then an example. Let's modify our code to add in the
1694 `random` function:
1695
1696 ```{rust,ignore}
1697 use std::io;
1698 use std::rand;
1699
1700 fn main() {
1701     println!("Guess the number!");
1702
1703     let secret_number = (rand::random() % 100i) + 1i;
1704
1705     println!("The secret number is: {}", secret_number);
1706
1707     println!("Please input your guess.");
1708
1709     let input = io::stdin().read_line()
1710                            .ok()
1711                            .expect("Failed to read line");
1712
1713
1714     println!("You guessed: {}", input);
1715 }
1716 ```
1717
1718 The first thing we changed was to `use std::rand`, as the docs
1719 explained.  We then added in a `let` expression to create a variable binding
1720 named `secret_number`, and we printed out its result. Let's try to compile
1721 this using `cargo build`:
1722
1723 ```{notrust,no_run}
1724 $ cargo build
1725    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
1726 src/guessing_game.rs:7:26: 7:34 error: the type of this value must be known in this context
1727 src/guessing_game.rs:7     let secret_number = (rand::random() % 100i) + 1i;
1728                                                 ^~~~~~~~
1729 error: aborting due to previous error
1730 ```
1731
1732 It didn't work! Rust says "the type of this value must be known in this
1733 context." What's up with that? Well, as it turns out, `rand::random()` can
1734 generate many kinds of random values, not just integers. And in this case, Rust
1735 isn't sure what kind of value `random()` should generate. So we have to help
1736 it. With number literals, we just add an `i` onto the end to tell Rust they're
1737 integers, but that does not work with functions. There's a different syntax,
1738 and it looks like this:
1739
1740 ```{rust,ignore}
1741 rand::random::<int>();
1742 ```
1743
1744 This says "please give me a random `int` value." We can change our code to use
1745 this hint...
1746
1747 ```{rust,no_run}
1748 use std::io;
1749 use std::rand;
1750
1751 fn main() {
1752     println!("Guess the number!");
1753
1754     let secret_number = (rand::random::<int>() % 100i) + 1i;
1755
1756     println!("The secret number is: {}", secret_number);
1757
1758     println!("Please input your guess.");
1759
1760     let input = io::stdin().read_line()
1761                            .ok()
1762                            .expect("Failed to read line");
1763
1764
1765     println!("You guessed: {}", input);
1766 }
1767 ```
1768
1769 ... and then recompile:
1770
1771 ```{notrust,ignore}
1772 $ cargo build
1773   Compiling guessing_game v0.1.0 (file:/home/steve/tmp/guessing_game)
1774 $
1775 ```
1776
1777 Excellent! Try running our new program a few times:
1778
1779 ```{notrust,ignore}
1780 $ ./target/guessing_game 
1781 Guess the number!
1782 The secret number is: 7
1783 Please input your guess.
1784 4
1785 You guessed: 4
1786 $ ./target/guessing_game 
1787 Guess the number!
1788 The secret number is: 83
1789 Please input your guess.
1790 5
1791 You guessed: 5
1792 $ ./target/guessing_game 
1793 Guess the number!
1794 The secret number is: -29
1795 Please input your guess.
1796 42
1797 You guessed: 42
1798 ```
1799
1800 Wait. Negative 29? We wanted a number between one and a hundred! We have two
1801 options here: we can either ask `random()` to generate an unsigned integer, which
1802 can only be positive, or we can use the `abs()` function. Let's go with the
1803 unsigned integer approach. If we want a random positive number, we should ask for
1804 a random positive number. Our code looks like this now:
1805
1806 ```{rust,no_run}
1807 use std::io;
1808 use std::rand;
1809
1810 fn main() {
1811     println!("Guess the number!");
1812
1813     let secret_number = (rand::random::<uint>() % 100u) + 1u;
1814
1815     println!("The secret number is: {}", secret_number);
1816
1817     println!("Please input your guess.");
1818
1819     let input = io::stdin().read_line()
1820                            .ok()
1821                            .expect("Failed to read line");
1822
1823
1824     println!("You guessed: {}", input);
1825 }
1826 ```
1827
1828 And trying it out:
1829
1830 ```{notrust,ignore}
1831 $ cargo build
1832    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
1833 $ ./target/guessing_game 
1834 Guess the number!
1835 The secret number is: 57
1836 Please input your guess.
1837 3
1838 You guessed: 3
1839 ```
1840
1841 Great! Next up: let's compare our guess to the secret guess.
1842
1843 ## Comparing guesses
1844
1845 If you remember, earlier in the tutorial, we made a `cmp` function that compared
1846 two numbers. Let's add that in, along with a `match` statement to compare the
1847 guess to the secret guess:
1848
1849 ```{rust,ignore}
1850 use std::io;
1851 use std::rand;
1852
1853 fn main() {
1854     println!("Guess the number!");
1855
1856     let secret_number = (rand::random::<uint>() % 100u) + 1u;
1857
1858     println!("The secret number is: {}", secret_number);
1859
1860     println!("Please input your guess.");
1861
1862     let input = io::stdin().read_line()
1863                            .ok()
1864                            .expect("Failed to read line");
1865
1866
1867     println!("You guessed: {}", input);
1868
1869     match cmp(input, secret_number) { 
1870         Less    => println!("Too small!"),
1871         Greater => println!("Too big!"),
1872         Equal   => { println!("You win!"); },
1873     }
1874 }
1875
1876 fn cmp(a: int, b: int) -> Ordering {
1877     if a < b { Less }
1878     else if a > b { Greater }
1879     else { Equal }
1880 }
1881 ```
1882
1883 If we try to compile, we'll get some errors:
1884
1885 ```{notrust,ignore}
1886 $ cargo build
1887 $ cargo build
1888    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
1889 src/guessing_game.rs:20:15: 20:20 error: mismatched types: expected `int` but found `collections::string::String` (expected int but found struct collections::string::String)
1890 src/guessing_game.rs:20     match cmp(input, secret_number) {
1891                                       ^~~~~
1892 src/guessing_game.rs:20:22: 20:35 error: mismatched types: expected `int` but found `uint` (expected int but found uint)
1893 src/guessing_game.rs:20     match cmp(input, secret_number) {
1894                                              ^~~~~~~~~~~~~
1895 error: aborting due to 2 previous errors
1896 ```
1897
1898 This often happens when writing Rust programs, and is one of Rust's greatest
1899 strengths. You try out some code, see if it compiles, and Rust tells you that
1900 you've done something wrong. In this case, our `cmp` function works on integers,
1901 but we've given it unsigned integers. In this case, the fix is easy, because
1902 we wrote the `cmp` function! Let's change it to take `uint`s:
1903
1904 ```{rust,ignore}
1905 use std::io;
1906 use std::rand;
1907
1908 fn main() {
1909     println!("Guess the number!");
1910
1911     let secret_number = (rand::random::<uint>() % 100u) + 1u;
1912
1913     println!("The secret number is: {}", secret_number);
1914
1915     println!("Please input your guess.");
1916
1917     let input = io::stdin().read_line()
1918                            .ok()
1919                            .expect("Failed to read line");
1920
1921
1922     println!("You guessed: {}", input);
1923
1924     match cmp(input, secret_number) {
1925         Less    => println!("Too small!"),
1926         Greater => println!("Too big!"),
1927         Equal   => { println!("You win!"); },
1928     }
1929 }
1930
1931 fn cmp(a: uint, b: uint) -> Ordering {
1932     if a < b { Less }
1933     else if a > b { Greater }
1934     else { Equal }
1935 }
1936 ```
1937
1938 And try compiling again:
1939
1940 ```{notrust,ignore}
1941 $ cargo build
1942    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
1943 src/guessing_game.rs:20:15: 20:20 error: mismatched types: expected `uint` but found `collections::string::String` (expected uint but found struct collections::string::String)
1944 src/guessing_game.rs:20     match cmp(input, secret_number) {
1945                                       ^~~~~
1946 error: aborting due to previous error
1947 ```
1948
1949 This error is similar to the last one: we expected to get a `uint`, but we got
1950 a `String` instead! That's because our `input` variable is coming from the
1951 standard input, and you can guess anything. Try it:
1952
1953 ```{notrust,ignore}
1954 $ ./target/guessing_game 
1955 Guess the number!
1956 The secret number is: 73
1957 Please input your guess.
1958 hello
1959 You guessed: hello
1960 ```
1961
1962 Oops! Also, you'll note that we just ran our program even though it didn't compile.
1963 This works because the older version we did successfully compile was still lying
1964 around. Gotta be careful!
1965
1966 Anyway, we have a `String`, but we need a `uint`. What to do? Well, there's
1967 a function for that:
1968
1969 ```{rust,ignore}
1970 let input = io::stdin().read_line()
1971                        .ok()
1972                        .expect("Failed to read line");
1973 let guess: Option<uint> = from_str(input.as_slice());
1974 ```
1975
1976 The `from_str` function takes in a `&str` value and converts it into something.
1977 We tell it what kind of something with a type hint. Remember our type hint with
1978 `random()`? It looked like this:
1979
1980 ```{rust,ignore}
1981 rand::random::<uint>();
1982 ```
1983
1984 There's an alternate way of providing a hint too, and that's declaring the type
1985 in a `let`:
1986
1987 ```{rust,ignore}
1988 let x: uint = rand::random();
1989 ```
1990
1991 In this case, we say `x` is a `uint` explicitly, so Rust is able to properly
1992 tell `random()` what to generate. In a similar fashion, both of these work:
1993
1994 ```{rust,ignore}
1995 let guess = from_str::<Option<uint>>("5");
1996 let guess: Option<uint> = from_str("5");
1997 ```
1998
1999 In this case, I happen to prefer the latter, and in the `random()` case, I prefer
2000 the former. I think the nested `<>`s make the first option especially ugly and
2001 a bit harder to read.
2002
2003 Anyway, with us now convering our input to a number, our code looks like this:
2004
2005 ```{rust,ignore}
2006 use std::io;
2007 use std::rand;
2008
2009 fn main() {
2010     println!("Guess the number!");
2011
2012     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2013
2014     println!("The secret number is: {}", secret_number);
2015
2016     println!("Please input your guess.");
2017
2018     let input = io::stdin().read_line()
2019                            .ok()
2020                            .expect("Failed to read line");
2021     let input_num: Option<uint> = from_str(input.as_slice());
2022
2023
2024
2025     println!("You guessed: {}", input_num);
2026
2027     match cmp(input_num, secret_number) {
2028         Less    => println!("Too small!"),
2029         Greater => println!("Too big!"),
2030         Equal   => { println!("You win!"); },
2031     }
2032 }
2033
2034 fn cmp(a: uint, b: uint) -> Ordering {
2035     if a < b { Less }
2036     else if a > b { Greater }
2037     else { Equal }
2038 }
2039 ```
2040
2041 Let's try it out!
2042
2043 ```{notrust,ignore}
2044 $ cargo build
2045    Compiling guessing_game v0.1.0 (file:/home/steve/tmp/guessing_game)
2046 src/guessing_game.rs:22:15: 22:24 error: mismatched types: expected `uint` but found `core::option::Option<uint>` (expected uint but found enum core::option::Option)
2047 src/guessing_game.rs:22     match cmp(input_num, secret_number) {
2048                                       ^~~~~~~~~
2049 error: aborting due to previous error
2050 ```
2051
2052 Oh yeah! Our `input_num` has the type `Option<uint>`, rather than `uint`. We
2053 need to unwrap the Option. If you remember from before, `match` is a great way
2054 to do that. Try this code:
2055
2056 ```{rust,no_run}
2057 use std::io;
2058 use std::rand;
2059
2060 fn main() {
2061     println!("Guess the number!");
2062
2063     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2064
2065     println!("The secret number is: {}", secret_number);
2066
2067     println!("Please input your guess.");
2068
2069     let input = io::stdin().read_line()
2070                            .ok()
2071                            .expect("Failed to read line");
2072     let input_num: Option<uint> = from_str(input.as_slice());
2073
2074     let num = match input_num {
2075         Some(num) => num,
2076         None      => {
2077             println!("Please input a number!");
2078             return;
2079         }
2080     };
2081
2082
2083     println!("You guessed: {}", num);
2084
2085     match cmp(num, secret_number) {
2086         Less    => println!("Too small!"),
2087         Greater => println!("Too big!"),
2088         Equal   => { println!("You win!"); },
2089     }
2090 }
2091
2092 fn cmp(a: uint, b: uint) -> Ordering {
2093     if a < b { Less }
2094     else if a > b { Greater }
2095     else { Equal }
2096 }
2097 ```
2098
2099 We use a `match` to either give us the `uint` inside of the `Option`, or we
2100 print an error message and return. Let's give this a shot:
2101
2102 ```{notrust,ignore}
2103 $ cargo build
2104    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
2105 $ ./target/guessing_game 
2106 Guess the number!
2107 The secret number is: 17
2108 Please input your guess.
2109 5
2110 Please input a number!
2111 $
2112 ```
2113
2114 Uh, what? But we did!
2115
2116 ... actually, we didn't. See, when you get a line of input from `stdin()`,
2117 you get all the input. Including the `\n` character from you pressing Enter.
2118 So, `from_str()` sees the string `"5\n"` and says "nope, that's not a number,
2119 there's non-number stuff in there!" Luckily for us, `&str`s have an easy
2120 method we can use defined on them: `trim()`. One small modification, and our
2121 code looks like this:
2122
2123 ```{rust,no_run}
2124 use std::io;
2125 use std::rand;
2126
2127 fn main() {
2128     println!("Guess the number!");
2129
2130     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2131
2132     println!("The secret number is: {}", secret_number);
2133
2134     println!("Please input your guess.");
2135
2136     let input = io::stdin().read_line()
2137                            .ok()
2138                            .expect("Failed to read line");
2139     let input_num: Option<uint> = from_str(input.as_slice().trim());
2140
2141     let num = match input_num {
2142         Some(num) => num,
2143         None      => {
2144             println!("Please input a number!");
2145             return;
2146         }
2147     };
2148
2149
2150     println!("You guessed: {}", num);
2151
2152     match cmp(num, secret_number) {
2153         Less    => println!("Too small!"),
2154         Greater => println!("Too big!"),
2155         Equal   => { println!("You win!"); },
2156     }
2157 }
2158
2159 fn cmp(a: uint, b: uint) -> Ordering {
2160     if a < b { Less }
2161     else if a > b { Greater }
2162     else { Equal }
2163 }
2164 ```
2165
2166 Let's try it!
2167
2168 ```{notrust,ignore}
2169 $ cargo build
2170    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
2171 $ ./target/guessing_game 
2172 Guess the number!
2173 The secret number is: 58
2174 Please input your guess.
2175   76  
2176 You guessed: 76
2177 Too big!
2178 $
2179 ```
2180
2181 Nice! You can see I even added spaces before my guess, and it still figured
2182 out that I guessed 76. Run the program a few times, and verify that guessing
2183 the number works, as well as guessing a number too small.
2184
2185 The Rust compiler helped us out quite a bit there! This technique is called
2186 "lean on the compiler," and it's often useful when working on some code. Let
2187 the error messages help guide you towards the correct types.
2188
2189 Now we've got most of the game working, but we can only make one guess. Let's
2190 change that by adding loops!
2191
2192 ## Looping
2193
2194 As we already discussed, the `loop` key word gives us an infinite loop. So
2195 let's add that in:
2196
2197 ```{rust,no_run}
2198 use std::io;
2199 use std::rand;
2200
2201 fn main() {
2202     println!("Guess the number!");
2203
2204     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2205
2206     println!("The secret number is: {}", secret_number);
2207
2208     loop {
2209
2210         println!("Please input your guess.");
2211
2212         let input = io::stdin().read_line()
2213                                .ok()
2214                                .expect("Failed to read line");
2215         let input_num: Option<uint> = from_str(input.as_slice().trim());
2216
2217         let num = match input_num {
2218             Some(num) => num,
2219             None      => {
2220                 println!("Please input a number!");
2221                 return;
2222             }
2223         };
2224
2225
2226         println!("You guessed: {}", num);
2227
2228         match cmp(num, secret_number) {
2229             Less    => println!("Too small!"),
2230             Greater => println!("Too big!"),
2231             Equal   => { println!("You win!"); },
2232         }
2233     }
2234 }
2235
2236 fn cmp(a: uint, b: uint) -> Ordering {
2237     if a < b { Less }
2238     else if a > b { Greater }
2239     else { Equal }
2240 }
2241 ```
2242
2243 And try it out. But wait, didn't we just add an infinite loop? Yup. Remember
2244 that `return`? If we give a non-number answer, we'll `return` and quit. Observe:
2245
2246 ```{notrust,ignore}
2247 $ cargo build
2248    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
2249 steve@computer:~/tmp/guessing_game$ ./target/guessing_game 
2250 Guess the number!
2251 The secret number is: 59
2252 Please input your guess.
2253 45
2254 You guessed: 45
2255 Too small!
2256 Please input your guess.
2257 60
2258 You guessed: 60
2259 Too big!
2260 Please input your guess.
2261 59
2262 You guessed: 59
2263 You win!
2264 Please input your guess.
2265 quit
2266 Please input a number!
2267 $
2268 ```
2269
2270 Ha! `quit` actually quits. As does any other non-number input. Well, this is
2271 suboptimal to say the least. First, let's actually quit when you win the game:
2272
2273 ```{rust,no_run}
2274 use std::io;
2275 use std::rand;
2276
2277 fn main() {
2278     println!("Guess the number!");
2279
2280     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2281
2282     println!("The secret number is: {}", secret_number);
2283
2284     loop {
2285
2286         println!("Please input your guess.");
2287
2288         let input = io::stdin().read_line()
2289                                .ok()
2290                                .expect("Failed to read line");
2291         let input_num: Option<uint> = from_str(input.as_slice().trim());
2292
2293         let num = match input_num {
2294             Some(num) => num,
2295             None      => {
2296                 println!("Please input a number!");
2297                 return;
2298             }
2299         };
2300
2301
2302         println!("You guessed: {}", num);
2303
2304         match cmp(num, secret_number) {
2305             Less    => println!("Too small!"),
2306             Greater => println!("Too big!"),
2307             Equal   => {
2308                 println!("You win!");
2309                 return;
2310             },
2311         }
2312     }
2313 }
2314
2315 fn cmp(a: uint, b: uint) -> Ordering {
2316     if a < b { Less }
2317     else if a > b { Greater }
2318     else { Equal }
2319 }
2320 ```
2321
2322 By adding the `return` line after the `You win!`, we'll exit the program when
2323 we win. We have just one more tweak to make: when someone inputs a non-number,
2324 we don't want to quit, we just want to ignore it. Change that `return` to
2325 `continue`:
2326
2327
2328 ```{rust,no_run}
2329 use std::io;
2330 use std::rand;
2331
2332 fn main() {
2333     println!("Guess the number!");
2334
2335     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2336
2337     println!("The secret number is: {}", secret_number);
2338
2339     loop {
2340
2341         println!("Please input your guess.");
2342
2343         let input = io::stdin().read_line()
2344                                .ok()
2345                                .expect("Failed to read line");
2346         let input_num: Option<uint> = from_str(input.as_slice().trim());
2347
2348         let num = match input_num {
2349             Some(num) => num,
2350             None      => {
2351                 println!("Please input a number!");
2352                 continue;
2353             }
2354         };
2355
2356
2357         println!("You guessed: {}", num);
2358
2359         match cmp(num, secret_number) {
2360             Less    => println!("Too small!"),
2361             Greater => println!("Too big!"),
2362             Equal   => {
2363                 println!("You win!");
2364                 return;
2365             },
2366         }
2367     }
2368 }
2369
2370 fn cmp(a: uint, b: uint) -> Ordering {
2371     if a < b { Less }
2372     else if a > b { Greater }
2373     else { Equal }
2374 }
2375 ```
2376
2377 Now we should be good! Let's try:
2378
2379 ```{rust,ignore}
2380 $ cargo build
2381    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
2382 $ ./target/guessing_game 
2383 Guess the number!
2384 The secret number is: 61
2385 Please input your guess.
2386 10
2387 You guessed: 10
2388 Too small!
2389 Please input your guess.
2390 99
2391 You guessed: 99
2392 Too big!
2393 Please input your guess.
2394 foo
2395 Please input a number!
2396 Please input your guess.
2397 61
2398 You guessed: 61
2399 You win!
2400 ```
2401
2402 Awesome! With one tiny last tweak, we have finished the guessing game. Can you
2403 think of what it is? That's right, we don't want to print out the secret number.
2404 It was good for testing, but it kind of ruins the game. Here's our final source:
2405
2406 ```{rust,no_run}
2407 use std::io;
2408 use std::rand;
2409
2410 fn main() {
2411     println!("Guess the number!");
2412
2413     let secret_number = (rand::random::<uint>() % 100u) + 1u;
2414
2415     loop {
2416
2417         println!("Please input your guess.");
2418
2419         let input = io::stdin().read_line()
2420                                .ok()
2421                                .expect("Failed to read line");
2422         let input_num: Option<uint> = from_str(input.as_slice().trim());
2423
2424         let num = match input_num {
2425             Some(num) => num,
2426             None      => {
2427                 println!("Please input a number!");
2428                 continue;
2429             }
2430         };
2431
2432
2433         println!("You guessed: {}", num);
2434
2435         match cmp(num, secret_number) {
2436             Less    => println!("Too small!"),
2437             Greater => println!("Too big!"),
2438             Equal   => {
2439                 println!("You win!");
2440                 return;
2441             },
2442         }
2443     }
2444 }
2445
2446 fn cmp(a: uint, b: uint) -> Ordering {
2447     if a < b { Less }
2448     else if a > b { Greater }
2449     else { Equal }
2450 }
2451 ```
2452
2453 ## Complete!
2454
2455 At this point, you have successfully built the Guessing Game! Congratulations!
2456
2457 You've now learned the basic syntax of Rust. All of this is relatively close to
2458 various other programming languages you have used in the past. These
2459 fundamental syntactical and semantic elements will form the foundation for the
2460 rest of your Rust education.
2461
2462 Now that you're an expert at the basics, it's time to learn about some of
2463 Rust's more unique features.
2464
2465 # iterators
2466
2467 # Lambdas
2468
2469 # Testing
2470
2471 attributes
2472
2473 stability markers
2474
2475 # Crates and Modules
2476
2477 visibility
2478
2479
2480 # Generics
2481
2482 # Traits
2483
2484 # Operators and built-in Traits
2485
2486 # Ownership and Lifetimes
2487
2488 Move vs. Copy
2489
2490 Allocation
2491
2492 # Tasks
2493
2494 # Macros
2495
2496 # Unsafe
2497