]> git.lizzy.rs Git - rust.git/blob - src/doc/guide.md
auto merge of #15691 : jbclements/rust/method-field-cleanup, r=alexcrichton
[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." Then, we'll show off
22 Rust's features by writing a little program together.
23
24 Sound good? Let's go!
25
26 ## Installing Rust
27
28 The first step to using Rust is to install it! There are a number of ways to
29 install Rust, but the easiest is to use the the `rustup` script. If you're on
30 Linux or a Mac, all you need to do is this (note that you don't need to type
31 in the `$`s, they just indicate the start of each command):
32
33 ```{ignore}
34 $ curl -s http://www.rust-lang.org/rustup.sh | sudo sh
35 ```
36
37 (If you're concerned about `curl | sudo sh`, please keep reading. Disclaimer
38 below.)
39
40 If you're on Windows, please [download this .exe and run
41 it](http://static.rust-lang.org/dist/rust-nightly-install.exe).
42
43 If you decide you don't want Rust anymore, we'll be a bit sad, but that's okay.
44 Not every programming language is great for everyone. Just pass an argument to
45 the script:
46
47 ```{ignore}
48 $ curl -s http://www.rust-lang.org/rustup.sh | sudo sh -s -- --uninstall
49 ```
50
51 If you used the Windows installer, just re-run the `.exe` and it will give you
52 an uninstall option.
53
54 You can re-run this script any time you want to update Rust. Which, at this
55 point, is often. Rust is still pre-1.0, and so people assume that you're using
56 a very recent Rust.
57
58 This brings me to one other point: some people, and somewhat rightfully so, get
59 very upset when we tell you to `curl | sudo sh`. And they should be! Basically,
60 when you do this, you are trusting that the good people who maintain Rust
61 aren't going to hack your computer and do bad things. That's a good instinct!
62 If you're one of those people, please check out the documentation on [building
63 Rust from Source](https://github.com/rust-lang/rust#building-from-source), or
64 [the official binary downloads](http://www.rust-lang.org/install.html). And we
65 promise that this method will not be the way to install Rust forever: it's just
66 the easiest way to keep people updated while Rust is in its alpha state.
67
68 Oh, we should also mention the officially supported platforms:
69
70 * Windows (7, 8, Server 2008 R2), x86 only
71 * Linux (2.6.18 or later, various distributions), x86 and x86-64
72 * OSX 10.7 (Lion) or greater, x86 and x86-64
73
74 We extensively test Rust on these platforms, and a few others, too, like
75 Android. But these are the ones most likely to work, as they have the most
76 testing.
77
78 Finally, a comment about Windows. Rust considers Windows to be a first-class
79 platform upon release, but if we're honest, the Windows experience isn't as
80 integrated as the Linux/OS X experience is. We're working on it! If anything
81 does not work, it is a bug. Please let us know if that happens. Each and every
82 commit is tested against Windows just like any other platform.
83
84 If you've got Rust installed, you can open up a shell, and type this:
85
86 ```{ignore}
87 $ rustc --version
88 ```
89
90 You should see some output that looks something like this:
91
92 ```{ignore}
93 rustc 0.12.0-pre (443a1cd 2014-06-08 14:56:52 -0700)
94 ```
95
96 If you did, Rust has been installed successfully! Congrats!
97
98 If not, there are a number of places where you can get help. The easiest is
99 [the #rust IRC channel on irc.mozilla.org](irc://irc.mozilla.org/#rust), which
100 you can access through
101 [Mibbit](http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust). Click
102 that link, and you'll be chatting with other Rustaceans (a silly nickname we
103 call ourselves), and we can help you out. Other great resources include [our
104 mailing list](https://mail.mozilla.org/listinfo/rust-dev), [the /r/rust
105 subreddit](http://www.reddit.com/r/rust), and [Stack
106 Overflow](http://stackoverflow.com/questions/tagged/rust).
107
108 ## Hello, world!
109
110 Now that you have Rust installed, let's write your first Rust program. It's
111 traditional to make your first program in any new language one that prints the
112 text "Hello, world!" to the screen. The nice thing about starting with such a
113 simple program is that you can verify that your compiler isn't just installed,
114 but also working properly. And printing information to the screen is a pretty
115 common thing to do.
116
117 The first thing that we need to do is make a file to put our code in. I like
118 to make a projects directory in my home directory, and keep all my projects
119 there. Rust does not care where your code lives.
120
121 This actually leads to one other concern we should address: this tutorial will
122 assume that you have basic familiarity with the command-line. Rust does not
123 require that you know a whole ton about the command line, but until the
124 language is in a more finished state, IDE support is spotty. Rust makes no
125 specific demands on your editing tooling, or where your code lives.
126
127 With that said, let's make a directory in our projects directory.
128
129 ```{bash}
130 $ mkdir ~/projects
131 $ cd ~/projects
132 $ mkdir hello_world
133 $ cd hello_world
134 ```
135
136 If you're on Windows and not using PowerShell, the `~` may not work. Consult
137 the documentation for your shell for more details.
138
139 Let's make a new source file next. I'm going to use the syntax `editor
140 filename` to represent editing a file in these examples, but you should use
141 whatever method you want. We'll call our file `hello_world.rs`:
142
143 ```{bash}
144 $ editor hello_world.rs
145 ```
146
147 Rust files always end in a `.rs` extension. If you're using more than one word
148 in your file name, use an underscore. `hello_world.rs` versus `goodbye.rs`.
149
150 Now that you've got your file open, type this in:
151
152 ```
153 fn main() {
154     println!("Hello, world");
155 }
156 ```
157
158 Save the file, and then type this into your terminal window:
159
160 ```{bash}
161 $ rustc hello_world.rs
162 $ ./hello_world # or hello_world.exe on Windows
163 Hello, world
164 ```
165
166 Success! Let's go over what just happened in detail.
167
168 ```
169 fn main() {
170
171 }
172 ```
173
174 These two lines define a **function** in Rust. The `main` function is special:
175 it's the beginning of every Rust program. The first line says "I'm declaring a
176 function named `main`, which takes no arguments and returns nothing." If there
177 were arguments, they would go inside the parentheses (`(` and `)`), and because
178 we aren't returning anything from this function, we've dropped that notation
179 entirely.  We'll get to it later.
180
181 You'll also note that the function is wrapped in curly braces (`{` and `}`).
182 Rust requires these around all function bodies. It is also considered good
183 style to put the opening curly brace on the same line as the function
184 declaration, with one space in between.
185
186 Next up is this line:
187
188 ```
189     println!("Hello, world");
190 ```
191
192 This line does all of the work in our little program. There are a number of
193 details that are important here. The first is that it's indented with four
194 spaces, not tabs. Please configure your editor of choice to insert four spaces
195 with the tab key. We provide some sample configurations for various editors
196 [here](https://github.com/rust-lang/rust/tree/master/src/etc).
197
198 The second point is the `println!()` part. This is calling a Rust **macro**,
199 which is how metaprogramming is done in Rust. If it were a function instead, it
200 would look like this: `println()`. For our purposes, we don't need to worry
201 about this difference. Just know that sometimes, you'll see a `!`, and that
202 means that you're calling a macro instead of a normal function. One last thing
203 to mention: Rust's macros are significantly different than C macros, if you've
204 used those. Don't be scared of using macros. We'll get to the details
205 eventually, you'll just have to trust us for now.
206
207 Next, `"Hello, world"` is a **string**. Strings are a surprisingly complicated
208 topic in a systems programming language, and this is a **statically allocated**
209 string. We will talk more about different kinds of allocation later. We pass
210 this string as an argument to `println!`, which prints the string to the
211 screen. Easy enough!
212
213 Finally, the line ends with a semicolon (`;`). Rust is an **expression
214 oriented** language, which means that most things are expressions. The `;` is
215 used to indicate that this expression is over, and the next one is ready to
216 begin. Most lines of Rust code end with a `;`. We will cover this in-depth
217 later in the tutorial.
218
219 Finally, actually **compiling** and **running** our program. We can compile
220 with our compiler, `rustc`, by passing it the name of our source file:
221
222 ```{bash}
223 $ rustc hello_world.rs
224 ```
225
226 This is similar to `gcc` or `clang`, if you come from a C or C++ background. Rust
227 will output a binary executable. You can see it with `ls`:
228
229 ```{bash}
230 $ ls
231 hello_world  hello_world.rs
232 ```
233
234 Or on Windows:
235
236 ```{bash}
237 $ dir
238 hello_world.exe  hello_world.rs
239 ```
240
241 There are now two files: our source code, with the `.rs` extension, and the
242 executable (`hello_world.exe` on Windows, `hello_world` everywhere else)
243
244 ```{bash}
245 $ ./hello_world  # or hello_world.exe on Windows
246 ```
247
248 This prints out our `Hello, world!` text to our terminal.
249
250 If you come from a dynamically typed language like Ruby, Python, or JavaScript,
251 you may not be used to these two steps being separate. Rust is an
252 **ahead-of-time compiled language**, which means that you can compile a
253 program, give it to someone else, and they don't need to have Rust installed.
254 If you give someone a `.rb` or `.py` or `.js` file, they need to have
255 Ruby/Python/JavaScript installed, but you just need one command to both compile
256 and run your program. Everything is a tradeoff in language design, and Rust has
257 made its choice.
258
259 Congratulations! You have officially written a Rust program. That makes you a
260 Rust programmer! Welcome.
261
262 Next, I'd like to introduce you to another tool, Cargo, which is used to write
263 real-world Rust programs. Just using `rustc` is nice for simple things, but as
264 your project grows, you'll want something to help you manage all of the options
265 that it has, and to make it easy to share your code with other people and
266 projects.
267
268 ## Hello, Cargo!
269
270 [Cargo](http://crates.io) is a tool that Rustaceans use to help manage their
271 Rust projects. Cargo is currently in an alpha state, just like Rust, and so it
272 is still a work in progress. However, it is already good enough to use for many
273 Rust projects, and so it is assumed that Rust projects will use Cargo from the
274 beginning.
275
276 Cargo manages three things: building your code, downloading the dependencies
277 your code needs, and building the dependencies your code needs.  At first, your
278 program doesn't have any dependencies, so we'll only be using the first part of
279 its functionality. Eventually, we'll add more. Since we started off by using
280 Cargo, it'll be easy to add later.
281
282 Let's convert Hello World to Cargo. The first thing we need to do to begin using Cargo
283 is to install Cargo. To do this, we need to build it from source. There are no binaries
284 yet.
285
286 First, let's go back to our projects directory. We don't want Cargo to
287 live in our project!
288
289 ```{bash}
290 $ cd ..
291 ```
292
293 Next, we need these commands:
294
295 ```{bash}
296 $ git clone --recursive https://github.com/rust-lang/cargo
297 $ cd cargo
298 $ make
299 $ make install # may need sudo or admin permissions
300 ```
301
302 The `--recursive` downloads Cargo's own dependencies. You can't use Cargo to
303 fetch dependencies until you have Cargo installed! Also, you will need to have
304 `git` installed. Much of the Rust world assumes `git` usage, so it's a good
305 thing to have around. Please check out [the git
306 documentation](http://git-scm.com/book/en/Getting-Started-Installing-Git) for
307 more on installing `git`.
308
309 We hope to give Cargo a binary installer, similar to Rust's own, so that
310 this will not be necessary in the future.
311
312 Let's see if that worked. Try this:
313
314 ```{bash}
315 $ cargo
316 Commands:
317   build          # compile the current project
318
319 Options (for all commands):
320
321 -v, [--verbose]
322 -h, [--help]
323 ```
324
325 If you see this output when you run `cargo`, congrats! Cargo is working. If
326 not, please [open an issue](https://github.com/rust-lang/cargo/issues/new) or
327 drop by the Rust IRC, and we can help you out.
328
329 Let's move back into our `hello_world` directory now:
330
331 ```{bash}
332 $ cd ..              # move back up into projects
333 $ cd hello_world     # move into hello_world
334 ```
335
336 To Cargo-ify our project, we need to do two things: Make a `Cargo.toml`
337 configuration file, and put our source file in the right place. Let's
338 do that part first:
339
340 ```{bash}
341 $ mkdir src
342 $ mv hello_world.rs src/hello_world.rs
343 ```
344
345 Cargo expects your source files to live inside a `src` directory. That leaves
346 the top level for other things, like READMEs, licence information, and anything
347 not related to your code. Cargo helps us keep our projects nice and tidy. A
348 place for everything, and everything in its place.
349
350 Next, our configuration file:
351
352 ```{bash}
353 $ editor Cargo.toml
354 ```
355
356 Make sure to get this name right: you need the capital `C`!
357
358 Put this inside:
359
360 ```{ignore}
361 [package]
362
363 name = "hello_world"
364 version = "0.1.0"
365 authors = [ "someone@example.com" ]
366
367 [[bin]]
368
369 name = "hello_world"
370 ```
371
372 This file is in the [TOML](https://github.com/toml-lang/toml) format. Let's let
373 it explain itself to you:
374
375 > TOML aims to be a minimal configuration file format that's easy to read due
376 > to obvious semantics. TOML is designed to map unambiguously to a hash table.
377 > TOML should be easy to parse into data structures in a wide variety of
378 > languages.
379
380 TOML is very similar to INI, but with some extra goodies.
381
382 Anyway, there are two **table**s in this file: `package` and `bin`. The first
383 tells Cargo metadata about your package. The second tells Cargo that we're
384 interested in building a binary, not a library (though we could do both!), as
385 well as what it is named.
386
387 Once you have this file in place, we should be ready to build! Try this:
388
389 ```{bash}
390 $ cargo build
391    Compiling hello_world v0.1.0 (file:/home/yourname/projects/hello_world)
392 $ ./target/hello_world
393 Hello, world!
394 ```
395
396 Bam! We build our project with `cargo build`, and run it with
397 `./target/hello_world`. This hasn't bought us a whole lot over our simple use
398 of `rustc`, but think about the future: when our project has more than one
399 file, we would need to call `rustc` twice, and pass it a bunch of options to
400 tell it to build everything together. With Cargo, as our project grows, we can
401 just `cargo build` and it'll work the right way.
402
403 That's it! We've successfully built `hello_world` with Cargo. Even though our
404 program is simple, it's using much of the real tooling that you'll use for the
405 rest of your Rust career.
406
407 Next, we'll learn more about Rust itself, by starting to write a more complicated
408 program. We hope you want to do more with Rust than just print "Hello, world!"
409
410 ## Guessing Game
411
412 Let's write a bigger program in Rust. We could just go through a laundry list
413 of Rust features, but that's boring. Instead, we'll learn more about how to
414 code in Rust by writing a few example projects.
415
416 For our first project, we'll implement a classic beginner programming problem:
417 the guessing game. Here's how it works: Our program will generate a random
418 integer between one and a hundred. It will then prompt us to enter a guess.
419 Upon entering our guess, it will tell us if we're too low or too high. Once we
420 guess correctly, it will congratulate us, and print the number of guesses we've
421 taken to the screen. Sound good? It sounds easy, but it'll end up showing off a
422 number of basic features of Rust.
423
424 ### Set up
425
426 Let's set up a new project. Go to your projects directory, and make a new
427 directory for the project, as well as a `src` directory for our code:
428
429 ```{bash}
430 $ cd ~/projects
431 $ mkdir guessing_game
432 $ cd guessing_game
433 $ mkdir src
434 ```
435
436 Great. Next, let's make a `Cargo.toml` file so Cargo knows how to build our
437 project:
438
439 ```{ignore}
440 [package]
441
442 name = "guessing_game"
443 version = "0.1.0"
444 authors = [ "someone@example.com" ]
445
446 [[bin]]
447
448 name = "guessing_game"
449 ```
450
451 Finally, we need our source file. Let's just make it hello world for now, so we
452 can check that our setup works. In `src/guessing_game.rs`:
453
454 ```{rust}
455 fn main() {
456     println!("Hello world!");
457 }
458 ```
459
460 Let's make sure that worked:
461
462 ```{bash}
463 $ cargo build
464    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
465 $
466 ```
467
468 Excellent! Open up your `src/guessing_game.rs` again. We'll be writing all of
469 our code in this file. The next section of the tutorial will show you how to
470 build multiple-file projects.
471
472 ## Variable bindings
473
474 The first thing we'll learn about are 'variable bindings.' They look like this:
475
476 ```{rust}
477 let x = 5i;
478 ```
479
480 In many languages, this is called a 'variable.' But Rust's variable bindings
481 have a few tricks up their sleeves. Rust has a very powerful feature called
482 'pattern matching' that we'll get into detail with later, but the left
483 hand side of a `let` expression is a full pattern, not just a variable name.
484 This means we can do things like:
485
486 ```{rust}
487 let (x, y) = (1i, 2i);
488 ```
489
490 After this expression is evaluated, `x` will be one, and `y` will be two.
491 Patterns are really powerful, but this is about all we can do with them so far.
492 So let's just keep this in the back of our minds as we go forward.
493
494 By the way, in these examples, `i` indicates that the number is an integer.
495
496 Rust is a statically typed language, which means that we specify our types up
497 front. So why does our first example compile? Well, Rust has this thing called
498 "[Hindley-Milner type
499 inference](http://en.wikipedia.org/wiki/Hindley%E2%80%93Milner_type_system)",
500 named after some really smart type theorists. If you clicked that link, don't
501 be scared: what this means for you is that Rust will attempt to infer the types
502 in your program, and it's pretty good at it. If it can infer the type, Rust
503 doesn't require you to actually type it out.
504
505 We can add the type if we want to. Types come after a colon (`:`):
506
507 ```{rust}
508 let x: int = 5;
509 ```
510
511 If I asked you to read this out loud to the rest of the class, you'd say "`x`
512 is a binding with the type `int` and the value `five`."
513
514 By default, bindings are **immutable**. This code will not compile:
515
516 ```{ignore}
517 let x = 5i;
518 x = 10i;
519 ```
520
521 It will give you this error:
522
523 ```{ignore,notrust}
524 error: re-assignment of immutable variable `x`
525      x = 10i;
526      ^~~~~~~
527 ```
528
529 If you want a binding to be mutable, you can use `mut`:
530
531 ```{rust}
532 let mut x = 5i;
533 x = 10i;
534 ```
535
536 There is no single reason that bindings are immutable by default, but we can
537 think about it through one of Rust's primary focuses: safety. If you forget to
538 say `mut`, the compiler will catch it, and let you know that you have mutated
539 something you may not have cared to mutate. If bindings were mutable by
540 default, the compiler would not be able to tell you this. If you _did_ intend
541 mutation, then the solution is quite easy: add `mut`.
542
543 There are other good reasons to avoid mutable state when possible, but they're
544 out of the scope of this guide. In general, you can often avoid explicit
545 mutation, and so it is preferable in Rust. That said, sometimes, mutation is
546 what you need, so it's not verboten.
547
548 Let's get back to bindings. Rust variable bindings have one more aspect that
549 differs from other languages: bindings are required to be initialized with a
550 value before you're allowed to use it. If we try...
551
552 ```{ignore}
553 let x;
554 ```
555
556 ...we'll get an error:
557
558 ```{ignore}
559 src/guessing_game.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type
560 src/guessing_game.rs:2     let x;
561                                ^
562 ```
563
564 Giving it a type will compile, though:
565
566 ```{ignore}
567 let x: int;
568 ```
569
570 Let's try it out. Change your `src/guessing_game.rs` file to look like this:
571
572 ```{rust}
573 fn main() {
574     let x: int;
575
576     println!("Hello world!");
577 }
578 ```
579
580 You can use `cargo build` on the command line to build it. You'll get a warning,
581 but it will still print "Hello, world!":
582
583 ```{ignore,notrust}
584    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
585 src/guessing_game.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
586 src/guessing_game.rs:2     let x: int;
587                                ^
588 ```
589
590 Rust warns us that we never use the variable binding, but since we never use it,
591 no harm, no foul. Things change if we try to actually use this `x`, however. Let's
592 do that. Change your program to look like this:
593
594 ```{rust,ignore}
595 fn main() {
596     let x: int;
597
598     println!("The value of x is: {}", x);
599 }
600 ```
601
602 And try to build it. You'll get an error:
603
604 ```{bash}
605 $ cargo build
606    Compiling guessing_game v0.1.0 (file:/home/you/projects/guessing_game)
607 src/guessing_game.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
608 src/guessing_game.rs:4     println!("The value of x is: {}", x);
609                                                              ^
610 note: in expansion of format_args!
611 <std macros>:2:23: 2:77 note: expansion site
612 <std macros>:1:1: 3:2 note: in expansion of println!
613 src/guessing_game.rs:4:5: 4:42 note: expansion site
614 error: aborting due to previous error
615 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)
616 ```
617
618 Rust will not let us use a value that has not been initialized. So why let us
619 declare a binding without initializing it? You'd think our first example would
620 have errored. Well, Rust is smarter than that. Before we get to that, let's talk
621 about this stuff we've added to `println!`.
622
623 If you include two curly braces (`{}`, some call them moustaches...) in your
624 string to print, Rust will interpret this as a request to interpolate some sort
625 of value. **String interpolation** is a computer science term that means "stick
626 in the middle of a string." We add a comma, and then `x`, to indicate that we
627 want `x` to be the value we're interpolating. The comma is used to separate
628 arguments we pass to functions and macros, if you're passing more than one.
629
630 When you just use the double curly braces, Rust will attempt to display the
631 value in a meaningful way by checking out its type. If you want to specify the
632 format in a more detailed manner, there are a [wide number of options
633 available](/std/fmt/index.html). Fow now, we'll just stick to the default:
634 integers aren't very complicated to print.
635
636 So, we've cleared up all of the confusion around bindings, with one exception:
637 why does Rust let us declare a variable binding without an initial value if we
638 must initialize the binding before we use it? And how does it know that we have
639 or have not initialized the binding? For that, we need to learn our next
640 concept: `if`.
641
642 ## If
643
644 Rust's take on `if` is not particularly complex, but it's much more like the
645 `if` you'll find in a dynamically typed language than in a more traditional
646 systems language. So let's talk about it, to make sure you grasp the nuances.
647
648 `if` is a specific form of a more general concept, the 'branch.' The name comes
649 from a branch in a tree: a decision point, where depending on a choice,
650 multiple paths can be taken.
651
652 In the case of `if`, there is one choice that leads down two paths:
653
654 ```rust
655 let x = 5i;
656
657 if x == 5i {
658     println!("x is five!");
659 }
660 ```
661
662 If we changed the value of `x` to something else, this line would not print.
663 More specifically, if the expression after the `if` evaluates to `true`, then
664 the block is executed. If it's `false`, then it is not.
665
666 If you want something to happen in the `false` case, use an `else`:
667
668 ```
669 let x = 5i;
670
671 if x == 5i {
672     println!("x is five!");
673 } else {
674     println!("x is not five :(");
675 }
676 ```
677
678 This is all pretty standard. However, you can also do this:
679
680
681 ```
682 let x = 5i;
683
684 let y = if x == 5i {
685     10i
686 } else {
687     15i
688 };
689 ```
690
691 Which we can (and probably should) write like this:
692
693 ```
694 let x = 5i;
695
696 let y = if x == 5i { 10i } else { 15i };
697 ```
698
699 This reveals two interesting things about Rust: it is an expression-based
700 language, and semicolons are different than in other 'curly brace and
701 semicolon'-based languages. These two things are related.
702
703 ### Expressions vs. Statements
704
705 Rust is primarily an expression based language. There are only two kinds of
706 statements, and everything else is an expression.
707
708 So what's the difference? Expressions return a value, and statements do not.
709 In many languages, `if` is a statement, and therefore, `let x = if ...` would
710 make no sense. But in Rust, `if` is an expression, which means that it returns
711 a value. We can then use this value to initialize the binding.
712
713 Speaking of which, bindings are a kind of the first of Rust's two statements.
714 The proper name is a **declaration statement**. So far, `let` is the only kind
715 of declaration statement we've seen. Let's talk about that some more.
716
717 In some languages, variable bindings can be written as expressions, not just
718 statements. Like Ruby:
719
720 ```{ruby}
721 x = y = 5
722 ```
723
724 In Rust, however, using `let` to introduce a binding is _not_ an expression. The
725 following will produce a compile-time error:
726
727 ```{ignore}
728 let x = (let y = 5i); // found `let` in ident position
729 ```
730
731 The compiler is telling us here that it was expecting to see the beginning of
732 an expression, and a `let` can only begin a statement, not an expression.
733
734 However, assigning to a variable binding is an expression:
735
736 ```{rust}
737 let x;
738 let y = x = 5i;
739 ```
740
741 In this case, we have an assignment expression (`x = 5`) whose value is
742 being used as part of a `let` declaration statement (`let y = ...`).
743
744 The second kind of statement in Rust is the **expression statement**. Its
745 purpose is to turn any expression into a statement. In practical terms, Rust's
746 grammar expects statements to follow other statements. This means that you use
747 semicolons to separate expressions from each other. This means that Rust
748 looks a lot like most other languages that require you to use semicolons
749 at the end of every line, and you will see semicolons at the end of almost
750 every line of Rust code you see.
751
752 What is this exception that makes us say 'almost?' You saw it already, in this
753 code:
754
755 ```
756 let x = 5i;
757
758 let y: int = if x == 5i { 10i } else { 15i };
759 ```
760
761 Note that I've added the type annotation to `y`, to specify explicitly that I
762 want `y` to be an integer.
763
764 This is not the same as this, which won't compile:
765
766 ```{ignore}
767 let x = 5i;
768
769 let y: int = if x == 5 { 10i; } else { 15i; };
770 ```
771
772 Note the semicolons after the 10 and 15. Rust will give us the following error:
773
774 ```{ignore,notrust}
775 error: mismatched types: expected `int` but found `()` (expected int but found ())
776 ```
777
778 We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a
779 special type in Rust's type system. `()` is different than `null` in other
780 languages, because `()` is distinct from other types. For example, in C, `null`
781 is a valid value for a variable of type `int`. In Rust, `()` is _not_ a valid
782 value for a variable of type `int`. It's only a valid value for variables of
783 the type `()`, which aren't very useful. Remember how we said statements don't
784 return a value? Well, that's the purpose of unit in this case. The semicolon
785 turns any expression into a statement by throwing away its value and returning
786 unit instead.
787
788 There's one more time in which you won't see a semicolon at the end of a line
789 of Rust code. For that, we'll need our next concept: functions.
790
791 ## Functions
792
793 You've already seen one function so far, the `main` function:
794
795 ```{rust}
796 fn main() {
797 }
798 ```
799
800 This is the simplest possible function declaration. As we mentioned before,
801 `fn` says 'this is a function,' followed by the name, some parenthesis because
802 this function takes no arguments, and then some curly braces to indicate the
803 body. Here's a function named `foo`:
804
805 ```{rust}
806 fn foo() {
807 }
808 ```
809
810 So, what about taking arguments? Here's a function that prints a number:
811
812 ```{rust}
813 fn print_number(x: int) {
814     println!("x is: {}", x);
815 }
816 ```
817
818 Here's a complete program that uses `print_number`:
819
820 ```{rust}
821 fn main() {
822     print_number(5);
823 }
824
825 fn print_number(x: int) {
826     println!("x is: {}", x);
827 }
828 ```
829
830 As you can see, function arguments work very similar to `let` declarations:
831 you add a type to the argument name, after a colon.
832
833 Here's a complete program that adds two numbers together and prints them:
834
835 ```{rust}
836 fn main() {
837     print_sum(5, 6);
838 }
839
840 fn print_sum(x: int, y: int) {
841     println!("sum is: {}", x + y);
842 }
843 ```
844
845 You separate arguments with a comma, both when you call the function, as well
846 as when you declare it.
847
848 Unlike `let`, you _must_ declare the types of function arguments. This does
849 not work:
850
851 ```{ignore}
852 fn print_number(x, y) {
853     println!("x is: {}", x + y);
854 }
855 ```
856
857 You get this error:
858
859 ```{ignore,notrust}
860 hello.rs:5:18: 5:19 error: expected `:` but found `,`
861 hello.rs:5 fn print_number(x, y) {
862 ```
863
864 This is a deliberate design decision. While full-program inference is possible,
865 languages which have it, like Haskell, often suggest that documenting your
866 types explicitly is a best-practice. We agree that forcing functions to declare
867 types while allowing for inference inside of function bodies is a wonderful
868 compromise between full inference and no inference.
869
870 What about returning a value? Here's a function that adds one to an integer:
871
872 ```{rust}
873 fn add_one(x: int) -> int {
874     x + 1
875 }
876 ```
877
878 Rust functions return exactly one value, and you declare the type after an
879 'arrow', which is a dash (`-`) followed by a greater-than sign (`>`).
880
881 You'll note the lack of a semicolon here. If we added it in:
882
883 ```{ignore}
884 fn add_one(x: int) -> int {
885     x + 1;
886 }
887 ```
888
889 We would get an error:
890
891 ```{ignore,notrust}
892 error: not all control paths return a value
893 fn add_one(x: int) -> int {
894      x + 1;
895 }
896
897 note: consider removing this semicolon:
898      x + 1;
899           ^
900 ```
901
902 Remember our earlier discussions about semicolons and `()`? Our function claims
903 to return an `int`, but with a semicolon, it would return `()` instead. Rust
904 realizes this probably isn't what we want, and suggests removing the semicolon.
905
906 This is very much like our `if` statement before: the result of the block
907 (`{}`) is the value of the expression. Other expression-oriented languages,
908 such as Ruby, work like this, but it's a bit unusual in the systems programming
909 world. When people first learn about this, they usually assume that it
910 introduces bugs. But because Rust's type system is so strong, and because unit
911 is its own unique type, we have never seen an issue where adding or removing a
912 semicolon in a return position would cause a bug.
913
914 But what about early returns? Rust does have a keyword for that, `return`:
915
916 ```{rust}
917 fn foo(x: int) -> int {
918     if x < 5 { return x; }
919
920     x + 1
921 }
922 ```
923
924 Using a `return` as the last line of a function works, but is considered poor
925 style:
926
927 ```{rust}
928 fn foo(x: int) -> int {
929     if x < 5 { return x; }
930
931     return x + 1;
932 }
933 ```
934
935 There are some additional ways to define functions, but they involve features
936 that we haven't learned about yet, so let's just leave it at that for now.
937
938
939 ## Comments
940
941 Now that we have some functions, it's a good idea to learn about comments.
942 Comments are notes that you leave to other programmers to help explain things
943 about your code. The compiler mostly ignores them.
944
945 Rust has two kinds of comments that you should care about: **line comment**s
946 and **doc comment**s.
947
948 ```{rust}
949 // Line comments are anything after '//' and extend to the end of the line.
950
951 let x = 5i; // this is also a line comment.
952
953 // If you have a long explanation for something, you can put line comments next
954 // to each other. Put a space between the // and your comment so that it's
955 // more readable.
956 ```
957
958 The other kind of comment is a doc comment. Doc comments use `///` instead of
959 `//`, and support Markdown notation inside:
960
961 ```{rust}
962 /// `hello` is a function that prints a greeting that is personalized based on
963 /// the name given.
964 ///
965 /// # Arguments
966 ///
967 /// * `name` - The name of the person you'd like to greet.
968 ///
969 /// # Example
970 ///
971 /// ```rust
972 /// let name = "Steve";
973 /// hello(name); // prints "Hello, Steve!"
974 /// ```
975 fn hello(name: &str) {
976     println!("Hello, {}!", name);
977 }
978 ```
979
980 When writing doc comments, adding sections for any arguments, return values,
981 and providing some examples of usage is very, very helpful.
982
983 You can use the `rustdoc` tool to generate HTML documentation from these doc
984 comments. We will talk more about `rustdoc` when we get to modules, as
985 generally, you want to export documentation for a full module.
986
987 ## Compound Data Types
988
989 Rust, like many programming languages, has a number of different data types
990 that are built-in. You've already done some simple work with integers and
991 strings, but next, let's talk about some more complicated ways of storing data.
992
993 ### Tuples
994
995 The first compound data type we're going to talk about are called **tuple**s.
996 Tuples are an ordered list of a fixed size. Like this:
997
998 ```rust
999 let x = (1i, "hello");
1000 ```
1001
1002 The parenthesis and commas form this two-length tuple. Here's the same code, but
1003 with the type annotated:
1004
1005 ```rust
1006 let x: (int, &str) = (1, "hello");
1007 ```
1008
1009 As you can see, the type of a tuple looks just like the tuple, but with each
1010 position having a type name rather than the value. Careful readers will also
1011 note that tuples are heterogeneous: we have an `int` and a `&str` in this tuple.
1012 You haven't seen `&str` as a type before, and we'll discuss the details of
1013 strings later. In systems programming languages, strings are a bit more complex
1014 than in other languages. For now, just read `&str` as "a string slice," and
1015 we'll learn more soon.
1016
1017 You can access the fields in a tuple through a **destructuring let**. Here's
1018 an example:
1019
1020 ```rust
1021 let (x, y, z) = (1i, 2i, 3i);
1022
1023 println!("x is {}", x);
1024 ```
1025
1026 Remember before when I said the left hand side of a `let` statement was more
1027 powerful than just assigning a binding? Here we are. We can put a pattern on
1028 the left hand side of the `let`, and if it matches up to the right hand side,
1029 we can assign multiple bindings at once. In this case, `let` 'destructures,'
1030 or 'breaks up,' the tuple, and assigns the bits to three bindings.
1031
1032 This pattern is very powerful, and we'll see it repeated more later.
1033
1034 The last thing to say about tuples is that they are only equivalent if
1035 the arity, types, and values are all identical.
1036
1037 ```rust
1038 let x = (1i, 2i, 3i);
1039 let y = (2i, 3i, 4i);
1040
1041 if x == y {
1042     println!("yes");
1043 } else {
1044     println!("no");
1045 }
1046 ```
1047
1048 This will print `no`, as the values aren't equal.
1049
1050 One other use of tuples is to return multiple values from a function:
1051
1052 ```rust
1053 fn next_two(x: int) -> (int, int) { (x + 1i, x + 2i) }
1054
1055 fn main() {
1056     let (x, y) = next_two(5i);
1057     println!("x, y = {}, {}", x, y);
1058 }
1059 ```
1060
1061 Even though Rust functions can only return one value, a tuple _is_ one value,
1062 that happens to be made up of two. You can also see in this example how you
1063 can destructure a pattern returned by a function, as well.
1064
1065 Tuples are a very simple data structure, and so are not often what you want.
1066 Let's move on to their bigger sibling, structs.
1067
1068 ### Structs
1069
1070 A struct is another form of a 'record type,' just like a tuple. There's a
1071 difference: structs give each element that they contain a name, called a
1072 'field' or a 'member.' Check it out:
1073
1074 ```rust
1075 struct Point {
1076     x: int,
1077     y: int,
1078 }
1079
1080 fn main() {
1081     let origin = Point { x: 0i, y:  0i };
1082
1083     println!("The origin is at ({}, {})", origin.x, origin.y);
1084 }
1085 ```
1086
1087 There's a lot going on here, so let's break it down. We declare a struct with
1088 the `struct` keyword, and then with a name. By convention, structs begin with a
1089 capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`.
1090
1091 We can create an instance of our struct via `let`, as usual, but we use a `key:
1092 value` style syntax to set each field. The order doesn't need to be the same as
1093 in the original declaration.
1094
1095 Finally, because fields have names, we can access the field through dot
1096 notation: `origin.x`.
1097
1098 The values in structs are immutable, like other bindings in Rust. However, you
1099 can use `mut` to make them mutable:
1100
1101 ```rust
1102 struct Point {
1103     x: int,
1104     y: int,
1105 }
1106
1107 fn main() {
1108     let mut point = Point { x: 0i, y:  0i };
1109
1110     point.x = 5;
1111
1112     println!("The point is at ({}, {})", point.x, point.y);
1113 }
1114 ```
1115
1116 This will print `The point is at (5, 0)`.
1117
1118 ### Tuple Structs and Newtypes
1119
1120 Rust has another data type that's like a hybrid between a tuple and a struct,
1121 called a **tuple struct**. Tuple structs do have a name, but their fields
1122 don't:
1123
1124
1125 ```
1126 struct Color(int, int, int);
1127 struct Point(int, int, int);
1128 ```
1129
1130 These two will not be equal, even if they have the same values:
1131
1132 ```{rust,ignore}
1133 let black  = Color(0, 0, 0);
1134 let origin = Point(0, 0, 0);
1135 ```
1136
1137 It is almost always better to use a struct than a tuple struct. We would write
1138 `Color` and `Point` like this instead:
1139
1140 ```rust
1141 struct Color {
1142     red: int,
1143     blue: int,
1144     green: int,
1145 }
1146
1147 struct Point {
1148     x: int,
1149     y: int,
1150     z: int,
1151 }
1152 ```
1153
1154 Now, we have actual names, rather than positions. Good names are important,
1155 and with a struct, we have actual names.
1156
1157 There _is_ one case when a tuple struct is very useful, though, and that's a
1158 tuple struct with only one element. We call this a 'newtype,' because it lets
1159 you create a new type that's a synonym for another one:
1160
1161 ```
1162 struct Inches(int);
1163 struct Centimeters(int);
1164
1165 let length = Inches(10);
1166
1167 let Inches(integer_length) = length;
1168 println!("length is {} inches", integer_length);
1169 ```
1170
1171 As you can see here, you can extract the inner integer type through a
1172 destructuring `let`.
1173
1174 ### Enums
1175
1176 Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful
1177 feature of Rust, and are used throughout the standard library. Enums look
1178 like this:
1179
1180 ```
1181 enum Ordering {
1182     Less,
1183     Equal,
1184     Greater,
1185 }
1186 ```
1187
1188 This is an enum that is provided by the Rust standard library. An `Ordering`
1189 can only be _one_ of `Less`, `Equal`, or `Greater` at any given time. Here's
1190 an example:
1191
1192 ```rust
1193 let x = 5i;
1194 let y = 10i;
1195
1196 let ordering = x.cmp(&y);
1197
1198 if ordering == Less {
1199     println!("less");
1200 } else if ordering == Greater {
1201     println!("greater");
1202 } else if ordering == Equal {
1203     println!("equal");
1204 }
1205 ```
1206
1207 `cmp` is a function that compares two things, and returns an `Ordering`. The
1208 call looks a little bit strange: rather than `cmp(x, y)`, we say `x.cmp(&y)`.
1209 We haven't covered methods and references yet, so it should look a little bit
1210 foreign. Right now, just pretend it says `cmp(x, y)`, and we'll get to those
1211 details soon.
1212
1213 The `ordering` variable has the type `Ordering`, and so contains one of the
1214 three values. We can then do a bunch of `if`/`else` comparisons to check
1215 which one it is.
1216
1217 However, repeated `if`/`else` comparisons get quite tedious. Rust has a feature
1218 that not only makes them nicer to read, but also makes sure that you never
1219 miss a case. Before we get to that, though, let's talk about another kind of
1220 enum: one with values.
1221
1222 This enum has two variants, one of which has a value.:
1223
1224 ```
1225 enum OptionalInt {
1226     Value(int),
1227     Missing
1228 }
1229
1230 fn main() {
1231     let x = Value(5);
1232     let y = Missing;
1233
1234     match x {
1235         Value(n) => println!("x is {:d}", n),
1236         Missing  => println!("x is missing!"),
1237     }
1238
1239     match y {
1240         Value(n) => println!("y is {:d}", n),
1241         Missing  => println!("y is missing!"),
1242     }
1243 }
1244 ```
1245
1246 This enum represents an `int` that we may or may not have. In the `Missing`
1247 case, we have no value, but in the `Value` case, we do. This enum is specific
1248 to `int`s, though. We can make it usable by any type, but we haven't quite
1249 gotten there yet!
1250
1251 You can have any number of values in an enum:
1252
1253 ```
1254 enum OptionalColor {
1255     Color(int, int, int),
1256     Missing
1257 }
1258 ```
1259
1260 Enums with values are quite useful, but as I mentioned, they're even more
1261 useful when they're generic across types. But before we get to generics, let's
1262 talk about how to fix this big `if`/`else` statements we've been writing. We'll
1263 do that with `match`.
1264
1265 ## Match
1266
1267 Often, a simple `if`/`else` isn't enough, because you have more than two
1268 possible options. And `else` conditions can get incredibly complicated. So
1269 what's the solution?
1270
1271 Rust has a keyword, `match`, that allows you to replace complicated `if`/`else`
1272 groupings with something more powerful. Check it out:
1273
1274 ```rust
1275 let x = 5i;
1276
1277 match x {
1278     1 => println!("one"),
1279     2 => println!("two"),
1280     3 => println!("three"),
1281     4 => println!("four"),
1282     5 => println!("five"),
1283     _ => println!("something else"),
1284 }
1285 ```
1286
1287 `match` takes an expression, and then branches based on its value. Each 'arm' of
1288 the branch is of the form `val => expression`. When the value matches, that arm's
1289 expression will be evaluated. It's called `match` because of the term 'pattern
1290 matching,' which `match` is an implementation of.
1291
1292 So what's the big advantage here? Well, there are a few. First of all, `match`
1293 does 'exhaustiveness checking.' Do you see that last arm, the one with the
1294 underscore (`_`)? If we remove that arm, Rust will give us an error:
1295
1296 ```{ignore,notrust}
1297 error: non-exhaustive patterns: `_` not covered
1298 ```
1299
1300 In other words, Rust is trying to tell us we forgot a value. Because `x` is an
1301 integer, Rust knows that it can have a number of different values. For example,
1302 `6i`. But without the `_`, there is no arm that could match, and so Rust refuses
1303 to compile. `_` is sort of like a catch-all arm. If none of the other arms match,
1304 the arm with `_` will. And since we have this catch-all arm, we now have an arm
1305 for every possible value of `x`, and so our program will now compile.
1306
1307 `match` statements also destructure enums, as well. Remember this code from the
1308 section on enums?
1309
1310 ```{rust}
1311 let x = 5i;
1312 let y = 10i;
1313
1314 let ordering = x.cmp(&y);
1315
1316 if ordering == Less {
1317     println!("less");
1318 } else if ordering == Greater {
1319     println!("greater");
1320 } else if ordering == Equal {
1321     println!("equal");
1322 }
1323 ```
1324
1325 We can re-write this as a `match`:
1326
1327 ```{rust}
1328 let x = 5i;
1329 let y = 10i;
1330
1331 match x.cmp(&y) {
1332     Less    => println!("less"),
1333     Greater => println!("greater"),
1334     Equal   => println!("equal"),
1335 }
1336 ```
1337
1338 This version has way less noise, and it also checks exhaustively to make sure
1339 that we have covered all possible variants of `Ordering`. With our `if`/`else`
1340 version, if we had forgotten the `Greater` case, for example, our program would
1341 have happily compiled. If we forget in the `match`, it will not. Rust helps us
1342 make sure to cover all of our bases.
1343
1344 `match` is also an expression, which means we can use it on the right hand side
1345 of a `let` binding. We could also implement the previous line like this:
1346
1347 ```
1348 let x = 5i;
1349 let y = 10i;
1350
1351 let result = match x.cmp(&y) {
1352     Less    => "less",
1353     Greater => "greater",
1354     Equal   => "equal",
1355 };
1356
1357 println!("{}", result);
1358 ```
1359
1360 In this case, it doesn't make a lot of sense, as we are just making a temporary
1361 string where we don't need to, but sometimes, it's a nice pattern.
1362
1363 ## Looping
1364
1365 Looping is the last basic construct that we haven't learned yet in Rust. Rust has
1366 two main looping constructs: `for` and `while`.
1367
1368 ### `for`
1369
1370 The `for` loop is used to loop a particular number of times. Rust's `for` loops
1371 work a bit differently than in other systems languages, however. Rust's `for`
1372 loop doesn't look like this C `for` loop:
1373
1374 ```{ignore,c}
1375 for (x = 0; x < 10; x++) {
1376     printf( "%d\n", x );
1377 }
1378 ```
1379
1380 It looks like this:
1381
1382 ```{rust}
1383 for x in range(0i, 10i) {
1384     println!("{:d}", x);
1385 }
1386 ```
1387
1388 In slightly more abstract terms,
1389
1390 ```{ignore,notrust}
1391 for var in expression {
1392     code
1393 }
1394 ```
1395
1396 The expression is an iterator, which we will discuss in more depth later in the
1397 guide. The iterator gives back a series of elements. Each element is one
1398 iteration of the loop. That value is then bound to the name `var`, which is
1399 valid for the loop body. Once the body is over, the next value is fetched from
1400 the iterator, and we loop another time. When there are no more values, the
1401 `for` loop is over.
1402
1403 In our example, the `range` function is a function, provided by Rust, that
1404 takes a start and an end position, and gives an iterator over those values. The
1405 upper bound is exclusive, though, so our loop will print `0` through `9`, not
1406 `10`.
1407
1408 Rust does not have the "C style" `for` loop on purpose. Manually controlling
1409 each element of the loop is complicated and error prone, even for experienced C
1410 developers. There's an old joke that goes, "There are two hard problems in
1411 computer science: naming things, cache invalidation, and off-by-one errors."
1412 The joke, of course, being that the setup says "two hard problems" but then
1413 lists three things. This happens quite a bit with "C style" `for` loops.
1414
1415 We'll talk more about `for` when we cover **vector**s, later in the Guide.
1416
1417 ### `while`
1418
1419 The other kind of looping construct in Rust is the `while` loop. It looks like
1420 this:
1421
1422 ```{rust}
1423 let mut x = 5u;
1424 let mut done = false;
1425
1426 while !done {
1427     x += x - 3;
1428     println!("{}", x);
1429     if x % 5 == 0 { done = true; }
1430 }
1431 ```
1432
1433 `while` loops are the correct choice when you're not sure how many times
1434 you need to loop. 
1435
1436 If you need an infinite loop, you may be tempted to write this:
1437
1438 ```{rust,ignore}
1439 while true {
1440 ```
1441
1442 Rust has a dedicated keyword, `loop`, to handle this case:
1443
1444 ```{rust,ignore}
1445 loop {
1446 ```
1447
1448 Rust's control-flow analysis treats this construct differently than a
1449 `while true`, since we know that it will always loop. The details of what
1450 that _means_ aren't super important to understand at this stage, but in
1451 general, the more information we can give to the compiler, the better it
1452 can do with safety and code generation. So you should always prefer
1453 `loop` when you plan to loop infinitely.
1454
1455 ### Ending iteration early
1456
1457 Let's take a look at that `while` loop we had earlier:
1458
1459 ```{rust}
1460 let mut x = 5u;
1461 let mut done = false;
1462
1463 while !done {
1464     x += x - 3;
1465     println!("{}", x);
1466     if x % 5 == 0 { done = true; }
1467 }
1468 ```
1469
1470 We had to keep a dedicated `mut` boolean variable binding, `done`, to know
1471 when we should skip out of the loop. Rust has two keywords to help us with
1472 modifying iteration: `break` and `continue`.
1473
1474 In this case, we can write the loop in a better way with `break`:
1475
1476 ```{rust}
1477 let mut x = 5u;
1478
1479 loop {
1480     x += x - 3;
1481     println!("{}", x);
1482     if x % 5 == 0 { break; }
1483 }
1484 ```
1485
1486 We now loop forever with `loop`, and use `break` to break out early.
1487
1488 `continue` is similar, but instead of ending the loop, goes to the next
1489 iteration: This will only print the odd numbers:
1490
1491 ```
1492 for x in range(0i, 10i) {
1493     if x % 2 == 0 { continue; }
1494
1495     println!("{:d}", x);
1496 }
1497 ```
1498
1499 Both `continue` and `break` are valid in both kinds of loops.
1500
1501 We have now learned all of the most basic Rust concepts. We're ready to start
1502 building our guessing game, but we need to know how to do one last thing first:
1503 get input from the keyboard. You can't have a guessing game without the ability
1504 to guess!
1505
1506 ## Standard Input
1507
1508 Getting input from the keyboard is pretty easy, but uses some things
1509 we haven't seen before. Here's a simple program that reads some input,
1510 and then prints it back out:
1511
1512 ```{rust,ignore}
1513 fn main() {
1514     println!("Type something!");
1515
1516     let input = std::io::stdin().read_line().ok().expect("Failed to read line");
1517
1518     println!("{}", input);
1519 }
1520 ```
1521
1522 Let's go over these chunks, one by one:
1523
1524 ```{rust}
1525 std::io::stdin();
1526 ```
1527
1528 This calls a function, `stdin()`, that lives inside the `std::io` module. As
1529 you can imagine, everything in `std` is provided by Rust, the 'standard
1530 library.' We'll talk more about the module system later.
1531
1532 Since writing the fully qualified name all the time is annoying, we can use
1533 the `use` statement to import it in:
1534
1535 ```{rust}
1536 use std::io::stdin;
1537
1538 stdin();
1539 ```
1540
1541 However, it's considered better practice to not import individual functions, but
1542 to import the module, and only use one level of qualification:
1543
1544 ```{rust}
1545 use std::io;
1546
1547 io::stdin();
1548 ```
1549
1550 Let's update our example to use this style:
1551
1552 ```{rust,ignore}
1553 use std::io;
1554
1555 fn main() {
1556     println!("Type something!");
1557
1558     let input = io::stdin().read_line().ok().expect("Failed to read line");
1559
1560     println!("{}", input);
1561 }
1562 ```
1563
1564 Next up:
1565
1566 ```{rust,ignore}
1567 .read_line()
1568 ```
1569
1570 The `read_line()` method can be called on the result of `stdin()` to return
1571 a full line of input. Nice and easy.
1572
1573 ```{rust,ignore}
1574 .ok().expect("Failed to read line");
1575 ```
1576
1577 Here's the thing: reading a line from standard input could fail. For example,
1578 if this program isn't running in a terminal, but is running as part of a cron
1579 job, or some other context where there's no standard input. So Rust expects us
1580 to handle this case. Given that we plan on always running this program in a
1581 terminal, we use the `ok()` method to tell Rust that we're expecting everything
1582 to be just peachy, and the `expect()` method on that result to give an error
1583 message if our expectation goes wrong.
1584
1585 We will cover the exact details of how all of this works later in the Guide.
1586 For now, this is all you need.
1587
1588 With long lines like this, Rust gives you some flexibility with the whitespace.
1589 We _could_ write the example like this:
1590
1591 ```{rust,ignore}
1592 use std::io;
1593
1594 fn main() {
1595     println!("Type something!");
1596
1597     let input = io::stdin()
1598                   .read_line()
1599                   .ok()
1600                   .expect("Failed to read line");
1601
1602     println!("{}", input);
1603 }
1604 ```
1605
1606 Sometimes, this makes things more readable. Sometimes, less. Use your judgement
1607 here.
1608
1609 That's all you need to get basic input from the standard input! It's not too
1610 complicated, but there are a number of small parts.
1611
1612 ## Guessing Game: complete
1613
1614 At this point, you have successfully built the Guessing Game! Congratulations!
1615 For reference, [We've placed the sample code on
1616 GitHub](https://github.com/steveklabnik/guessing_game).
1617
1618 You've now learned the basic syntax of Rust. All of this is relatively close to
1619 various other programming languages you have used in the past. These
1620 fundamental syntactical and semantic elements will form the foundation for the
1621 rest of your Rust education.
1622
1623 Now that you're an expert at the basics, it's time to learn about some of
1624 Rust's more unique features.
1625
1626 ## iterators
1627
1628 ## Lambdas
1629
1630 ## Testing
1631
1632 attributes
1633
1634 stability markers
1635
1636 ## Crates and Modules
1637
1638 visibility
1639
1640
1641 ## Generics
1642
1643 ## Traits
1644
1645 ## Operators and built-in Traits
1646
1647 ## Ownership and Lifetimes
1648
1649 Move vs. Copy
1650
1651 Allocation
1652
1653 ## Tasks
1654
1655 ## Macros
1656
1657 ## Unsafe
1658