3 Hey there! Welcome to the Rust guide. This is the place to be if you'd like to
4 learn how to program in Rust. Rust is a systems programming language with a
5 focus on "high-level, bare-metal programming": the lowest level control a
6 programming language can give you, but with zero-cost, higher level
7 abstractions, because people aren't computers. We really think Rust is
8 something special, and we hope you do too.
10 To show you how to get going with Rust, we're going to write the traditional
11 "Hello, World!" program. Next, we'll introduce you to a tool that's useful for
12 writing real-world Rust programs and libraries: "Cargo." After that, we'll talk
13 about the basics of Rust, write a little program to try them out, and then learn
20 The first step to using Rust is to install it! There are a number of ways to
21 install Rust, but the easiest is to use the `rustup` script. If you're on
22 Linux or a Mac, all you need to do is this (note that you don't need to type
23 in the `$`s, they just indicate the start of each command):
26 $ curl -s https://static.rust-lang.org/rustup.sh | sudo sh
29 (If you're concerned about `curl | sudo sh`, please keep reading. Disclaimer
32 If you're on Windows, please download either the [32-bit
33 installer](https://static.rust-lang.org/dist/rust-nightly-i686-w64-mingw32.exe)
35 installer](https://static.rust-lang.org/dist/rust-nightly-x86_64-w64-mingw32.exe)
38 If you decide you don't want Rust anymore, we'll be a bit sad, but that's okay.
39 Not every programming language is great for everyone. Just pass an argument to
43 $ curl -s https://static.rust-lang.org/rustup.sh | sudo sh -s -- --uninstall
46 If you used the Windows installer, just re-run the `.exe` and it will give you
49 You can re-run this script any time you want to update Rust. Which, at this
50 point, is often. Rust is still pre-1.0, and so people assume that you're using
53 This brings me to one other point: some people, and somewhat rightfully so, get
54 very upset when we tell you to `curl | sudo sh`. And they should be! Basically,
55 when you do this, you are trusting that the good people who maintain Rust
56 aren't going to hack your computer and do bad things. That's a good instinct!
57 If you're one of those people, please check out the documentation on [building
58 Rust from Source](https://github.com/rust-lang/rust#building-from-source), or
59 [the official binary downloads](http://www.rust-lang.org/install.html). And we
60 promise that this method will not be the way to install Rust forever: it's just
61 the easiest way to keep people updated while Rust is in its alpha state.
63 Oh, we should also mention the officially supported platforms:
65 * Windows (7, 8, Server 2008 R2), x86 only
66 * Linux (2.6.18 or later, various distributions), x86 and x86-64
67 * OSX 10.7 (Lion) or greater, x86 and x86-64
69 We extensively test Rust on these platforms, and a few others, too, like
70 Android. But these are the ones most likely to work, as they have the most
73 Finally, a comment about Windows. Rust considers Windows to be a first-class
74 platform upon release, but if we're honest, the Windows experience isn't as
75 integrated as the Linux/OS X experience is. We're working on it! If anything
76 does not work, it is a bug. Please let us know if that happens. Each and every
77 commit is tested against Windows just like any other platform.
79 If you've got Rust installed, you can open up a shell, and type this:
85 You should see some output that looks something like this:
88 rustc 0.12.0-pre (443a1cd 2014-06-08 14:56:52 -0700)
91 If you did, Rust has been installed successfully! Congrats!
93 If not, there are a number of places where you can get help. The easiest is
94 [the #rust IRC channel on irc.mozilla.org](irc://irc.mozilla.org/#rust), which
95 you can access through
96 [Mibbit](http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust). Click
97 that link, and you'll be chatting with other Rustaceans (a silly nickname we
98 call ourselves), and we can help you out. Other great resources include [our
99 mailing list](https://mail.mozilla.org/listinfo/rust-dev), [the /r/rust
100 subreddit](http://www.reddit.com/r/rust), and [Stack
101 Overflow](http://stackoverflow.com/questions/tagged/rust).
105 Now that you have Rust installed, let's write your first Rust program. It's
106 traditional to make your first program in any new language one that prints the
107 text "Hello, world!" to the screen. The nice thing about starting with such a
108 simple program is that you can verify that your compiler isn't just installed,
109 but also working properly. And printing information to the screen is a pretty
112 The first thing that we need to do is make a file to put our code in. I like
113 to make a `projects` directory in my home directory, and keep all my projects
114 there. Rust does not care where your code lives.
116 This actually leads to one other concern we should address: this guide will
117 assume that you have basic familiarity with the command line. Rust does not
118 require that you know a whole ton about the command line, but until the
119 language is in a more finished state, IDE support is spotty. Rust makes no
120 specific demands on your editing tooling, or where your code lives.
122 With that said, let's make a directory in our projects directory.
131 If you're on Windows and not using PowerShell, the `~` may not work. Consult
132 the documentation for your shell for more details.
134 Let's make a new source file next. I'm going to use the syntax `editor
135 filename` to represent editing a file in these examples, but you should use
136 whatever method you want. We'll call our file `main.rs`:
142 Rust files always end in a `.rs` extension. If you're using more than one word
143 in your file name, use an underscore. `hello_world.rs` rather than
146 Now that you've got your file open, type this in:
150 println!("Hello, world!");
154 Save the file, and then type this into your terminal window:
158 $ ./main # or main.exe on Windows
162 Success! Let's go over what just happened in detail.
170 These lines define a **function** in Rust. The `main` function is special:
171 it's the beginning of every Rust program. The first line says "I'm declaring a
172 function named `main`, which takes no arguments and returns nothing." If there
173 were arguments, they would go inside the parentheses (`(` and `)`), and because
174 we aren't returning anything from this function, we've dropped that notation
175 entirely. We'll get to it later.
177 You'll also note that the function is wrapped in curly braces (`{` and `}`).
178 Rust requires these around all function bodies. It is also considered good
179 style to put the opening curly brace on the same line as the function
180 declaration, with one space in between.
182 Next up is this line:
185 println!("Hello, world!");
188 This line does all of the work in our little program. There are a number of
189 details that are important here. The first is that it's indented with four
190 spaces, not tabs. Please configure your editor of choice to insert four spaces
191 with the tab key. We provide some [sample configurations for various
192 editors](https://github.com/rust-lang/rust/tree/master/src/etc).
194 The second point is the `println!()` part. This is calling a Rust **macro**,
195 which is how metaprogramming is done in Rust. If it were a function instead, it
196 would look like this: `println()`. For our purposes, we don't need to worry
197 about this difference. Just know that sometimes, you'll see a `!`, and that
198 means that you're calling a macro instead of a normal function. One last thing
199 to mention: Rust's macros are significantly different than C macros, if you've
200 used those. Don't be scared of using macros. We'll get to the details
201 eventually, you'll just have to trust us for now.
203 Next, `"Hello, world!"` is a **string**. Strings are a surprisingly complicated
204 topic in a systems programming language, and this is a **statically allocated**
205 string. We will talk more about different kinds of allocation later. We pass
206 this string as an argument to `println!`, which prints the string to the
209 Finally, the line ends with a semicolon (`;`). Rust is an **expression
210 oriented** language, which means that most things are expressions. The `;` is
211 used to indicate that this expression is over, and the next one is ready to
212 begin. Most lines of Rust code end with a `;`. We will cover this in-depth
215 Finally, actually **compiling** and **running** our program. We can compile
216 with our compiler, `rustc`, by passing it the name of our source file:
222 This is similar to `gcc` or `clang`, if you come from a C or C++ background. Rust
223 will output a binary executable. You can see it with `ls`:
237 There are now two files: our source code, with the `.rs` extension, and the
238 executable (`main.exe` on Windows, `main` everywhere else)
241 $ ./main # or main.exe on Windows
244 This prints out our `Hello, world!` text to our terminal.
246 If you come from a dynamically typed language like Ruby, Python, or JavaScript,
247 you may not be used to these two steps being separate. Rust is an
248 **ahead-of-time compiled language**, which means that you can compile a
249 program, give it to someone else, and they don't need to have Rust installed.
250 If you give someone a `.rb` or `.py` or `.js` file, they need to have
251 Ruby/Python/JavaScript installed, but you just need one command to both compile
252 and run your program. Everything is a tradeoff in language design, and Rust has
255 Congratulations! You have officially written a Rust program. That makes you a
256 Rust programmer! Welcome.
258 Next, I'd like to introduce you to another tool, Cargo, which is used to write
259 real-world Rust programs. Just using `rustc` is nice for simple things, but as
260 your project grows, you'll want something to help you manage all of the options
261 that it has, and to make it easy to share your code with other people and
266 [Cargo](http://crates.io) is a tool that Rustaceans use to help manage their
267 Rust projects. Cargo is currently in an alpha state, just like Rust, and so it
268 is still a work in progress. However, it is already good enough to use for many
269 Rust projects, and so it is assumed that Rust projects will use Cargo from the
272 Cargo manages three things: building your code, downloading the dependencies
273 your code needs, and building the dependencies your code needs. At first, your
274 program doesn't have any dependencies, so we'll only be using the first part of
275 its functionality. Eventually, we'll add more. Since we started off by using
276 Cargo, it'll be easy to add later.
278 Let's convert Hello World to Cargo. The first thing we need to do to begin
279 using Cargo is to install Cargo. Luckily for us, the script we ran to install
280 Rust includes Cargo by default. If you installed Rust some other way, you may
281 want to [check the Cargo
282 README](https://github.com/rust-lang/cargo#installing-cargo-from-nightlies)
283 for specific instructions about installing it.
285 To Cargo-ify our project, we need to do two things: Make a `Cargo.toml`
286 configuration file, and put our source file in the right place. Let's
291 $ mv main.rs src/main.rs
294 Cargo expects your source files to live inside a `src` directory. That leaves
295 the top level for other things, like READMEs, license information, and anything
296 not related to your code. Cargo helps us keep our projects nice and tidy. A
297 place for everything, and everything in its place.
299 Next, our configuration file:
305 Make sure to get this name right: you need the capital `C`!
314 authors = [ "Your name <you@example.com>" ]
321 This file is in the [TOML](https://github.com/toml-lang/toml) format. Let's let
322 it explain itself to you:
324 > TOML aims to be a minimal configuration file format that's easy to read due
325 > to obvious semantics. TOML is designed to map unambiguously to a hash table.
326 > TOML should be easy to parse into data structures in a wide variety of
329 TOML is very similar to INI, but with some extra goodies.
331 Anyway, there are two **table**s in this file: `package` and `bin`. The first
332 tells Cargo metadata about your package. The second tells Cargo that we're
333 interested in building a binary, not a library (though we could do both!), as
334 well as what it is named.
336 Once you have this file in place, we should be ready to build! Try this:
340 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
341 $ ./target/hello_world
345 Bam! We build our project with `cargo build`, and run it with
346 `./target/hello_world`. This hasn't bought us a whole lot over our simple use
347 of `rustc`, but think about the future: when our project has more than one
348 file, we would need to call `rustc` twice, and pass it a bunch of options to
349 tell it to build everything together. With Cargo, as our project grows, we can
350 just `cargo build` and it'll work the right way.
352 You'll also notice that Cargo has created a new file: `Cargo.lock`.
360 This file is used by Cargo to keep track of dependencies in your application.
361 Right now, we don't have any, so it's a bit sparse. You won't ever need
362 to touch this file yourself, just let Cargo handle it.
364 That's it! We've successfully built `hello_world` with Cargo. Even though our
365 program is simple, it's using much of the real tooling that you'll use for the
366 rest of your Rust career.
368 Now that you've got the tools down, let's actually learn more about the Rust
369 language itself. These are the basics that will serve you well through the rest
370 of your time with Rust.
374 The first thing we'll learn about are 'variable bindings.' They look like this:
380 In many languages, this is called a 'variable.' But Rust's variable bindings
381 have a few tricks up their sleeves. Rust has a very powerful feature called
382 'pattern matching' that we'll get into detail with later, but the left
383 hand side of a `let` expression is a full pattern, not just a variable name.
384 This means we can do things like:
387 let (x, y) = (1i, 2i);
390 After this expression is evaluated, `x` will be one, and `y` will be two.
391 Patterns are really powerful, but this is about all we can do with them so far.
392 So let's just keep this in the back of our minds as we go forward.
394 By the way, in these examples, `i` indicates that the number is an integer.
396 Rust is a statically typed language, which means that we specify our types up
397 front. So why does our first example compile? Well, Rust has this thing called
398 "type inference." If it can figure out what the type of something is, Rust
399 doesn't require you to actually type it out.
401 We can add the type if we want to, though. Types come after a colon (`:`):
407 If I asked you to read this out loud to the rest of the class, you'd say "`x`
408 is a binding with the type `int` and the value `five`."
410 By default, bindings are **immutable**. This code will not compile:
417 It will give you this error:
420 error: re-assignment of immutable variable `x`
425 If you want a binding to be mutable, you can use `mut`:
432 There is no single reason that bindings are immutable by default, but we can
433 think about it through one of Rust's primary focuses: safety. If you forget to
434 say `mut`, the compiler will catch it, and let you know that you have mutated
435 something you may not have cared to mutate. If bindings were mutable by
436 default, the compiler would not be able to tell you this. If you _did_ intend
437 mutation, then the solution is quite easy: add `mut`.
439 There are other good reasons to avoid mutable state when possible, but they're
440 out of the scope of this guide. In general, you can often avoid explicit
441 mutation, and so it is preferable in Rust. That said, sometimes, mutation is
442 what you need, so it's not verboten.
444 Let's get back to bindings. Rust variable bindings have one more aspect that
445 differs from other languages: bindings are required to be initialized with a
446 value before you're allowed to use them. If we try...
452 ...we'll get an error:
455 src/main.rs:2:9: 2:10 error: cannot determine a type for this local variable: unconstrained type
460 Giving it a type will compile, though:
466 Let's try it out. Change your `src/main.rs` file to look like this:
472 println!("Hello world!");
476 You can use `cargo build` on the command line to build it. You'll get a warning,
477 but it will still print "Hello, world!":
480 Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
481 src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variable)] on by default
482 src/main.rs:2 let x: int;
486 Rust warns us that we never use the variable binding, but since we never use it,
487 no harm, no foul. Things change if we try to actually use this `x`, however. Let's
488 do that. Change your program to look like this:
494 println!("The value of x is: {}", x);
498 And try to build it. You'll get an error:
502 Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
503 src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
504 src/main.rs:4 println!("The value of x is: {}", x);
506 note: in expansion of format_args!
507 <std macros>:2:23: 2:77 note: expansion site
508 <std macros>:1:1: 3:2 note: in expansion of println!
509 src/main.rs:4:5: 4:42 note: expansion site
510 error: aborting due to previous error
511 Could not compile `hello_world`.
514 Rust will not let us use a value that has not been initialized. Next, let's
515 talk about this stuff we've added to `println!`.
517 If you include two curly braces (`{}`, some call them moustaches...) in your
518 string to print, Rust will interpret this as a request to interpolate some sort
519 of value. **String interpolation** is a computer science term that means "stick
520 in the middle of a string." We add a comma, and then `x`, to indicate that we
521 want `x` to be the value we're interpolating. The comma is used to separate
522 arguments we pass to functions and macros, if you're passing more than one.
524 When you just use the curly braces, Rust will attempt to display the
525 value in a meaningful way by checking out its type. If you want to specify the
526 format in a more detailed manner, there are a [wide number of options
527 available](std/fmt/index.html). For now, we'll just stick to the default:
528 integers aren't very complicated to print.
532 Rust's take on `if` is not particularly complex, but it's much more like the
533 `if` you'll find in a dynamically typed language than in a more traditional
534 systems language. So let's talk about it, to make sure you grasp the nuances.
536 `if` is a specific form of a more general concept, the 'branch.' The name comes
537 from a branch in a tree: a decision point, where depending on a choice,
538 multiple paths can be taken.
540 In the case of `if`, there is one choice that leads down two paths:
546 println!("x is five!");
550 If we changed the value of `x` to something else, this line would not print.
551 More specifically, if the expression after the `if` evaluates to `true`, then
552 the block is executed. If it's `false`, then it is not.
554 If you want something to happen in the `false` case, use an `else`:
560 println!("x is five!");
562 println!("x is not five :(");
566 This is all pretty standard. However, you can also do this:
579 Which we can (and probably should) write like this:
584 let y = if x == 5i { 10i } else { 15i };
587 This reveals two interesting things about Rust: it is an expression-based
588 language, and semicolons are different than in other 'curly brace and
589 semicolon'-based languages. These two things are related.
591 ## Expressions vs. Statements
593 Rust is primarily an expression based language. There are only two kinds of
594 statements, and everything else is an expression.
596 So what's the difference? Expressions return a value, and statements do not.
597 In many languages, `if` is a statement, and therefore, `let x = if ...` would
598 make no sense. But in Rust, `if` is an expression, which means that it returns
599 a value. We can then use this value to initialize the binding.
601 Speaking of which, bindings are a kind of the first of Rust's two statements.
602 The proper name is a **declaration statement**. So far, `let` is the only kind
603 of declaration statement we've seen. Let's talk about that some more.
605 In some languages, variable bindings can be written as expressions, not just
606 statements. Like Ruby:
612 In Rust, however, using `let` to introduce a binding is _not_ an expression. The
613 following will produce a compile-time error:
616 let x = (let y = 5i); // expected identifier, found keyword `let`
619 The compiler is telling us here that it was expecting to see the beginning of
620 an expression, and a `let` can only begin a statement, not an expression.
622 Note that assigning to an already-bound variable (e.g. `y = 5i`) is still an
623 expression, although its value is not particularly useful. Unlike C, where an
624 assignment evaluates to the assigned value (e.g. `5i` in the previous example),
625 in Rust the value of an assignment is the unit type `()` (which we'll cover later).
627 The second kind of statement in Rust is the **expression statement**. Its
628 purpose is to turn any expression into a statement. In practical terms, Rust's
629 grammar expects statements to follow other statements. This means that you use
630 semicolons to separate expressions from each other. This means that Rust
631 looks a lot like most other languages that require you to use semicolons
632 at the end of every line, and you will see semicolons at the end of almost
633 every line of Rust code you see.
635 What is this exception that makes us say 'almost?' You saw it already, in this
641 let y: int = if x == 5i { 10i } else { 15i };
644 Note that I've added the type annotation to `y`, to specify explicitly that I
645 want `y` to be an integer.
647 This is not the same as this, which won't compile:
652 let y: int = if x == 5i { 10i; } else { 15i; };
655 Note the semicolons after the 10 and 15. Rust will give us the following error:
658 error: mismatched types: expected `int` but found `()` (expected int but found ())
661 We expected an integer, but we got `()`. `()` is pronounced 'unit', and is a
662 special type in Rust's type system. `()` is different than `null` in other
663 languages, because `()` is distinct from other types. For example, in C, `null`
664 is a valid value for a variable of type `int`. In Rust, `()` is _not_ a valid
665 value for a variable of type `int`. It's only a valid value for variables of
666 the type `()`, which aren't very useful. Remember how we said statements don't
667 return a value? Well, that's the purpose of unit in this case. The semicolon
668 turns any expression into a statement by throwing away its value and returning
671 There's one more time in which you won't see a semicolon at the end of a line
672 of Rust code. For that, we'll need our next concept: functions.
676 You've already seen one function so far, the `main` function:
683 This is the simplest possible function declaration. As we mentioned before,
684 `fn` says 'this is a function,' followed by the name, some parenthesis because
685 this function takes no arguments, and then some curly braces to indicate the
686 body. Here's a function named `foo`:
693 So, what about taking arguments? Here's a function that prints a number:
696 fn print_number(x: int) {
697 println!("x is: {}", x);
701 Here's a complete program that uses `print_number`:
708 fn print_number(x: int) {
709 println!("x is: {}", x);
713 As you can see, function arguments work very similar to `let` declarations:
714 you add a type to the argument name, after a colon.
716 Here's a complete program that adds two numbers together and prints them:
723 fn print_sum(x: int, y: int) {
724 println!("sum is: {}", x + y);
728 You separate arguments with a comma, both when you call the function, as well
729 as when you declare it.
731 Unlike `let`, you _must_ declare the types of function arguments. This does
735 fn print_number(x, y) {
736 println!("x is: {}", x + y);
743 hello.rs:5:18: 5:19 error: expected `:` but found `,`
744 hello.rs:5 fn print_number(x, y) {
747 This is a deliberate design decision. While full-program inference is possible,
748 languages which have it, like Haskell, often suggest that documenting your
749 types explicitly is a best-practice. We agree that forcing functions to declare
750 types while allowing for inference inside of function bodies is a wonderful
751 sweet spot between full inference and no inference.
753 What about returning a value? Here's a function that adds one to an integer:
756 fn add_one(x: int) -> int {
761 Rust functions return exactly one value, and you declare the type after an
762 'arrow', which is a dash (`-`) followed by a greater-than sign (`>`).
764 You'll note the lack of a semicolon here. If we added it in:
767 fn add_one(x: int) -> int {
772 We would get an error:
775 error: not all control paths return a value
776 fn add_one(x: int) -> int {
780 note: consider removing this semicolon:
785 Remember our earlier discussions about semicolons and `()`? Our function claims
786 to return an `int`, but with a semicolon, it would return `()` instead. Rust
787 realizes this probably isn't what we want, and suggests removing the semicolon.
789 This is very much like our `if` statement before: the result of the block
790 (`{}`) is the value of the expression. Other expression-oriented languages,
791 such as Ruby, work like this, but it's a bit unusual in the systems programming
792 world. When people first learn about this, they usually assume that it
793 introduces bugs. But because Rust's type system is so strong, and because unit
794 is its own unique type, we have never seen an issue where adding or removing a
795 semicolon in a return position would cause a bug.
797 But what about early returns? Rust does have a keyword for that, `return`:
800 fn foo(x: int) -> int {
801 if x < 5 { return x; }
807 Using a `return` as the last line of a function works, but is considered poor
811 fn foo(x: int) -> int {
812 if x < 5 { return x; }
818 There are some additional ways to define functions, but they involve features
819 that we haven't learned about yet, so let's just leave it at that for now.
824 Now that we have some functions, it's a good idea to learn about comments.
825 Comments are notes that you leave to other programmers to help explain things
826 about your code. The compiler mostly ignores them.
828 Rust has two kinds of comments that you should care about: **line comment**s
829 and **doc comment**s.
832 // Line comments are anything after '//' and extend to the end of the line.
834 let x = 5i; // this is also a line comment.
836 // If you have a long explanation for something, you can put line comments next
837 // to each other. Put a space between the // and your comment so that it's
841 The other kind of comment is a doc comment. Doc comments use `///` instead of
842 `//`, and support Markdown notation inside:
845 /// `hello` is a function that prints a greeting that is personalized based on
850 /// * `name` - The name of the person you'd like to greet.
855 /// let name = "Steve";
856 /// hello(name); // prints "Hello, Steve!"
858 fn hello(name: &str) {
859 println!("Hello, {}!", name);
863 When writing doc comments, adding sections for any arguments, return values,
864 and providing some examples of usage is very, very helpful.
866 You can use the `rustdoc` tool to generate HTML documentation from these doc
867 comments. We will talk more about `rustdoc` when we get to modules, as
868 generally, you want to export documentation for a full module.
870 # Compound Data Types
872 Rust, like many programming languages, has a number of different data types
873 that are built-in. You've already done some simple work with integers and
874 strings, but next, let's talk about some more complicated ways of storing data.
878 The first compound data type we're going to talk about are called **tuple**s.
879 Tuples are an ordered list of a fixed size. Like this:
882 let x = (1i, "hello");
885 The parenthesis and commas form this two-length tuple. Here's the same code, but
886 with the type annotated:
889 let x: (int, &str) = (1, "hello");
892 As you can see, the type of a tuple looks just like the tuple, but with each
893 position having a type name rather than the value. Careful readers will also
894 note that tuples are heterogeneous: we have an `int` and a `&str` in this tuple.
895 You haven't seen `&str` as a type before, and we'll discuss the details of
896 strings later. In systems programming languages, strings are a bit more complex
897 than in other languages. For now, just read `&str` as "a string slice," and
898 we'll learn more soon.
900 You can access the fields in a tuple through a **destructuring let**. Here's
904 let (x, y, z) = (1i, 2i, 3i);
906 println!("x is {}", x);
909 Remember before when I said the left hand side of a `let` statement was more
910 powerful than just assigning a binding? Here we are. We can put a pattern on
911 the left hand side of the `let`, and if it matches up to the right hand side,
912 we can assign multiple bindings at once. In this case, `let` 'destructures,'
913 or 'breaks up,' the tuple, and assigns the bits to three bindings.
915 This pattern is very powerful, and we'll see it repeated more later.
917 The last thing to say about tuples is that they are only equivalent if
918 the arity, types, and values are all identical.
921 let x = (1i, 2i, 3i);
922 let y = (2i, 3i, 4i);
931 This will print `no`, as the values aren't equal.
933 One other use of tuples is to return multiple values from a function:
936 fn next_two(x: int) -> (int, int) { (x + 1i, x + 2i) }
939 let (x, y) = next_two(5i);
940 println!("x, y = {}, {}", x, y);
944 Even though Rust functions can only return one value, a tuple _is_ one value,
945 that happens to be made up of two. You can also see in this example how you
946 can destructure a pattern returned by a function, as well.
948 Tuples are a very simple data structure, and so are not often what you want.
949 Let's move on to their bigger sibling, structs.
953 A struct is another form of a 'record type,' just like a tuple. There's a
954 difference: structs give each element that they contain a name, called a
955 'field' or a 'member.' Check it out:
964 let origin = Point { x: 0i, y: 0i };
966 println!("The origin is at ({}, {})", origin.x, origin.y);
970 There's a lot going on here, so let's break it down. We declare a struct with
971 the `struct` keyword, and then with a name. By convention, structs begin with a
972 capital letter and are also camel cased: `PointInSpace`, not `Point_In_Space`.
974 We can create an instance of our struct via `let`, as usual, but we use a `key:
975 value` style syntax to set each field. The order doesn't need to be the same as
976 in the original declaration.
978 Finally, because fields have names, we can access the field through dot
979 notation: `origin.x`.
981 The values in structs are immutable, like other bindings in Rust. However, you
982 can use `mut` to make them mutable:
991 let mut point = Point { x: 0i, y: 0i };
995 println!("The point is at ({}, {})", point.x, point.y);
999 This will print `The point is at (5, 0)`.
1001 ## Tuple Structs and Newtypes
1003 Rust has another data type that's like a hybrid between a tuple and a struct,
1004 called a **tuple struct**. Tuple structs do have a name, but their fields
1009 struct Color(int, int, int);
1010 struct Point(int, int, int);
1013 These two will not be equal, even if they have the same values:
1016 let black = Color(0, 0, 0);
1017 let origin = Point(0, 0, 0);
1020 It is almost always better to use a struct than a tuple struct. We would write
1021 `Color` and `Point` like this instead:
1037 Now, we have actual names, rather than positions. Good names are important,
1038 and with a struct, we have actual names.
1040 There _is_ one case when a tuple struct is very useful, though, and that's a
1041 tuple struct with only one element. We call this a 'newtype,' because it lets
1042 you create a new type that's a synonym for another one:
1047 let length = Inches(10);
1049 let Inches(integer_length) = length;
1050 println!("length is {} inches", integer_length);
1053 As you can see here, you can extract the inner integer type through a
1054 destructuring `let`.
1058 Finally, Rust has a "sum type", an **enum**. Enums are an incredibly useful
1059 feature of Rust, and are used throughout the standard library. This is an enum
1060 that is provided by the Rust standard library:
1070 An `Ordering` can only be _one_ of `Less`, `Equal`, or `Greater` at any given
1071 time. Here's an example:
1074 fn cmp(a: int, b: int) -> Ordering {
1076 else if a > b { Greater }
1084 let ordering = cmp(x, y);
1086 if ordering == Less {
1088 } else if ordering == Greater {
1089 println!("greater");
1090 } else if ordering == Equal {
1096 `cmp` is a function that compares two things, and returns an `Ordering`. We
1097 return either `Less`, `Greater`, or `Equal`, depending on if the two values
1098 are greater, less, or equal.
1100 The `ordering` variable has the type `Ordering`, and so contains one of the
1101 three values. We can then do a bunch of `if`/`else` comparisons to check
1104 However, repeated `if`/`else` comparisons get quite tedious. Rust has a feature
1105 that not only makes them nicer to read, but also makes sure that you never
1106 miss a case. Before we get to that, though, let's talk about another kind of
1107 enum: one with values.
1109 This enum has two variants, one of which has a value:
1122 Value(n) => println!("x is {:d}", n),
1123 Missing => println!("x is missing!"),
1127 Value(n) => println!("y is {:d}", n),
1128 Missing => println!("y is missing!"),
1133 This enum represents an `int` that we may or may not have. In the `Missing`
1134 case, we have no value, but in the `Value` case, we do. This enum is specific
1135 to `int`s, though. We can make it usable by any type, but we haven't quite
1138 You can have any number of values in an enum:
1141 enum OptionalColor {
1142 Color(int, int, int),
1147 Enums with values are quite useful, but as I mentioned, they're even more
1148 useful when they're generic across types. But before we get to generics, let's
1149 talk about how to fix this big `if`/`else` statements we've been writing. We'll
1150 do that with `match`.
1154 Often, a simple `if`/`else` isn't enough, because you have more than two
1155 possible options. And `else` conditions can get incredibly complicated. So
1156 what's the solution?
1158 Rust has a keyword, `match`, that allows you to replace complicated `if`/`else`
1159 groupings with something more powerful. Check it out:
1165 1 => println!("one"),
1166 2 => println!("two"),
1167 3 => println!("three"),
1168 4 => println!("four"),
1169 5 => println!("five"),
1170 _ => println!("something else"),
1174 `match` takes an expression, and then branches based on its value. Each 'arm' of
1175 the branch is of the form `val => expression`. When the value matches, that arm's
1176 expression will be evaluated. It's called `match` because of the term 'pattern
1177 matching,' which `match` is an implementation of.
1179 So what's the big advantage here? Well, there are a few. First of all, `match`
1180 does 'exhaustiveness checking.' Do you see that last arm, the one with the
1181 underscore (`_`)? If we remove that arm, Rust will give us an error:
1184 error: non-exhaustive patterns: `_` not covered
1187 In other words, Rust is trying to tell us we forgot a value. Because `x` is an
1188 integer, Rust knows that it can have a number of different values. For example,
1189 `6i`. But without the `_`, there is no arm that could match, and so Rust refuses
1190 to compile. `_` is sort of like a catch-all arm. If none of the other arms match,
1191 the arm with `_` will. And since we have this catch-all arm, we now have an arm
1192 for every possible value of `x`, and so our program will now compile.
1194 `match` statements also destructure enums, as well. Remember this code from the
1198 fn cmp(a: int, b: int) -> Ordering {
1200 else if a > b { Greater }
1208 let ordering = cmp(x, y);
1210 if ordering == Less {
1212 } else if ordering == Greater {
1213 println!("greater");
1214 } else if ordering == Equal {
1220 We can re-write this as a `match`:
1223 fn cmp(a: int, b: int) -> Ordering {
1225 else if a > b { Greater }
1234 Less => println!("less"),
1235 Greater => println!("greater"),
1236 Equal => println!("equal"),
1241 This version has way less noise, and it also checks exhaustively to make sure
1242 that we have covered all possible variants of `Ordering`. With our `if`/`else`
1243 version, if we had forgotten the `Greater` case, for example, our program would
1244 have happily compiled. If we forget in the `match`, it will not. Rust helps us
1245 make sure to cover all of our bases.
1247 `match` is also an expression, which means we can use it on the right hand side
1248 of a `let` binding. We could also implement the previous line like this:
1251 fn cmp(a: int, b: int) -> Ordering {
1253 else if a > b { Greater }
1261 let result = match cmp(x, y) {
1263 Greater => "greater",
1267 println!("{}", result);
1271 In this case, it doesn't make a lot of sense, as we are just making a temporary
1272 string where we don't need to, but sometimes, it's a nice pattern.
1276 Looping is the last basic construct that we haven't learned yet in Rust. Rust has
1277 two main looping constructs: `for` and `while`.
1281 The `for` loop is used to loop a particular number of times. Rust's `for` loops
1282 work a bit differently than in other systems languages, however. Rust's `for`
1283 loop doesn't look like this "C style" `for` loop:
1286 for (x = 0; x < 10; x++) {
1287 printf( "%d\n", x );
1291 Instead, it looks like this:
1294 for x in range(0i, 10i) {
1295 println!("{:d}", x);
1299 In slightly more abstract terms,
1302 for var in expression {
1307 The expression is an iterator, which we will discuss in more depth later in the
1308 guide. The iterator gives back a series of elements. Each element is one
1309 iteration of the loop. That value is then bound to the name `var`, which is
1310 valid for the loop body. Once the body is over, the next value is fetched from
1311 the iterator, and we loop another time. When there are no more values, the
1314 In our example, `range` is a function that takes a start and an end position,
1315 and gives an iterator over those values. The upper bound is exclusive, though,
1316 so our loop will print `0` through `9`, not `10`.
1318 Rust does not have the "C style" `for` loop on purpose. Manually controlling
1319 each element of the loop is complicated and error prone, even for experienced C
1322 We'll talk more about `for` when we cover **iterator**s, later in the Guide.
1326 The other kind of looping construct in Rust is the `while` loop. It looks like
1331 let mut done = false;
1336 if x % 5 == 0 { done = true; }
1340 `while` loops are the correct choice when you're not sure how many times
1343 If you need an infinite loop, you may be tempted to write this:
1349 Rust has a dedicated keyword, `loop`, to handle this case:
1355 Rust's control-flow analysis treats this construct differently than a
1356 `while true`, since we know that it will always loop. The details of what
1357 that _means_ aren't super important to understand at this stage, but in
1358 general, the more information we can give to the compiler, the better it
1359 can do with safety and code generation. So you should always prefer
1360 `loop` when you plan to loop infinitely.
1362 ## Ending iteration early
1364 Let's take a look at that `while` loop we had earlier:
1368 let mut done = false;
1373 if x % 5 == 0 { done = true; }
1377 We had to keep a dedicated `mut` boolean variable binding, `done`, to know
1378 when we should skip out of the loop. Rust has two keywords to help us with
1379 modifying iteration: `break` and `continue`.
1381 In this case, we can write the loop in a better way with `break`:
1389 if x % 5 == 0 { break; }
1393 We now loop forever with `loop`, and use `break` to break out early.
1395 `continue` is similar, but instead of ending the loop, goes to the next
1396 iteration: This will only print the odd numbers:
1399 for x in range(0i, 10i) {
1400 if x % 2 == 0 { continue; }
1402 println!("{:d}", x);
1406 Both `continue` and `break` are valid in both kinds of loops.
1410 Strings are an important concept for any programmer to master. Rust's string
1411 handling system is a bit different than in other languages, due to its systems
1412 focus. Any time you have a data structure of variable size, things can get
1413 tricky, and strings are a re-sizable data structure. That said, Rust's strings
1414 also work differently than in some other systems languages, such as C.
1416 Let's dig into the details. A **string** is a sequence of unicode scalar values
1417 encoded as a stream of UTF-8 bytes. All strings are guaranteed to be
1418 validly-encoded UTF-8 sequences. Additionally, strings are not null-terminated
1419 and can contain null bytes.
1421 Rust has two main types of strings: `&str` and `String`.
1423 The first kind is a `&str`. This is pronounced a 'string slice.' String literals
1424 are of the type `&str`:
1427 let string = "Hello there.";
1430 This string is statically allocated, meaning that it's saved inside our
1431 compiled program, and exists for the entire duration it runs. The `string`
1432 binding is a reference to this statically allocated string. String slices
1433 have a fixed size, and cannot be mutated.
1435 A `String`, on the other hand, is an in-memory string. This string is
1436 growable, and is also guaranteed to be UTF-8.
1439 let mut s = "Hello".to_string();
1442 s.push_str(", world.");
1446 You can coerce a `String` into a `&str` with the `as_slice()` method:
1449 fn takes_slice(slice: &str) {
1450 println!("Got: {}", slice);
1454 let s = "Hello".to_string();
1455 takes_slice(s.as_slice());
1459 To compare a String to a constant string, prefer `as_slice()`...
1462 fn compare(string: String) {
1463 if string.as_slice() == "Hello" {
1469 ... over `to_string()`:
1472 fn compare(string: String) {
1473 if string == "Hello".to_string() {
1479 Converting a `String` to a `&str` is cheap, but converting the `&str` to a
1480 `String` involves allocating memory. No reason to do that unless you have to!
1482 That's the basics of strings in Rust! They're probably a bit more complicated
1483 than you are used to, if you come from a scripting language, but when the
1484 low-level details matter, they really matter. Just remember that `String`s
1485 allocate memory and control their data, while `&str`s are a reference to
1486 another string, and you'll be all set.
1490 Like many programming languages, Rust has a list type for when you want a list
1491 of things. But similar to strings, Rust has different types to represent this
1492 idea: `Vec<T>` (a 'vector'), `[T, .. N]` (an 'array'), and `&[T]` (a 'slice').
1495 Vectors are similar to `String`s: they have a dynamic length, and they
1496 allocate enough memory to fit. You can create a vector with the `vec!` macro:
1499 let nums = vec![1i, 2i, 3i];
1502 Notice that unlike the `println!` macro we've used in the past, we use square
1503 brackets (`[]`) with `vec!`. Rust allows you to use either in either situation,
1504 this is just convention.
1506 You can create an array with just square brackets:
1509 let nums = [1i, 2i, 3i];
1512 So what's the difference? An array has a fixed size, so you can't add or
1516 let mut nums = vec![1i, 2i, 3i];
1517 nums.push(4i); // works
1519 let mut nums = [1i, 2i, 3i];
1520 nums.push(4i); // error: type `[int, .. 3]` does not implement any method
1521 // in scope named `push`
1524 The `push()` method lets you append a value to the end of the vector. But
1525 since arrays have fixed sizes, adding an element doesn't make any sense.
1526 You can see how it has the exact type in the error message: `[int, .. 3]`.
1527 An array of `int`s, with length 3.
1529 Similar to `&str`, a slice is a reference to another array. We can get a
1530 slice from a vector by using the `as_slice()` method:
1533 let vec = vec![1i, 2i, 3i];
1534 let slice = vec.as_slice();
1537 All three types implement an `iter()` method, which returns an iterator. We'll
1538 talk more about the details of iterators later, but for now, the `iter()` method
1539 allows you to write a `for` loop that prints out the contents of a vector, array,
1543 let vec = vec![1i, 2i, 3i];
1545 for i in vec.iter() {
1550 This code will print each number in order, on its own line.
1552 You can access a particular element of a vector, array, or slice by using
1553 **subscript notation**:
1556 let names = ["Graydon", "Brian", "Niko"];
1558 println!("The second name is: {}", names[1]);
1561 These subscripts start at zero, like in most programming languages, so the
1562 first name is `names[0]` and the second name is `names[1]`. The above example
1563 prints `The second name is Brian`.
1565 There's a whole lot more to vectors, but that's enough to get started. We have
1566 now learned all of the most basic Rust concepts. We're ready to start building
1567 our guessing game, but we need to know how to do one last thing first: get
1568 input from the keyboard. You can't have a guessing game without the ability to
1573 Getting input from the keyboard is pretty easy, but uses some things
1574 we haven't seen before. Here's a simple program that reads some input,
1575 and then prints it back out:
1579 println!("Type something!");
1581 let input = std::io::stdin().read_line().ok().expect("Failed to read line");
1583 println!("{}", input);
1587 Let's go over these chunks, one by one:
1593 This calls a function, `stdin()`, that lives inside the `std::io` module. As
1594 you can imagine, everything in `std` is provided by Rust, the 'standard
1595 library.' We'll talk more about the module system later.
1597 Since writing the fully qualified name all the time is annoying, we can use
1598 the `use` statement to import it in:
1606 However, it's considered better practice to not import individual functions, but
1607 to import the module, and only use one level of qualification:
1615 Let's update our example to use this style:
1621 println!("Type something!");
1623 let input = io::stdin().read_line().ok().expect("Failed to read line");
1625 println!("{}", input);
1635 The `read_line()` method can be called on the result of `stdin()` to return
1636 a full line of input. Nice and easy.
1639 .ok().expect("Failed to read line");
1642 Do you remember this code?
1655 Value(n) => println!("x is {:d}", n),
1656 Missing => println!("x is missing!"),
1660 Value(n) => println!("y is {:d}", n),
1661 Missing => println!("y is missing!"),
1666 We had to match each time, to see if we had a value or not. In this case,
1667 though, we _know_ that `x` has a `Value`. But `match` forces us to handle
1668 the `missing` case. This is what we want 99% of the time, but sometimes, we
1669 know better than the compiler.
1671 Likewise, `read_line()` does not return a line of input. It _might_ return a
1672 line of input. It might also fail to do so. This could happen if our program
1673 isn't running in a terminal, but as part of a cron job, or some other context
1674 where there's no standard input. Because of this, `read_line` returns a type
1675 very similar to our `OptionalInt`: an `IoResult<T>`. We haven't talked about
1676 `IoResult<T>` yet because it is the **generic** form of our `OptionalInt`.
1677 Until then, you can think of it as being the same thing, just for any type, not
1680 Rust provides a method on these `IoResult<T>`s called `ok()`, which does the
1681 same thing as our `match` statement, but assuming that we have a valid value.
1682 If we don't, it will terminate our program. In this case, if we can't get
1683 input, our program doesn't work, so we're okay with that. In most cases, we
1684 would want to handle the error case explicitly. The result of `ok()` has a
1685 method, `expect()`, which allows us to give an error message if this crash
1688 We will cover the exact details of how all of this works later in the Guide.
1689 For now, this gives you enough of a basic understanding to work with.
1691 Back to the code we were working on! Here's a refresher:
1697 println!("Type something!");
1699 let input = io::stdin().read_line().ok().expect("Failed to read line");
1701 println!("{}", input);
1705 With long lines like this, Rust gives you some flexibility with the whitespace.
1706 We _could_ write the example like this:
1712 println!("Type something!");
1714 let input = io::stdin()
1717 .expect("Failed to read line");
1719 println!("{}", input);
1723 Sometimes, this makes things more readable. Sometimes, less. Use your judgment
1726 That's all you need to get basic input from the standard input! It's not too
1727 complicated, but there are a number of small parts.
1731 Okay! We've got the basics of Rust down. Let's write a bigger program.
1733 For our first project, we'll implement a classic beginner programming problem:
1734 the guessing game. Here's how it works: Our program will generate a random
1735 integer between one and a hundred. It will then prompt us to enter a guess.
1736 Upon entering our guess, it will tell us if we're too low or too high. Once we
1737 guess correctly, it will congratulate us, and print the number of guesses we've
1738 taken to the screen. Sound good?
1742 Let's set up a new project. Go to your projects directory. Remember how we
1743 had to create our directory structure and a `Cargo.toml` for `hello_world`? Cargo
1744 has a command that does that for us. Let's give it a shot:
1748 $ cargo new guessing_game --bin
1752 We pass the name of our project to `cargo new`, and then the `--bin` flag,
1753 since we're making a binary, rather than a library.
1755 Check out the generated `Cargo.toml`:
1760 name = "guessing_game"
1762 authors = ["Your Name <you@example.com>"]
1765 Cargo gets this information from your environment. If it's not correct, go ahead
1768 Finally, Cargo generated a hello, world for us. Check out `src/main.rs`:
1772 println!("Hello, world!");
1776 Let's try compiling what Cargo gave us:
1780 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1783 Excellent! Open up your `src/main.rs` again. We'll be writing all of
1784 our code in this file. We'll talk about multiple-file projects later on in the
1787 Before we move on, let me show you one more Cargo command: `run`. `cargo run`
1788 is kind of like `cargo build`, but it also then runs the produced executable.
1793 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1794 Running `target/guessing_game`
1798 Great! The `run` command comes in handy when you need to rapidly iterate on a project.
1799 Our game is just such a project, we need to quickly test each iteration before moving on to the next one.
1801 ## Processing a Guess
1803 Let's get to it! The first thing we need to do for our guessing game is
1804 allow our player to input a guess. Put this in your `src/main.rs`:
1810 println!("Guess the number!");
1812 println!("Please input your guess.");
1814 let input = io::stdin().read_line()
1816 .expect("Failed to read line");
1818 println!("You guessed: {}", input);
1822 You've seen this code before, when we talked about standard input. We
1823 import the `std::io` module with `use`, and then our `main` function contains
1824 our program's logic. We print a little message announcing the game, ask the
1825 user to input a guess, get their input, and then print it out.
1827 Because we talked about this in the section on standard I/O, I won't go into
1828 more details here. If you need a refresher, go re-read that section.
1830 ## Generating a secret number
1832 Next, we need to generate a secret number. To do that, we need to use Rust's
1833 random number generation, which we haven't talked about yet. Rust includes a
1834 bunch of interesting functions in its standard library. If you need a bit of
1835 code, it's possible that it's already been written for you! In this case,
1836 we do know that Rust has random number generation, but we don't know how to
1839 Enter the docs. Rust has a page specifically to document the standard library.
1840 You can find that page [here](std/index.html). There's a lot of information on
1841 that page, but the best part is the search bar. Right up at the top, there's
1842 a box that you can enter in a search term. The search is pretty primitive
1843 right now, but is getting better all the time. If you type 'random' in that
1844 box, the page will update to [this
1845 one](http://doc.rust-lang.org/std/index.html?search=random). The very first
1847 [std::rand::random](http://doc.rust-lang.org/std/rand/fn.random.html). If we
1848 click on that result, we'll be taken to its documentation page.
1850 This page shows us a few things: the type signature of the function, some
1851 explanatory text, and then an example. Let's modify our code to add in the
1859 println!("Guess the number!");
1861 let secret_number = (rand::random() % 100i) + 1i;
1863 println!("The secret number is: {}", secret_number);
1865 println!("Please input your guess.");
1867 let input = io::stdin().read_line()
1869 .expect("Failed to read line");
1872 println!("You guessed: {}", input);
1876 The first thing we changed was to `use std::rand`, as the docs
1877 explained. We then added in a `let` expression to create a variable binding
1878 named `secret_number`, and we printed out its result.
1880 Also, you may wonder why we are using `%` on the result of `rand::random()`.
1881 This operator is called 'modulo', and it returns the remainder of a division.
1882 By taking the modulo of the result of `rand::random()`, we're limiting the
1883 values to be between 0 and 99. Then, we add one to the result, making it from 1
1884 to 100. Using modulo can give you a very, very small bias in the result, but
1885 for this example, it is not important.
1887 Let's try to compile this using `cargo build`:
1891 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1892 src/main.rs:7:26: 7:34 error: the type of this value must be known in this context
1893 src/main.rs:7 let secret_number = (rand::random() % 100i) + 1i;
1895 error: aborting due to previous error
1898 It didn't work! Rust says "the type of this value must be known in this
1899 context." What's up with that? Well, as it turns out, `rand::random()` can
1900 generate many kinds of random values, not just integers. And in this case, Rust
1901 isn't sure what kind of value `random()` should generate. So we have to help
1902 it. With number literals, we just add an `i` onto the end to tell Rust they're
1903 integers, but that does not work with functions. There's a different syntax,
1904 and it looks like this:
1907 rand::random::<int>();
1910 This says "please give me a random `int` value." We can change our code to use
1918 println!("Guess the number!");
1920 let secret_number = (rand::random::<int>() % 100i) + 1i;
1922 println!("The secret number is: {}", secret_number);
1924 println!("Please input your guess.");
1926 let input = io::stdin().read_line()
1928 .expect("Failed to read line");
1931 println!("You guessed: {}", input);
1935 Try running our new program a few times:
1939 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1940 Running `target/guessing_game`
1942 The secret number is: 7
1943 Please input your guess.
1946 $ ./target/guessing_game
1948 The secret number is: 83
1949 Please input your guess.
1952 $ ./target/guessing_game
1954 The secret number is: -29
1955 Please input your guess.
1960 Wait. Negative 29? We wanted a number between one and a hundred! We have two
1961 options here: we can either ask `random()` to generate an unsigned integer, which
1962 can only be positive, or we can use the `abs()` function. Let's go with the
1963 unsigned integer approach. If we want a random positive number, we should ask for
1964 a random positive number. Our code looks like this now:
1971 println!("Guess the number!");
1973 let secret_number = (rand::random::<uint>() % 100u) + 1u;
1975 println!("The secret number is: {}", secret_number);
1977 println!("Please input your guess.");
1979 let input = io::stdin().read_line()
1981 .expect("Failed to read line");
1984 println!("You guessed: {}", input);
1992 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
1993 Running `target/guessing_game`
1995 The secret number is: 57
1996 Please input your guess.
2001 Great! Next up: let's compare our guess to the secret guess.
2003 ## Comparing guesses
2005 If you remember, earlier in the guide, we made a `cmp` function that compared
2006 two numbers. Let's add that in, along with a `match` statement to compare the
2007 guess to the secret guess:
2014 println!("Guess the number!");
2016 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2018 println!("The secret number is: {}", secret_number);
2020 println!("Please input your guess.");
2022 let input = io::stdin().read_line()
2024 .expect("Failed to read line");
2027 println!("You guessed: {}", input);
2029 match cmp(input, secret_number) {
2030 Less => println!("Too small!"),
2031 Greater => println!("Too big!"),
2032 Equal => { println!("You win!"); },
2036 fn cmp(a: int, b: int) -> Ordering {
2038 else if a > b { Greater }
2043 If we try to compile, we'll get some errors:
2047 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2048 src/main.rs:20:15: 20:20 error: mismatched types: expected `int` but found `collections::string::String` (expected int but found struct collections::string::String)
2049 src/main.rs:20 match cmp(input, secret_number) {
2051 src/main.rs:20:22: 20:35 error: mismatched types: expected `int` but found `uint` (expected int but found uint)
2052 src/main.rs:20 match cmp(input, secret_number) {
2054 error: aborting due to 2 previous errors
2057 This often happens when writing Rust programs, and is one of Rust's greatest
2058 strengths. You try out some code, see if it compiles, and Rust tells you that
2059 you've done something wrong. In this case, our `cmp` function works on integers,
2060 but we've given it unsigned integers. In this case, the fix is easy, because
2061 we wrote the `cmp` function! Let's change it to take `uint`s:
2068 println!("Guess the number!");
2070 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2072 println!("The secret number is: {}", secret_number);
2074 println!("Please input your guess.");
2076 let input = io::stdin().read_line()
2078 .expect("Failed to read line");
2081 println!("You guessed: {}", input);
2083 match cmp(input, secret_number) {
2084 Less => println!("Too small!"),
2085 Greater => println!("Too big!"),
2086 Equal => { println!("You win!"); },
2090 fn cmp(a: uint, b: uint) -> Ordering {
2092 else if a > b { Greater }
2097 And try compiling again:
2101 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2102 src/main.rs:20:15: 20:20 error: mismatched types: expected `uint` but found `collections::string::String` (expected uint but found struct collections::string::String)
2103 src/main.rs:20 match cmp(input, secret_number) {
2105 error: aborting due to previous error
2108 This error is similar to the last one: we expected to get a `uint`, but we got
2109 a `String` instead! That's because our `input` variable is coming from the
2110 standard input, and you can guess anything. Try it:
2113 $ ./target/guessing_game
2115 The secret number is: 73
2116 Please input your guess.
2121 Oops! Also, you'll note that we just ran our program even though it didn't compile.
2122 This works because the older version we did successfully compile was still lying
2123 around. Gotta be careful!
2125 Anyway, we have a `String`, but we need a `uint`. What to do? Well, there's
2126 a function for that:
2129 let input = io::stdin().read_line()
2131 .expect("Failed to read line");
2132 let input_num: Option<uint> = from_str(input.as_slice());
2135 The `from_str` function takes in a `&str` value and converts it into something.
2136 We tell it what kind of something with a type hint. Remember our type hint with
2137 `random()`? It looked like this:
2140 rand::random::<uint>();
2143 There's an alternate way of providing a hint too, and that's declaring the type
2147 let x: uint = rand::random();
2150 In this case, we say `x` is a `uint` explicitly, so Rust is able to properly
2151 tell `random()` what to generate. In a similar fashion, both of these work:
2154 let input_num = from_str::<Option<uint>>("5");
2155 let input_num: Option<uint> = from_str("5");
2158 In this case, I happen to prefer the latter, and in the `random()` case, I prefer
2159 the former. I think the nested `<>`s make the first option especially ugly and
2160 a bit harder to read.
2162 Anyway, with us now converting our input to a number, our code looks like this:
2169 println!("Guess the number!");
2171 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2173 println!("The secret number is: {}", secret_number);
2175 println!("Please input your guess.");
2177 let input = io::stdin().read_line()
2179 .expect("Failed to read line");
2180 let input_num: Option<uint> = from_str(input.as_slice());
2184 println!("You guessed: {}", input_num);
2186 match cmp(input_num, secret_number) {
2187 Less => println!("Too small!"),
2188 Greater => println!("Too big!"),
2189 Equal => { println!("You win!"); },
2193 fn cmp(a: uint, b: uint) -> Ordering {
2195 else if a > b { Greater }
2204 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2205 src/main.rs:22:15: 22:24 error: mismatched types: expected `uint` but found `core::option::Option<uint>` (expected uint but found enum core::option::Option)
2206 src/main.rs:22 match cmp(input_num, secret_number) {
2208 error: aborting due to previous error
2211 Oh yeah! Our `input_num` has the type `Option<uint>`, rather than `uint`. We
2212 need to unwrap the Option. If you remember from before, `match` is a great way
2213 to do that. Try this code:
2220 println!("Guess the number!");
2222 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2224 println!("The secret number is: {}", secret_number);
2226 println!("Please input your guess.");
2228 let input = io::stdin().read_line()
2230 .expect("Failed to read line");
2231 let input_num: Option<uint> = from_str(input.as_slice());
2233 let num = match input_num {
2236 println!("Please input a number!");
2242 println!("You guessed: {}", num);
2244 match cmp(num, secret_number) {
2245 Less => println!("Too small!"),
2246 Greater => println!("Too big!"),
2247 Equal => { println!("You win!"); },
2251 fn cmp(a: uint, b: uint) -> Ordering {
2253 else if a > b { Greater }
2258 We use a `match` to either give us the `uint` inside of the `Option`, or we
2259 print an error message and return. Let's give this a shot:
2263 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2264 Running `target/guessing_game`
2266 The secret number is: 17
2267 Please input your guess.
2269 Please input a number!
2272 Uh, what? But we did!
2274 ... actually, we didn't. See, when you get a line of input from `stdin()`,
2275 you get all the input. Including the `\n` character from you pressing Enter.
2276 So, `from_str()` sees the string `"5\n"` and says "nope, that's not a number,
2277 there's non-number stuff in there!" Luckily for us, `&str`s have an easy
2278 method we can use defined on them: `trim()`. One small modification, and our
2279 code looks like this:
2286 println!("Guess the number!");
2288 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2290 println!("The secret number is: {}", secret_number);
2292 println!("Please input your guess.");
2294 let input = io::stdin().read_line()
2296 .expect("Failed to read line");
2297 let input_num: Option<uint> = from_str(input.as_slice().trim());
2299 let num = match input_num {
2302 println!("Please input a number!");
2308 println!("You guessed: {}", num);
2310 match cmp(num, secret_number) {
2311 Less => println!("Too small!"),
2312 Greater => println!("Too big!"),
2313 Equal => { println!("You win!"); },
2317 fn cmp(a: uint, b: uint) -> Ordering {
2319 else if a > b { Greater }
2328 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2329 Running `target/guessing_game`
2331 The secret number is: 58
2332 Please input your guess.
2338 Nice! You can see I even added spaces before my guess, and it still figured
2339 out that I guessed 76. Run the program a few times, and verify that guessing
2340 the number works, as well as guessing a number too small.
2342 The Rust compiler helped us out quite a bit there! This technique is called
2343 "lean on the compiler," and it's often useful when working on some code. Let
2344 the error messages help guide you towards the correct types.
2346 Now we've got most of the game working, but we can only make one guess. Let's
2347 change that by adding loops!
2351 As we already discussed, the `loop` keyword gives us an infinite loop. So
2359 println!("Guess the number!");
2361 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2363 println!("The secret number is: {}", secret_number);
2367 println!("Please input your guess.");
2369 let input = io::stdin().read_line()
2371 .expect("Failed to read line");
2372 let input_num: Option<uint> = from_str(input.as_slice().trim());
2374 let num = match input_num {
2377 println!("Please input a number!");
2383 println!("You guessed: {}", num);
2385 match cmp(num, secret_number) {
2386 Less => println!("Too small!"),
2387 Greater => println!("Too big!"),
2388 Equal => { println!("You win!"); },
2393 fn cmp(a: uint, b: uint) -> Ordering {
2395 else if a > b { Greater }
2400 And try it out. But wait, didn't we just add an infinite loop? Yup. Remember
2401 that `return`? If we give a non-number answer, we'll `return` and quit. Observe:
2405 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2406 Running `target/guessing_game`
2408 The secret number is: 59
2409 Please input your guess.
2413 Please input your guess.
2417 Please input your guess.
2421 Please input your guess.
2423 Please input a number!
2426 Ha! `quit` actually quits. As does any other non-number input. Well, this is
2427 suboptimal to say the least. First, let's actually quit when you win the game:
2434 println!("Guess the number!");
2436 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2438 println!("The secret number is: {}", secret_number);
2442 println!("Please input your guess.");
2444 let input = io::stdin().read_line()
2446 .expect("Failed to read line");
2447 let input_num: Option<uint> = from_str(input.as_slice().trim());
2449 let num = match input_num {
2452 println!("Please input a number!");
2458 println!("You guessed: {}", num);
2460 match cmp(num, secret_number) {
2461 Less => println!("Too small!"),
2462 Greater => println!("Too big!"),
2464 println!("You win!");
2471 fn cmp(a: uint, b: uint) -> Ordering {
2473 else if a > b { Greater }
2478 By adding the `return` line after the `You win!`, we'll exit the program when
2479 we win. We have just one more tweak to make: when someone inputs a non-number,
2480 we don't want to quit, we just want to ignore it. Change that `return` to
2489 println!("Guess the number!");
2491 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2493 println!("The secret number is: {}", secret_number);
2497 println!("Please input your guess.");
2499 let input = io::stdin().read_line()
2501 .expect("Failed to read line");
2502 let input_num: Option<uint> = from_str(input.as_slice().trim());
2504 let num = match input_num {
2507 println!("Please input a number!");
2513 println!("You guessed: {}", num);
2515 match cmp(num, secret_number) {
2516 Less => println!("Too small!"),
2517 Greater => println!("Too big!"),
2519 println!("You win!");
2526 fn cmp(a: uint, b: uint) -> Ordering {
2528 else if a > b { Greater }
2533 Now we should be good! Let's try:
2537 Compiling guessing_game v0.0.1 (file:///home/you/projects/guessing_game)
2538 Running `target/guessing_game`
2540 The secret number is: 61
2541 Please input your guess.
2545 Please input your guess.
2549 Please input your guess.
2551 Please input a number!
2552 Please input your guess.
2558 Awesome! With one tiny last tweak, we have finished the guessing game. Can you
2559 think of what it is? That's right, we don't want to print out the secret number.
2560 It was good for testing, but it kind of ruins the game. Here's our final source:
2567 println!("Guess the number!");
2569 let secret_number = (rand::random::<uint>() % 100u) + 1u;
2573 println!("Please input your guess.");
2575 let input = io::stdin().read_line()
2577 .expect("Failed to read line");
2578 let input_num: Option<uint> = from_str(input.as_slice().trim());
2580 let num = match input_num {
2583 println!("Please input a number!");
2589 println!("You guessed: {}", num);
2591 match cmp(num, secret_number) {
2592 Less => println!("Too small!"),
2593 Greater => println!("Too big!"),
2595 println!("You win!");
2602 fn cmp(a: uint, b: uint) -> Ordering {
2604 else if a > b { Greater }
2611 At this point, you have successfully built the Guessing Game! Congratulations!
2613 You've now learned the basic syntax of Rust. All of this is relatively close to
2614 various other programming languages you have used in the past. These
2615 fundamental syntactical and semantic elements will form the foundation for the
2616 rest of your Rust education.
2618 Now that you're an expert at the basics, it's time to learn about some of
2619 Rust's more unique features.
2621 # Crates and Modules
2623 Rust features a strong module system, but it works a bit differently than in
2624 other programming languages. Rust's module system has two main components:
2625 **crate**s, and **module**s.
2627 A crate is Rust's unit of independent compilation. Rust always compiles one
2628 crate at a time, producing either a library or an executable. However, executables
2629 usually depend on libraries, and many libraries depend on other libraries as well.
2630 To support this, crates can depend on other crates.
2632 Each crate contains a hierarchy of modules. This tree starts off with a single
2633 module, called the **crate root**. Within the crate root, we can declare other
2634 modules, which can contain other modules, as deeply as you'd like.
2636 Note that we haven't mentioned anything about files yet. Rust does not impose a
2637 particular relationship between your filesystem structure and your module
2638 structure. That said, there is a conventional approach to how Rust looks for
2639 modules on the file system, but it's also overridable.
2641 Enough talk, let's build something! Let's make a new project called `modules`.
2645 $ cargo new modules --bin
2648 Let's double check our work by compiling:
2652 Compiling modules v0.0.1 (file:///home/you/projects/modules)
2653 Running `target/modules`
2657 Excellent! So, we already have a single crate here: our `src/main.rs` is a crate.
2658 Everything in that file is in the crate root. A crate that generates an executable
2659 defines a `main` function inside its root, as we've done here.
2661 Let's define a new module inside our crate. Edit `src/main.rs` to look
2666 println!("Hello, world!");
2671 println!("Hello, world!");
2676 We now have a module named `hello` inside of our crate root. Modules use
2677 `snake_case` naming, like functions and variable bindings.
2679 Inside the `hello` module, we've defined a `print_hello` function. This will
2680 also print out our hello world message. Modules allow you to split up your
2681 program into nice neat boxes of functionality, grouping common things together,
2682 and keeping different things apart. It's kinda like having a set of shelves:
2683 a place for everything and everything in its place.
2685 To call our `print_hello` function, we use the double colon (`::`):
2688 hello::print_hello();
2691 You've seen this before, with `io::stdin()` and `rand::random()`. Now you know
2692 how to make your own. However, crates and modules have rules about
2693 **visibility**, which controls who exactly may use the functions defined in a
2694 given module. By default, everything in a module is private, which means that
2695 it can only be used by other functions in the same module. This will not
2700 hello::print_hello();
2705 println!("Hello, world!");
2713 Compiling modules v0.0.1 (file:///home/you/projects/modules)
2714 src/main.rs:2:5: 2:23 error: function `print_hello` is private
2715 src/main.rs:2 hello::print_hello();
2719 To make it public, we use the `pub` keyword:
2723 hello::print_hello();
2727 pub fn print_hello() {
2728 println!("Hello, world!");
2737 Compiling modules v0.0.1 (file:///home/you/projects/modules)
2738 Running `target/modules`
2742 Nice! There are more things we can do with modules, including moving them into
2743 their own files. This is enough detail for now.
2747 Traditionally, testing has not been a strong suit of most systems programming
2748 languages. Rust, however, has very basic testing built into the language
2749 itself. While automated testing cannot prove that your code is bug-free, it is
2750 useful for verifying that certain behaviors work as intended.
2752 Here's a very basic test:
2756 fn is_one_equal_to_one() {
2761 You may notice something new: that `#[test]`. Before we get into the mechanics
2762 of testing, let's talk about attributes.
2766 Rust's testing system uses **attribute**s to mark which functions are tests.
2767 Attributes can be placed on any Rust **item**. Remember how most things in
2768 Rust are an expression, but `let` is not? Item declarations are also not
2769 expressions. Here's a list of things that qualify as an item:
2780 You haven't learned about all of these things yet, but that's the list. As
2781 you can see, functions are at the top of it.
2783 Attributes can appear in three ways:
2785 1. A single identifier, the attribute name. `#[test]` is an example of this.
2786 2. An identifier followed by an equals sign (`=`) and a literal. `#[cfg=test]`
2787 is an example of this.
2788 3. An identifier followed by a parenthesized list of sub-attribute arguments.
2789 `#[cfg(unix, target_word_size = "32")]` is an example of this, where one of
2790 the sub-arguments is of the second kind.
2792 There are a number of different kinds of attributes, enough that we won't go
2793 over them all here. Before we talk about the testing-specific attributes, I
2794 want to call out one of the most important kinds of attributes: stability
2797 ## Stability attributes
2799 Rust provides six attributes to indicate the stability level of various
2800 parts of your library. The six levels are:
2802 * deprecated: This item should no longer be used. No guarantee of backwards
2804 * experimental: This item was only recently introduced or is otherwise in a
2805 state of flux. It may change significantly, or even be removed. No guarantee
2806 of backwards-compatibility.
2807 * unstable: This item is still under development, but requires more testing to
2808 be considered stable. No guarantee of backwards-compatibility.
2809 * stable: This item is considered stable, and will not change significantly.
2810 Guarantee of backwards-compatibility.
2811 * frozen: This item is very stable, and is unlikely to change. Guarantee of
2812 backwards-compatibility.
2813 * locked: This item will never change unless a serious bug is found. Guarantee
2814 of backwards-compatibility.
2816 All of Rust's standard library uses these attribute markers to communicate
2817 their relative stability, and you should use them in your code, as well.
2818 There's an associated attribute, `warn`, that allows you to warn when you
2819 import an item marked with certain levels: deprecated, experimental and
2820 unstable. For now, only deprecated warns by default, but this will change once
2821 the standard library has been stabilized.
2823 You can use the `warn` attribute like this:
2829 And later, when you import a crate:
2832 extern crate some_crate;
2835 You'll get a warning if you use something marked unstable.
2837 You may have noticed an exclamation point in the `warn` attribute declaration.
2838 The `!` in this attribute means that this attribute applies to the enclosing
2839 item, rather than to the item that follows the attribute. So this `warn`
2840 attribute declaration applies to the enclosing crate itself, rather than
2841 to whatever item statement follows it:
2844 // applies to the crate we're in
2847 extern crate some_crate;
2849 // applies to the following `fn`.
2858 Let's write a very simple crate in a test-driven manner. You know the drill by
2859 now: make a new project:
2863 $ cargo new testing --bin
2871 Compiling testing v0.0.1 (file:///home/you/projects/testing)
2872 Running `target/testing`
2876 Great. Rust's infrastructure supports tests in two sorts of places, and they're
2877 for two kinds of tests: you include **unit test**s inside of the crate itself,
2878 and you place **integration test**s inside a `tests` directory. "Unit tests"
2879 are small tests that test one focused unit, "integration tests" tests multiple
2880 units in integration. That said, this is a social convention, they're no different
2881 in syntax. Let's make a `tests` directory:
2887 Next, let's create an integration test in `tests/lib.rs`:
2896 It doesn't matter what you name your test functions, though it's nice if
2897 you give them descriptive names. You'll see why in a moment. We then use a
2898 macro, `assert!`, to assert that something is true. In this case, we're giving
2899 it `false`, so this test should fail. Let's try it!
2903 Compiling testing v0.0.1 (file:///home/you/projects/testing)
2904 /home/you/projects/testing/src/main.rs:1:1: 3:2 warning: code is never used: `main`, #[warn(dead_code)] on by default
2905 /home/you/projects/testing/src/main.rs:1 fn main() {
2906 /home/you/projects/testing/src/main.rs:2 println!("Hello, world");
2907 /home/you/projects/testing/src/main.rs:3 }
2911 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
2919 ---- foo stdout ----
2920 task 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
2927 test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
2929 task '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:242
2932 Lots of output! Let's break this down:
2936 Compiling testing v0.0.1 (file:///home/you/projects/testing)
2939 You can run all of your tests with `cargo test`. This runs both your tests in
2940 `tests`, as well as the tests you put inside of your crate.
2943 /home/you/projects/testing/src/main.rs:1:1: 3:2 warning: code is never used: `main`, #[warn(dead_code)] on by default
2944 /home/you/projects/testing/src/main.rs:1 fn main() {
2945 /home/you/projects/testing/src/main.rs:2 println!("Hello, world");
2946 /home/you/projects/testing/src/main.rs:3 }
2949 Rust has a **lint** called 'warn on dead code' used by default. A lint is a
2950 bit of code that checks your code, and can tell you things about it. In this
2951 case, Rust is warning us that we've written some code that's never used: our
2952 `main` function. Of course, since we're running tests, we don't use `main`.
2953 We'll turn this lint off for just this function soon. For now, just ignore this
2959 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
2962 Wait a minute, zero tests? Didn't we define one? Yup. This output is from
2963 attempting to run the tests in our crate, of which we don't have any.
2964 You'll note that Rust reports on several kinds of tests: passed, failed,
2965 ignored, and measured. The 'measured' tests refer to benchmark tests, which
2966 we'll cover soon enough!
2973 Now we're getting somewhere. Remember when we talked about naming our tests
2974 with good names? This is why. Here, it says 'test foo' because we called our
2975 test 'foo.' If we had given it a good name, it'd be more clear which test
2976 failed, especially as we accumulate more tests.
2981 ---- foo stdout ----
2982 task 'foo' failed at 'assertion failed: false', /home/you/projects/testing/tests/lib.rs:3
2989 test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured
2991 task '<main>' failed at 'Some tests failed', /home/you/src/rust/src/libtest/lib.rs:242
2994 After all the tests run, Rust will show us any output from our failed tests.
2995 In this instance, Rust tells us that our assertion failed, with false. This was
2998 Whew! Let's fix our test:
3007 And then try to run our tests again:
3011 Compiling testing v0.0.1 (file:///home/you/projects/testing)
3012 /home/you/projects/testing/src/main.rs:1:1: 3:2 warning: code is never used: `main`, #[warn(dead_code)] on by default
3013 /home/you/projects/testing/src/main.rs:1 fn main() {
3014 /home/you/projects/testing/src/main.rs:2 println!("Hello, world");
3015 /home/you/projects/testing/src/main.rs:3 }
3019 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3025 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3028 Nice! Our test passes, as we expected. Let's get rid of that warning for our `main`
3029 function. Change your `src/main.rs` to look like this:
3034 println!("Hello, world");
3038 This attribute combines two things: `cfg` and `not`. The `cfg` attribute allows
3039 you to conditionally compile code based on something. The following item will
3040 only be compiled if the configuration says it's true. And when Cargo compiles
3041 our tests, it sets things up so that `cfg(test)` is true. But we want to only
3042 include `main` when it's _not_ true. So we use `not` to negate things:
3043 `cfg(not(test))` will only compile our code when the `cfg(test)` is false.
3045 With this attribute, we won't get the warning:
3049 Compiling testing v0.0.1 (file:///home/you/projects/testing)
3053 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3059 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3062 Nice. Okay, let's write a real test now. Change your `tests/lib.rs`
3067 fn math_checks_out() {
3068 let result = add_three_times_four(5i);
3070 assert_eq!(32i, result);
3074 And try to run the test:
3078 Compiling testing v0.0.1 (file:///home/youg/projects/testing)
3079 /home/youg/projects/testing/tests/lib.rs:3:18: 3:38 error: unresolved name `add_three_times_four`.
3080 /home/youg/projects/testing/tests/lib.rs:3 let result = add_three_times_four(5i);
3081 ^~~~~~~~~~~~~~~~~~~~
3082 error: aborting due to previous error
3083 Build failed, waiting for other jobs to finish...
3084 Could not compile `testing`.
3086 To learn more, run the command again with --verbose.
3089 Rust can't find this function. That makes sense, as we didn't write it yet!
3091 In order to share this code with our tests, we'll need to make a library crate.
3092 This is also just good software design: as we mentioned before, it's a good idea
3093 to put most of your functionality into a library crate, and have your executable
3094 crate use that library. This allows for code re-use.
3096 To do that, we'll need to make a new module. Make a new file, `src/lib.rs`,
3101 pub fn add_three_times_four(x: int) -> int {
3106 We're calling this file `lib.rs` because it has the same name as our project,
3107 and so it's named this, by convention.
3109 We'll then need to use this crate in our `src/main.rs`:
3112 extern crate testing;
3116 println!("Hello, world");
3120 Finally, let's import this function in our `tests/lib.rs`:
3123 extern crate testing;
3124 use testing::add_three_times_four;
3127 fn math_checks_out() {
3128 let result = add_three_times_four(5i);
3130 assert_eq!(32i, result);
3134 Let's give it a run:
3138 Compiling testing v0.0.1 (file:///home/you/projects/testing)
3142 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3147 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3151 test math_checks_out ... ok
3153 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3156 Great! One test passed. We've got an integration test showing that our public
3157 method works, but maybe we want to test some of the internal logic as well.
3158 While this function is simple, if it were more complicated, you can imagine
3159 we'd need more tests. So let's break it up into two helper functions, and
3160 write some unit tests to test those.
3162 Change your `src/lib.rs` to look like this:
3165 pub fn add_three_times_four(x: int) -> int {
3166 times_four(add_three(x))
3169 fn add_three(x: int) -> int { x + 3 }
3171 fn times_four(x: int) -> int { x * 4 }
3174 If you run `cargo test`, you should get the same output:
3178 Compiling testing v0.0.1 (file:///home/you/projects/testing)
3182 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3187 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3191 test math_checks_out ... ok
3193 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3196 If we tried to write a test for these two new functions, it wouldn't
3200 extern crate testing;
3201 use testing::add_three_times_four;
3202 use testing::add_three;
3205 fn math_checks_out() {
3206 let result = add_three_times_four(5i);
3208 assert_eq!(32i, result);
3212 fn test_add_three() {
3213 let result = add_three(5i);
3215 assert_eq!(8i, result);
3219 We'd get this error:
3222 Compiling testing v0.0.1 (file:///home/you/projects/testing)
3223 /home/you/projects/testing/tests/lib.rs:3:5: 3:24 error: function `add_three` is private
3224 /home/you/projects/testing/tests/lib.rs:3 use testing::add_three;
3228 Right. It's private. So external, integration tests won't work. We need a
3229 unit test. Open up your `src/lib.rs` and add this:
3232 pub fn add_three_times_four(x: int) -> int {
3233 times_four(add_three(x))
3236 fn add_three(x: int) -> int { x + 3 }
3238 fn times_four(x: int) -> int { x * 4 }
3242 use super::add_three;
3243 use super::times_four;
3246 fn test_add_three() {
3247 let result = add_three(5i);
3249 assert_eq!(8i, result);
3253 fn test_times_four() {
3254 let result = times_four(5i);
3256 assert_eq!(20i, result);
3261 Let's give it a shot:
3265 Compiling testing v0.0.1 (file:///home/you/projects/testing)
3268 test test::test_times_four ... ok
3269 test test::test_add_three ... ok
3271 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3276 test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
3280 test math_checks_out ... ok
3282 test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
3285 Cool! We now have two tests of our internal functions. You'll note that there
3286 are three sets of output now: one for `src/main.rs`, one for `src/lib.rs`, and
3287 one for `tests/lib.rs`. There's one interesting thing that we haven't talked
3288 about yet, and that's these lines:
3291 use super::add_three;
3292 use super::times_four;
3295 Because we've made a nested module, we can import functions from the parent
3296 module by using `super`. Sub-modules are allowed to 'see' private functions in
3297 the parent. We sometimes call this usage of `use` a 're-export,' because we're
3298 exporting the name again, somewhere else.
3300 We've now covered the basics of testing. Rust's tools are primitive, but they
3301 work well in the simple cases. There are some Rustaceans working on building
3302 more complicated frameworks on top of all of this, but they're just starting
3307 In systems programming, pointers are an incredibly important topic. Rust has a
3308 very rich set of pointers, and they operate differently than in many other
3309 languages. They are important enough that we have a specific [Pointer
3310 Guide](guide-pointers.html) that goes into pointers in much detail. In fact,
3311 while you're currently reading this guide, which covers the language in broad
3312 overview, there are a number of other guides that put a specific topic under a
3313 microscope. You can find the list of guides on the [documentation index
3314 page](index.html#guides).
3316 In this section, we'll assume that you're familiar with pointers as a general
3317 concept. If you aren't, please read the [introduction to
3318 pointers](guide-pointers.html#an-introduction) section of the Pointer Guide,
3319 and then come back here. We'll wait.
3321 Got the gist? Great. Let's talk about pointers in Rust.
3325 The most primitive form of pointer in Rust is called a **reference**.
3326 References are created using the ampersand (`&`). Here's a simple
3334 `y` is a reference to `x`. To dereference (get the value being referred to
3335 rather than the reference itself) `y`, we use the asterisk (`*`):
3344 Like any `let` binding, references are immutable by default.
3346 You can declare that functions take a reference:
3349 fn add_one(x: &int) -> int { *x + 1 }
3352 assert_eq!(6, add_one(&5));
3356 As you can see, we can make a reference from a literal by applying `&` as well.
3357 Of course, in this simple function, there's not a lot of reason to take `x` by
3358 reference. It's just an example of the syntax.
3360 Because references are immutable, you can have multiple references that
3361 **alias** (point to the same place):
3369 We can make a mutable reference by using `&mut` instead of `&`:
3376 Note that `x` must also be mutable. If it isn't, like this:
3386 6:19 error: cannot borrow immutable local variable `x` as mutable
3391 We don't want a mutable reference to immutable data! This error message uses a
3392 term we haven't talked about yet, 'borrow.' We'll get to that in just a moment.
3394 This simple example actually illustrates a lot of Rust's power: Rust has
3395 prevented us, at compile time, from breaking our own rules. Because Rust's
3396 references check these kinds of rules entirely at compile time, there's no
3397 runtime overhead for this safety. At runtime, these are the same as a raw
3398 machine pointer, like in C or C++. We've just double-checked ahead of time
3399 that we haven't done anything dangerous.
3401 Rust will also prevent us from creating two mutable references that alias.
3410 It gives us this error:
3413 error: cannot borrow `x` as mutable more than once at a time
3416 note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3419 note: previous borrow ends here
3428 This is a big error message. Let's dig into it for a moment. There are three
3429 parts: the error and two notes. The error says what we expected, we cannot have
3430 two pointers that point to the same memory.
3432 The two notes give some extra context. Rust's error messages often contain this
3433 kind of extra information when the error is complex. Rust is telling us two
3434 things: first, that the reason we cannot **borrow** `x` as `z` is that we
3435 previously borrowed `x` as `y`. The second note shows where `y`'s borrowing
3440 In order to truly understand this error, we have to learn a few new concepts:
3441 **ownership**, **borrowing**, and **lifetimes**.
3443 ## Ownership, borrowing, and lifetimes
3445 Whenever a resource of some kind is created, something must be responsible
3446 for destroying that resource as well. Given that we're discussing pointers
3447 right now, let's discuss this in the context of memory allocation, though
3448 it applies to other resources as well.
3450 When you allocate heap memory, you need a mechanism to free that memory. Many
3451 languages let the programmer control the allocation, and then use a garbage
3452 collector to handle the deallocation. This is a valid, time-tested strategy,
3453 but it's not without its drawbacks. Because the programmer does not have to
3454 think as much about deallocation, allocation becomes something commonplace,
3455 because it's easy. And if you need precise control over when something is
3456 deallocated, leaving it up to your runtime can make this difficult.
3458 Rust chooses a different path, and that path is called **ownership**. Any
3459 binding that creates a resource is the **owner** of that resource.
3461 Being an owner affords you some privileges:
3463 1. You control when that resource is deallocated.
3464 2. You may lend that resource, immutably, to as many borrowers as you'd like.
3465 3. You may lend that resource, mutably, to a single borrower.
3467 But it also comes with some restrictions:
3469 1. If someone is borrowing your resource (either mutably or immutably), you may
3470 not mutate the resource or mutably lend it to someone.
3471 2. If someone is mutably borrowing your resource, you may not lend it out at
3472 all (mutably or immutably) or access it in any way.
3474 What's up with all this 'lending' and 'borrowing'? When you allocate memory,
3475 you get a pointer to that memory. This pointer allows you to manipulate said
3476 memory. If you are the owner of a pointer, then you may allow another
3477 binding to temporarily borrow that pointer, and then they can manipulate the
3478 memory. The length of time that the borrower is borrowing the pointer
3479 from you is called a **lifetime**.
3481 If two distinct bindings share a pointer, and the memory that pointer points to
3482 is immutable, then there are no problems. But if it's mutable, both pointers
3483 can attempt to write to the memory at the same time, causing a **race
3484 condition**. Therefore, if someone wants to mutate something that they've
3485 borrowed from you, you must not have lent out that pointer to anyone else.
3487 Rust has a sophisticated system called the **borrow checker** to make sure that
3488 everyone plays by these rules. At compile time, it verifies that none of these
3489 rules are broken. If there's no problem, our program compiles successfully, and
3490 there is no runtime overhead for any of this. The borrow checker works only at
3491 compile time. If the borrow checker did find a problem, it will report a
3492 **lifetime error**, and your program will refuse to compile.
3494 That's a lot to take in. It's also one of the _most_ important concepts in
3495 all of Rust. Let's see this syntax in action:
3499 let x = 5i; // x is the owner of this integer, which is memory on the stack.
3501 // other code here...
3503 } // privilege 1: when x goes out of scope, this memory is deallocated
3505 /// this function borrows an integer. It's given back automatically when the
3506 /// function returns.
3507 fn foo(x: &int) -> &int { x }
3510 let x = 5i; // x is the owner of this integer, which is memory on the stack.
3512 // privilege 2: you may lend that resource, to as many borrowers as you'd like
3516 foo(&x); // functions can borrow too!
3518 let a = &x; // we can do this alllllll day!
3522 let mut x = 5i; // x is the owner of this integer, which is memory on the stack.
3524 let y = &mut x; // privilege 3: you may lend that resource to a single borrower,
3529 If you are a borrower, you get a few privileges as well, but must also obey a
3532 1. If the borrow is immutable, you may read the data the pointer points to.
3533 2. If the borrow is mutable, you may read and write the data the pointer points to.
3534 3. You may lend the pointer to someone else in an immutable fashion, **BUT**
3535 4. When you do so, they must return it to you before you must give your own
3538 This last requirement can seem odd, but it also makes sense. If you have to
3539 return something, and you've lent it to someone, they need to give it back to
3540 you for you to give it back! If we didn't, then the owner could deallocate
3541 the memory, and the person we've loaned it out to would have a pointer to
3542 invalid memory. This is called a 'dangling pointer.'
3544 Let's re-examine the error that led us to talk about all of this, which was a
3545 violation of the restrictions placed on owners who lend something out mutably.
3557 error: cannot borrow `x` as mutable more than once at a time
3560 note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3563 note: previous borrow ends here
3572 This error comes in three parts. Let's go over each in turn.
3575 error: cannot borrow `x` as mutable more than once at a time
3580 This error states the restriction: you cannot lend out something mutable more
3581 than once at the same time. The borrow checker knows the rules!
3584 note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3589 Some compiler errors come with notes to help you fix the error. This error comes
3590 with two notes, and this is the first. This note informs us of exactly where
3591 the first mutable borrow occurred. The error showed us the second. So now we
3592 see both parts of the problem. It also alludes to rule #3, by reminding us that
3593 we can't change `x` until the borrow is over.
3596 note: previous borrow ends here
3605 Here's the second note, which lets us know where the first borrow would be over.
3606 This is useful, because if we wait to try to borrow `x` after this borrow is
3607 over, then everything will work.
3609 For more advanced patterns, please consult the [Lifetime
3610 Guide](guide-lifetimes.html). You'll also learn what this type signature with
3614 pub fn as_maybe_owned(&self) -> MaybeOwned<'a> { ... }
3619 All of our references so far have been to variables we've created on the stack.
3620 In Rust, the simplest way to allocate heap variables is using a *box*. To
3621 create a box, use the `box` keyword:
3627 This allocates an integer `5` on the heap, and creates a binding `x` that
3628 refers to it.. The great thing about boxed pointers is that we don't have to
3629 manually free this allocation! If we write
3638 then Rust will automatically free `x` at the end of the block. This isn't
3639 because Rust has a garbage collector -- it doesn't. Instead, when `x` goes out
3640 of scope, Rust `free`s `x`. This Rust code will do the same thing as the
3645 int *x = (int *)malloc(sizeof(int));
3651 This means we get the benefits of manual memory management, but the compiler
3652 ensures that we don't do something wrong. We can't forget to `free` our memory.
3654 Boxes are the sole owner of their contents, so you cannot take a mutable
3655 reference to them and then use the original box:
3661 *x; // you might expect 5, but this is actually an error
3664 This gives us this error:
3667 8:7 error: cannot use `*x` because it was mutably borrowed
3670 6:19 note: borrow of `x` occurs here
3675 As long as `y` is borrowing the contents, we cannot use `x`. After `y` is
3676 done borrowing the value, we can use it again. This works fine:
3683 } // y goes out of scope at the end of the block
3690 Sometimes, you need to allocate something on the heap, but give out multiple
3691 references to the memory. Rust's `Rc<T>` (pronounced 'arr cee tee') and
3692 `Arc<T>` types (again, the `T` is for generics, we'll learn more later) provide
3693 you with this ability. **Rc** stands for 'reference counted,' and **Arc** for
3694 'atomically reference counted.' This is how Rust keeps track of the multiple
3695 owners: every time we make a new reference to the `Rc<T>`, we add one to its
3696 internal 'reference count.' Every time a reference goes out of scope, we
3697 subtract one from the count. When the count is zero, the `Rc<T>` can be safely
3698 deallocated. `Arc<T>` is almost identical to `Rc<T>`, except for one thing: The
3699 'atomically' in 'Arc' means that increasing and decreasing the count uses a
3700 thread-safe mechanism to do so. Why two types? `Rc<T>` is faster, so if you're
3701 not in a multi-threaded scenario, you can have that advantage. Since we haven't
3702 talked about threading yet in Rust, we'll show you `Rc<T>` for the rest of this
3705 To create an `Rc<T>`, use `Rc::new()`:
3710 let x = Rc::new(5i);
3713 To create a second reference, use the `.clone()` method:
3718 let x = Rc::new(5i);
3722 The `Rc<T>` will live as long as any of its references are alive. After they
3723 all go out of scope, the memory will be `free`d.
3725 If you use `Rc<T>` or `Arc<T>`, you have to be careful about introducing
3726 cycles. If you have two `Rc<T>`s that point to each other, the reference counts
3727 will never drop to zero, and you'll have a memory leak. To learn more, check
3728 out [the section on `Rc<T>` and `Arc<T>` in the pointers
3729 guide](http://doc.rust-lang.org/guide-pointers.html#rc-and-arc).
3733 We've made use of patterns a few times in the guide: first with `let` bindings,
3734 then with `match` statements. Let's go on a whirlwind tour of all of the things
3737 A quick refresher: you can match against literals directly, and `_` acts as an
3744 1 => println!("one"),
3745 2 => println!("two"),
3746 3 => println!("three"),
3747 _ => println!("anything"),
3751 You can match multiple patterns with `|`:
3757 1 | 2 => println!("one or two"),
3758 3 => println!("three"),
3759 _ => println!("anything"),
3763 You can match a range of values with `..`:
3769 1 .. 5 => println!("one through five"),
3770 _ => println!("anything"),
3774 Ranges are mostly used with integers and single characters.
3776 If you're matching multiple things, via a `|` or a `..`, you can bind
3777 the value to a name with `@`:
3783 x @ 1 .. 5 => println!("got {}", x),
3784 _ => println!("anything"),
3788 If you're matching on an enum which has variants, you can use `..` to
3789 ignore the value in the variant:
3800 Value(..) => println!("Got an int!"),
3801 Missing => println!("No such luck."),
3805 You can introduce **match guards** with `if`:
3816 Value(x) if x > 5 => println!("Got an int bigger than five!"),
3817 Value(..) => println!("Got an int!"),
3818 Missing => println!("No such luck."),
3822 If you're matching on a pointer, you can use the same syntax as you declared it
3829 &x => println!("Got a value: {}", x),
3833 Here, the `x` inside the `match` has type `int`. In other words, the left hand
3834 side of the pattern destructures the value. If we have `&5i`, then in `&x`, `x`
3837 If you want to get a reference, use the `ref` keyword:
3843 ref x => println!("Got a reference to {}", x),
3847 Here, the `x` inside the `match` has the type `&int`. In other words, the `ref`
3848 keyword _creates_ a reference, for use in the pattern. If you need a mutable
3849 reference, `ref mut` will work in the same way:
3855 ref mut x => println!("Got a mutable reference to {}", x),
3859 If you have a struct, you can destructure it inside of a pattern:
3867 let origin = Point { x: 0i, y: 0i };
3870 Point { x: x, y: y } => println!("({},{})", x, y),
3874 If we only care about some of the values, we don't have to give them all names:
3882 let origin = Point { x: 0i, y: 0i };
3885 Point { x: x, .. } => println!("x is {}", x),
3889 Whew! That's a lot of different ways to match things, and they can all be
3890 mixed and matched, depending on what you're doing:
3894 Foo { x: Some(ref name), y: None } => ...
3898 Patterns are very powerful. Make good use of them.
3902 Functions are great, but if you want to call a bunch of them on some data, it
3903 can be awkward. Consider this code:
3909 We would read this left-to right, and so we see 'baz bar foo.' But this isn't the
3910 order that the functions would get called in, that's inside-out: 'foo bar baz.'
3911 Wouldn't it be nice if we could do this instead?
3914 x.foo().bar().baz();
3917 Luckily, as you may have guessed with the leading question, you can! Rust provides
3918 the ability to use this **method call syntax** via the `impl` keyword.
3920 Here's how it works:
3930 fn area(&self) -> f64 {
3931 std::f64::consts::PI * (self.radius * self.radius)
3936 let c = Circle { x: 0.0, y: 0.0, radius: 2.0 };
3937 println!("{}", c.area());
3941 This will print `12.566371`.
3943 We've made a struct that represents a circle. We then write an `impl` block,
3944 and inside it, define a method, `area`. Methods take a special first
3945 parameter, `&self`. There are three variants: `self`, `&self`, and `&mut self`.
3946 You can think of this first parameter as being the `x` in `x.foo()`. The three
3947 variants correspond to the three kinds of thing `x` could be: `self` if it's
3948 just a value on the stack, `&self` if it's a reference, and `&mut self` if it's
3949 a mutable reference. We should default to using `&self`, as it's the most
3952 Finally, as you may remember, the value of the area of a circle is `π*r²`.
3953 Because we took the `&self` parameter to `area`, we can use it just like any
3954 other parameter. Because we know it's a `Circle`, we can access the `radius`
3955 just like we would with any other struct. An import of π and some
3956 multiplications later, and we have our area.
3958 You can also define methods that do not take a `self` parameter. Here's a
3959 pattern that's very common in Rust code:
3969 fn new(x: f64, y: f64, radius: f64) -> Circle {
3979 let c = Circle::new(0.0, 0.0, 2.0);
3983 This **static method** builds a new `Circle` for us. Note that static methods
3984 are called with the `Struct::method()` syntax, rather than the `ref.method()`
3989 So far, we've made lots of functions in Rust. But we've given them all names.
3990 Rust also allows us to create anonymous functions too. Rust's anonymous
3991 functions are called **closure**s. By themselves, closures aren't all that
3992 interesting, but when you combine them with functions that take closures as
3993 arguments, really powerful things are possible.
3995 Let's make a closure:
3998 let add_one = |x| { 1i + x };
4000 println!("The 5 plus 1 is {}.", add_one(5i));
4003 We create a closure using the `|...| { ... }` syntax, and then we create a
4004 binding so we can use it later. Note that we call the function using the
4005 binding name and two parentheses, just like we would for a named function.
4007 Let's compare syntax. The two are pretty close:
4010 let add_one = |x: int| -> int { 1i + x };
4011 fn add_one (x: int) -> int { 1i + x }
4014 As you may have noticed, closures infer their argument and return types, so you
4015 don't need to declare one. This is different from named functions, which
4016 default to returning unit (`()`).
4018 There's one big difference between a closure and named functions, and it's in
4019 the name: a closure "closes over its environment." What's that mean? It means
4026 let printer = || { println!("x is: {}", x); };
4028 printer(); // prints "x is: 5"
4032 The `||` syntax means this is an anonymous closure that takes no arguments.
4033 Without it, we'd just have a block of code in `{}`s.
4035 In other words, a closure has access to variables in the scope that it's
4036 defined. The closure borrows any variables that it uses. This will error:
4042 let printer = || { println!("x is: {}", x); };
4044 x = 6i; // error: cannot assign to `x` because it is borrowed
4050 Rust has a second type of closure, called a **proc**. Procs are created
4051 with the `proc` keyword:
4056 let p = proc() { x * x };
4057 println!("{}", p()); // prints 25
4060 Procs have a big difference from closures: they may only be called once. This
4061 will error when we try to compile:
4066 let p = proc() { x * x };
4067 println!("{}", p());
4068 println!("{}", p()); // error: use of moved value `p`
4071 This restriction is important. Procs are allowed to consume values that they
4072 capture, and thus have to be restricted to being called once for soundness
4073 reasons: any value consumed would be invalid on a second call.
4075 Procs are most useful with Rust's concurrency features, and so we'll just leave
4076 it at this for now. We'll talk about them more in the "Tasks" section of the
4079 ## Accepting closures as arguments
4081 Closures are most useful as an argument to another function. Here's an example:
4084 fn twice(x: int, f: |int| -> int) -> int {
4089 let square = |x: int| { x * x };
4091 twice(5i, square); // evaluates to 50
4095 Let's break example down, starting with `main`:
4098 let square = |x: int| { x * x };
4101 We've seen this before. We make a closure that takes an integer, and returns
4105 twice(5i, square); // evaluates to 50
4108 This line is more interesting. Here, we call our function, `twice`, and we pass
4109 it two arguments: an integer, `5`, and our closure, `square`. This is just like
4110 passing any other two variable bindings to a function, but if you've never
4111 worked with closures before, it can seem a little complex. Just think: "I'm
4112 passing two variables, one is an int, and one is a function."
4114 Next, let's look at how `twice` is defined:
4117 fn twice(x: int, f: |int| -> int) -> int {
4120 `twice` takes two arguments, `x` and `f`. That's why we called it with two
4121 arguments. `x` is an `int`, we've done that a ton of times. `f` is a function,
4122 though, and that function takes an `int` and returns an `int`. Notice
4123 how the `|int| -> int` syntax looks a lot like our definition of `square`
4124 above, if we added the return type in:
4127 let square = |x: int| -> int { x * x };
4131 This function takes an `int` and returns an `int`.
4133 This is the most complicated function signature we've seen yet! Give it a read
4134 a few times until you can see how it works. It takes a teeny bit of practice, and
4137 Finally, `twice` returns an `int` as well.
4139 Okay, let's look at the body of `twice`:
4142 fn twice(x: int, f: |int| -> int) -> int {
4147 Since our closure is named `f`, we can call it just like we called our closures
4148 before. And we pass in our `x` argument to each one. Hence 'twice.'
4150 If you do the math, `(5 * 5) + (5 * 5) == 50`, so that's the output we get.
4152 Play around with this concept until you're comfortable with it. Rust's standard
4153 library uses lots of closures, where appropriate, so you'll be using
4154 this technique a lot.
4156 If we didn't want to give `square` a name, we could also just define it inline.
4157 This example is the same as the previous one:
4160 fn twice(x: int, f: |int| -> int) -> int {
4165 twice(5i, |x: int| { x * x }); // evaluates to 50
4169 A named function's name can be used wherever you'd use a closure. Another
4170 way of writing the previous example:
4173 fn twice(x: int, f: |int| -> int) -> int {
4177 fn square(x: int) -> int { x * x }
4180 twice(5i, square); // evaluates to 50
4184 Doing this is not particularly common, but every once in a while, it's useful.
4186 That's all you need to get the hang of closures! Closures are a little bit
4187 strange at first, but once you're used to using them, you'll miss them in any
4188 language that doesn't have them. Passing functions to other functions is
4189 incredibly powerful. Next, let's look at one of those things: iterators.
4193 Let's talk about loops.
4195 Remember Rust's `for` loop? Here's an example:
4198 for x in range(0i, 10i) {
4199 println!("{:d}", x);
4203 Now that you know more Rust, we can talk in detail about how this works. The
4204 `range` function returns an **iterator**. An iterator is something that we can
4205 call the `.next()` method on repeatedly, and it gives us a sequence of things.
4210 let mut range = range(0i, 10i);
4213 match range.next() {
4222 We make a mutable binding to the return value of `range`, which is our iterator.
4223 We then `loop`, with an inner `match`. This `match` is used on the result of
4224 `range.next()`, which gives us a reference to the next value of the iterator.
4225 `next` returns an `Option<int>`, in this case, which will be `Some(int)` when
4226 we have a value and `None` once we run out. If we get `Some(int)`, we print it
4227 out, and if we get `None`, we `break` out of the loop.
4229 This code sample is basically the same as our `for` loop version. The `for`
4230 loop is just a handy way to write this `loop`/`match`/`break` construct.
4232 `for` loops aren't the only thing that uses iterators, however. Writing your
4233 own iterator involves implementing the `Iterator` trait. While doing that is
4234 outside of the scope of this guide, Rust provides a number of useful iterators
4235 to accomplish various tasks. Before we talk about those, we should talk about a
4236 Rust anti-pattern. And that's `range`.
4238 Yes, we just talked about how `range` is cool. But `range` is also very
4239 primitive. For example, if you needed to iterate over the contents of
4240 a vector, you may be tempted to write this:
4243 let nums = vec![1i, 2i, 3i];
4245 for i in range(0u, nums.len()) {
4246 println!("{}", nums[i]);
4250 This is strictly worse than using an actual iterator. The `.iter()` method on
4251 vectors returns an iterator which iterates through a reference to each element
4252 of the vector in turn. So write this:
4255 let nums = vec![1i, 2i, 3i];
4257 for num in nums.iter() {
4258 println!("{}", num);
4262 There are two reasons for this. First, this more directly expresses what we
4263 mean. We iterate through the entire vector, rather than iterating through
4264 indexes, and then indexing the vector. Second, this version is more efficient:
4265 the first version will have extra bounds checking because it used indexing,
4266 `nums[i]`. But since we yield a reference to each element of the vector in turn
4267 with the iterator, there's no bounds checking in the second example. This is
4268 very common with iterators: we can ignore unnecessary bounds checks, but still
4269 know that we're safe.
4271 There's another detail here that's not 100% clear because of how `println!`
4272 works. `num` is actually of type `&int`. That is, it's a reference to an `int`,
4273 not an `int` itself. `println!` handles the dereferencing for us, so we don't
4274 see it. This code works fine too:
4277 let nums = vec![1i, 2i, 3i];
4279 for num in nums.iter() {
4280 println!("{}", *num);
4284 Now we're explicitly dereferencing `num`. Why does `iter()` give us references?
4285 Well, if it gave us the data itself, we would have to be its owner, which would
4286 involve making a copy of the data and giving us the copy. With references,
4287 we're just borrowing a reference to the data, and so it's just passing
4288 a reference, without needing to do the copy.
4290 So, now that we've established that `range` is often not what you want, let's
4291 talk about what you do want instead.
4293 There are three broad classes of things that are relevant here: iterators,
4294 **iterator adapters**, and **consumers**. Here's some definitions:
4296 * 'iterators' give you a sequence of values.
4297 * 'iterator adapters' operate on an iterator, producing a new iterator with a
4298 different output sequence.
4299 * 'consumers' operate on an iterator, producing some final set of values.
4301 Let's talk about consumers first, since you've already seen an iterator,
4306 A 'consumer' operates on an iterator, returning some kind of value or values.
4307 The most common consumer is `collect()`. This code doesn't quite compile,
4308 but it shows the intention:
4311 let one_to_one_hundred = range(0i, 100i).collect();
4314 As you can see, we call `collect()` on our iterator. `collect()` takes
4315 as many values as the iterator will give it, and returns a collection
4316 of the results. So why won't this compile? Rust can't determine what
4317 type of things you want to collect, and so you need to let it know.
4318 Here's the version that does compile:
4321 let one_to_one_hundred = range(0i, 100i).collect::<Vec<int>>();
4324 If you remember, the `::<>` syntax allows us to give a type hint,
4325 and so we tell it that we want a vector of integers.
4327 `collect()` is the most common consumer, but there are others too. `find()`
4331 let one_to_one_hundred = range(0i, 100i);
4333 let greater_than_forty_two = range(0i, 100i)
4334 .find(|x| *x >= 42);
4336 match greater_than_forty_two {
4337 Some(_) => println!("We got some numbers!"),
4338 None => println!("No numbers found :("),
4342 `find` takes a closure, and works on a reference to each element of an
4343 iterator. This closure returns `true` if the element is the element we're
4344 looking for, and `false` otherwise. Because we might not find a matching
4345 element, `find` returns an `Option` rather than the element itself.
4347 Another important consumer is `fold`. Here's what it looks like:
4350 let sum = range(1i, 100i)
4351 .fold(0i, |sum, x| sum + x);
4354 `fold()` is a consumer that looks like this:
4355 `fold(base, |accumulator, element| ...)`. It takes two arguments: the first
4356 is an element called the "base". The second is a closure that itself takes two
4357 arguments: the first is called the "accumulator," and the second is an
4358 "element." Upon each iteration, the closure is called, and the result is the
4359 value of the accumulator on the next iteration. On the first iteration, the
4360 base is the value of the accumulator.
4362 Okay, that's a bit confusing. Let's examine the values of all of these things
4365 | base | accumulator | element | closure result |
4366 |------|-------------|---------|----------------|
4367 | 0i | 0i | 1i | 1i |
4368 | 0i | 1i | 2i | 3i |
4369 | 0i | 3i | 3i | 6i |
4371 We called `fold()` with these arguments:
4375 .fold(0i, |sum, x| sum + x);
4378 So, `0i` is our base, `sum` is our accumulator, and `x` is our element. On the
4379 first iteration, we set `sum` to `0i`, and `x` is the first element of `nums`,
4380 `1i`. We then add `sum` and `x`, which gives us `0i + 1i = 1i`. On the second
4381 iteration, that value becomes our accumulator, `sum`, and the element is
4382 the second element of the array, `2i`. `1i + 2i = 3i`, and so that becomes
4383 the value of the accumulator for the last iteration. On that iteration,
4384 `x` is the last element, `3i`, and `3i + 3i = 6i`, which is our final
4385 result for our sum. `1 + 2 + 3 = 6`, and that's the result we got.
4387 Whew. `fold` can be a bit strange the first few times you see it, but once it
4388 clicks, you can use it all over the place. Any time you have a list of things,
4389 and you want a single result, `fold` is appropriate.
4391 Consumers are important due to one additional property of iterators we haven't
4392 talked about yet: laziness. Let's talk some more about iterators, and you'll
4393 see why consumers matter.
4397 As we've said before, an iterator is something that we can call the `.next()`
4398 method on repeatedly, and it gives us a sequence of things. Because you need
4399 to call the method, this means that iterators are **lazy**. This code, for
4400 example, does not actually generate the numbers `1-100`, and just creates a
4401 value that represents the sequence:
4404 let nums = range(1i, 100i);
4407 Since we didn't do anything with the range, it didn't generate the sequence.
4408 Once we add the consumer:
4411 let nums = range(1i, 100i).collect::<Vec<int>>();
4414 Now, `collect()` will require that `range()` give it some numbers, and so
4415 it will do the work of generating the sequence.
4417 `range` is one of two basic iterators that you'll see. The other is `iter()`,
4418 which you've used before. `iter()` can turn a vector into a simple iterator
4419 that gives you each element in turn:
4422 let nums = [1i, 2i, 3i];
4424 for num in nums.iter() {
4425 println!("{}", num);
4429 These two basic iterators should serve you well. There are some more
4430 advanced iterators, including ones that are infinite. Like `count`:
4433 std::iter::count(1i, 5i);
4436 This iterator counts up from one, adding five each time. It will give
4437 you a new integer every time, forever. Well, technically, until the
4438 maximum number that an `int` can represent. But since iterators are lazy,
4439 that's okay! You probably don't want to use `collect()` on it, though...
4441 That's enough about iterators. Iterator adapters are the last concept
4442 we need to talk about with regards to iterators. Let's get to it!
4444 ## Iterator adapters
4446 "Iterator adapters" take an iterator and modify it somehow, producing
4447 a new iterator. The simplest one is called `map`:
4450 range(1i, 100i).map(|x| x + 1i);
4453 `map` is called upon another iterator, and produces a new iterator where each
4454 element reference has the closure it's been given as an argument called on it.
4455 So this would give us the numbers from `2-101`. Well, almost! If you
4456 compile the example, you'll get a warning:
4459 2:37 warning: unused result which must be used: iterator adaptors are lazy and
4460 do nothing unless consumed, #[warn(unused_must_use)] on by default
4461 range(1i, 100i).map(|x| x + 1i);
4462 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4465 Laziness strikes again! That closure will never execute. This example
4466 doesn't print any numbers:
4469 range(1i, 100i).map(|x| println!("{}", x));
4472 If you are trying to execute a closure on an iterator for its side effects,
4473 just use `for` instead.
4475 There are tons of interesting iterator adapters. `take(n)` will get the
4476 first `n` items out of an iterator, and return them as a list. Let's
4477 try it out with our infinite iterator from before, `count()`:
4480 for i in std::iter::count(1i, 5i).take(5) {
4495 `filter()` is an adapter that takes a closure as an argument. This closure
4496 returns `true` or `false`. The new iterator `filter()` produces returns
4497 only the elements that that closure returned `true` for:
4500 for i in range(1i, 100i).filter(|x| x % 2 == 0) {
4505 This will print all of the even numbers between one and a hundred.
4507 You can chain all three things together: start with an iterator, adapt it
4508 a few times, and then consume the result. Check it out:
4512 .filter(|x| x % 2 == 0)
4513 .filter(|x| x % 3 == 0)
4515 .collect::<Vec<int>>();
4518 This will give you a vector containing `6`, `12`, `18`, `24`, and `30`.
4520 This is just a small taste of what iterators, iterator adapters, and consumers
4521 can help you with. There are a number of really useful iterators, and you can
4522 write your own as well. Iterators provide a safe, efficient way to manipulate
4523 all kinds of lists. They're a little unusual at first, but if you play with
4524 them, you'll get hooked. For a full list of the different iterators and
4525 consumers, check out the [iterator module documentation](std/iter/index.html).
4529 Sometimes, when writing a function or data type, we may want it to work for
4530 multiple types of arguments. For example, remember our `OptionalInt` type?
4539 If we wanted to also have an `OptionalFloat64`, we would need a new enum:
4542 enum OptionalFloat64 {
4548 This is really unfortunate. Luckily, Rust has a feature that gives us a better
4549 way: generics. Generics are called **parametric polymorphism** in type theory,
4550 which means that they are types or functions that have multiple forms ("poly"
4551 is multiple, "morph" is form) over a given parameter ("parametric").
4553 Anyway, enough with type theory declarations, let's check out the generic form
4554 of `OptionalInt`. It is actually provided by Rust itself, and looks like this:
4563 The `<T>` part, which you've seen a few times before, indicates that this is
4564 a generic data type. Inside the declaration of our enum, wherever we see a `T`,
4565 we substitute that type for the same type used in the generic. Here's an
4566 example of using `Option<T>`, with some extra type annotations:
4569 let x: Option<int> = Some(5i);
4572 In the type declaration, we say `Option<int>`. Note how similar this looks to
4573 `Option<T>`. So, in this particular `Option`, `T` has the value of `int`. On
4574 the right hand side of the binding, we do make a `Some(T)`, where `T` is `5i`.
4575 Since that's an `int`, the two sides match, and Rust is happy. If they didn't
4576 match, we'd get an error:
4579 let x: Option<f64> = Some(5i);
4580 // error: mismatched types: expected `core::option::Option<f64>`
4581 // but found `core::option::Option<int>` (expected f64 but found int)
4584 That doesn't mean we can't make `Option<T>`s that hold an `f64`! They just have to
4588 let x: Option<int> = Some(5i);
4589 let y: Option<f64> = Some(5.0f64);
4592 This is just fine. One definition, multiple uses.
4594 Generics don't have to only be generic over one type. Consider Rust's built-in
4595 `Result<T, E>` type:
4604 This type is generic over _two_ types: `T` and `E`. By the way, the capital letters
4605 can be any letter you'd like. We could define `Result<T, E>` as:
4614 if we wanted to. Convention says that the first generic parameter should be
4615 `T`, for 'type,' and that we use `E` for 'error.' Rust doesn't care, however.
4617 The `Result<T, E>` type is intended to
4618 be used to return the result of a computation, and to have the ability to
4619 return an error if it didn't work out. Here's an example:
4622 let x: Result<f64, String> = Ok(2.3f64);
4623 let y: Result<f64, String> = Err("There was an error.".to_string());
4626 This particular Result will return an `f64` if there's a success, and a
4627 `String` if there's a failure. Let's write a function that uses `Result<T, E>`:
4630 fn inverse(x: f64) -> Result<f64, String> {
4631 if x == 0.0f64 { return Err("x cannot be zero!".to_string()); }
4637 We don't want to take the inverse of zero, so we check to make sure that we
4638 weren't passed zero. If we were, then we return an `Err`, with a message. If
4639 it's okay, we return an `Ok`, with the answer.
4641 Why does this matter? Well, remember how `match` does exhaustive matches?
4642 Here's how this function gets used:
4645 # fn inverse(x: f64) -> Result<f64, String> {
4646 # if x == 0.0f64 { return Err("x cannot be zero!".to_string()); }
4649 let x = inverse(25.0f64);
4652 Ok(x) => println!("The inverse of 25 is {}", x),
4653 Err(msg) => println!("Error: {}", msg),
4657 The `match` enforces that we handle the `Err` case. In addition, because the
4658 answer is wrapped up in an `Ok`, we can't just use the result without doing
4662 let x = inverse(25.0f64);
4663 println!("{}", x + 2.0f64); // error: binary operation `+` cannot be applied
4664 // to type `core::result::Result<f64,collections::string::String>`
4667 This function is great, but there's one other problem: it only works for 64 bit
4668 floating point values. What if we wanted to handle 32 bit floating point as
4669 well? We'd have to write this:
4672 fn inverse32(x: f32) -> Result<f32, String> {
4673 if x == 0.0f32 { return Err("x cannot be zero!".to_string()); }
4679 Bummer. What we need is a **generic function**. Luckily, we can write one!
4680 However, it won't _quite_ work yet. Before we get into that, let's talk syntax.
4681 A generic version of `inverse` would look something like this:
4684 fn inverse<T>(x: T) -> Result<T, String> {
4685 if x == 0.0 { return Err("x cannot be zero!".to_string()); }
4691 Just like how we had `Option<T>`, we use a similar syntax for `inverse<T>`.
4692 We can then use `T` inside the rest of the signature: `x` has type `T`, and half
4693 of the `Result` has type `T`. However, if we try to compile that example, we'll get
4697 error: binary operation `==` cannot be applied to type `T`
4700 Because `T` can be _any_ type, it may be a type that doesn't implement `==`,
4701 and therefore, the first line would be wrong. What do we do?
4703 To fix this example, we need to learn about another Rust feature: traits.
4707 Do you remember the `impl` keyword, used to call a function with method
4718 fn area(&self) -> f64 {
4719 std::f64::consts::PI * (self.radius * self.radius)
4724 Traits are similar, except that we define a trait with just the method
4725 signature, then implement the trait for that struct. Like this:
4735 fn area(&self) -> f64;
4738 impl HasArea for Circle {
4739 fn area(&self) -> f64 {
4740 std::f64::consts::PI * (self.radius * self.radius)
4745 As you can see, the `trait` block looks very similar to the `impl` block,
4746 but we don't define a body, just a type signature. When we `impl` a trait,
4747 we use `impl Trait for Item`, rather than just `impl Item`.
4749 So what's the big deal? Remember the error we were getting with our generic
4753 error: binary operation `==` cannot be applied to type `T`
4756 We can use traits to constrain our generics. Consider this function, which
4757 does not compile, and gives us a similar error:
4760 fn print_area<T>(shape: T) {
4761 println!("This shape has an area of {}", shape.area());
4768 error: type `T` does not implement any method in scope named `area`
4771 Because `T` can be any type, we can't be sure that it implements the `area`
4772 method. But we can add a **trait constraint** to our generic `T`, ensuring
4777 # fn area(&self) -> f64;
4779 fn print_area<T: HasArea>(shape: T) {
4780 println!("This shape has an area of {}", shape.area());
4784 The syntax `<T: HasArea>` means `any type that implements the HasArea trait`.
4785 Because traits define function type signatures, we can be sure that any type
4786 which implements `HasArea` will have an `.area()` method.
4788 Here's an extended example of how this works:
4792 fn area(&self) -> f64;
4801 impl HasArea for Circle {
4802 fn area(&self) -> f64 {
4803 std::f64::consts::PI * (self.radius * self.radius)
4813 impl HasArea for Square {
4814 fn area(&self) -> f64 {
4815 self.side * self.side
4819 fn print_area<T: HasArea>(shape: T) {
4820 println!("This shape has an area of {}", shape.area());
4841 This program outputs:
4844 This shape has an area of 3.141593
4845 This shape has an area of 1
4848 As you can see, `print_area` is now generic, but also ensures that we
4849 have passed in the correct types. If we pass in an incorrect type:
4855 We get a compile-time error:
4858 error: failed to find an implementation of trait main::HasArea for int
4861 So far, we've only added trait implementations to structs, but you can
4862 implement a trait for any type. So technically, we _could_ implement
4863 `HasArea` for `int`:
4867 fn area(&self) -> f64;
4870 impl HasArea for int {
4871 fn area(&self) -> f64 {
4872 println!("this is silly");
4881 It is considered poor style to implement methods on such primitive types, even
4882 though it is possible.
4884 This may seem like the Wild West, but there are two other restrictions around
4885 implementing traits that prevent this from getting out of hand. First, traits
4886 must be `use`d in any scope where you wish to use the trait's method. So for
4887 example, this does not work:
4891 use std::f64::consts;
4894 fn area(&self) -> f64;
4903 impl HasArea for Circle {
4904 fn area(&self) -> f64 {
4905 consts::PI * (self.radius * self.radius)
4911 let c = shapes::Circle {
4917 println!("{}", c.area());
4921 Now that we've moved the structs and traits into their own module, we get an
4925 error: type `shapes::Circle` does not implement any method in scope named `area`
4928 If we add a `use` line right above `main` and make the right things public,
4932 use shapes::HasArea;
4935 use std::f64::consts;
4938 fn area(&self) -> f64;
4947 impl HasArea for Circle {
4948 fn area(&self) -> f64 {
4949 consts::PI * (self.radius * self.radius)
4956 let c = shapes::Circle {
4962 println!("{}", c.area());
4966 This means that even if someone does something bad like add methods to `int`,
4967 it won't affect you, unless you `use` that trait.
4969 There's one more restriction on implementing traits. Either the trait or the
4970 type you're writing the `impl` for must be inside your crate. So, we could
4971 implement the `HasArea` type for `int`, because `HasArea` is in our crate. But
4972 if we tried to implement `Float`, a trait provided by Rust, for `int`, we could
4973 not, because both the trait and the type aren't in our crate.
4975 One last thing about traits: generic functions with a trait bound use
4976 **monomorphization** ("mono": one, "morph": form), so they are statically
4977 dispatched. What's that mean? Well, let's take a look at `print_area` again:
4980 fn print_area<T: HasArea>(shape: T) {
4981 println!("This shape has an area of {}", shape.area());
4985 let c = Circle { ... };
4987 let s = Square { ... };
4994 When we use this trait with `Circle` and `Square`, Rust ends up generating
4995 two different functions with the concrete type, and replacing the call sites with
4996 calls to the concrete implementations. In other words, you get something like
5000 fn __print_area_circle(shape: Circle) {
5001 println!("This shape has an area of {}", shape.area());
5004 fn __print_area_square(shape: Square) {
5005 println!("This shape has an area of {}", shape.area());
5009 let c = Circle { ... };
5011 let s = Square { ... };
5013 __print_area_circle(c);
5014 __print_area_square(s);
5018 The names don't actually change to this, it's just for illustration. But
5019 as you can see, there's no overhead of deciding which version to call here,
5020 hence 'statically dispatched.' The downside is that we have two copies of
5021 the same function, so our binary is a little bit larger.
5025 Concurrency and parallelism are topics that are of increasing interest to a
5026 broad subsection of software developers. Modern computers are often multi-core,
5027 to the point that even embedded devices like cell phones have more than one
5028 processor. Rust's semantics lend themselves very nicely to solving a number of
5029 issues that programmers have with concurrency. Many concurrency errors that are
5030 runtime errors in other languages are compile-time errors in Rust.
5032 Rust's concurrency primitive is called a **task**. Tasks are lightweight, and
5033 do not share memory in an unsafe manner, preferring message passing to
5034 communicate. It's worth noting that tasks are implemented as a library, and
5035 not part of the language. This means that in the future, other concurrency
5036 libraries can be written for Rust to help in specific scenarios. Here's an
5037 example of creating a task:
5041 println!("Hello from a task!");
5045 The `spawn` function takes a proc as an argument, and runs that proc in a new
5046 task. A proc takes ownership of its entire environment, and so any variables
5047 that you use inside the proc will not be usable afterward:
5050 let mut x = vec![1i, 2i, 3i];
5053 println!("The value of x[0] is: {}", x[0]);
5056 println!("The value of x[0] is: {}", x[0]); // error: use of moved value: `x`
5059 `x` is now owned by the proc, and so we can't use it anymore. Many other
5060 languages would let us do this, but it's not safe to do so. Rust's type system
5063 If tasks were only able to capture these values, they wouldn't be very useful.
5064 Luckily, tasks can communicate with each other through **channel**s. Channels
5068 let (tx, rx) = channel();
5071 tx.send("Hello from a task!".to_string());
5074 let message = rx.recv();
5075 println!("{}", message);
5078 The `channel()` function returns two endpoints: a `Receiver<T>` and a
5079 `Sender<T>`. You can use the `.send()` method on the `Sender<T>` end, and
5080 receive the message on the `Receiver<T>` side with the `recv()` method. This
5081 method blocks until it gets a message. There's a similar method, `.try_recv()`,
5082 which returns an `Option<T>` and does not block.
5084 If you want to send messages to the task as well, create two channels!
5087 let (tx1, rx1) = channel();
5088 let (tx2, rx2) = channel();
5091 tx1.send("Hello from a task!".to_string());
5092 let message = rx2.recv();
5093 println!("{}", message);
5096 let message = rx1.recv();
5097 println!("{}", message);
5099 tx2.send("Goodbye from main!".to_string());
5102 The proc has one sending end and one receiving end, and the main task has one
5103 of each as well. Now they can talk back and forth in whatever way they wish.
5105 Notice as well that because `Sender` and `Receiver` are generic, while you can
5106 pass any kind of information through the channel, the ends are strongly typed.
5107 If you try to pass a string, and then an integer, Rust will complain.
5111 With these basic primitives, many different concurrency patterns can be
5112 developed. Rust includes some of these types in its standard library. For
5113 example, if you wish to compute some value in the background, `Future` is
5114 a useful thing to use:
5117 use std::sync::Future;
5119 let mut delayed_value = Future::spawn(proc() {
5120 // just return anything for examples' sake
5124 println!("value = {}", delayed_value.get());
5127 Calling `Future::spawn` works just like `spawn()`: it takes a proc. In this
5128 case, though, you don't need to mess with the channel: just have the proc
5131 `Future::spawn` will return a value which we can bind with `let`. It needs
5132 to be mutable, because once the value is computed, it saves a copy of the
5133 value, and if it were immutable, it couldn't update itself.
5135 The proc will go on processing in the background, and when we need the final
5136 value, we can call `get()` on it. This will block until the result is done,
5137 but if it's finished computing in the background, we'll just get the value
5140 ## Success and failure
5142 Tasks don't always succeed, they can also fail. A task that wishes to fail
5143 can call the `fail!` macro, passing a message:
5151 If a task fails, it is not possible for it to recover. However, it can
5152 notify other tasks that it has failed. We can do this with `task::try`:
5158 let result = task::try(proc() {
5167 This task will randomly fail or succeed. `task::try` returns a `Result`
5168 type, so we can handle the response like any other computation that may
5173 One of Rust's most advanced features is its system of **macro**s. While
5174 functions allow you to provide abstractions over values and operations, macros
5175 allow you to provide abstractions over syntax. Do you wish Rust had the ability
5176 to do something that it can't currently do? You may be able to write a macro
5177 to extend Rust's capabilities.
5179 You've already used one macro extensively: `println!`. When we invoke
5180 a Rust macro, we need to use the exclamation mark (`!`). There's two reasons
5181 that this is true: the first is that it makes it clear when you're using a
5182 macro. The second is that macros allow for flexible syntax, and so Rust must
5183 be able to tell where a macro starts and ends. The `!(...)` helps with this.
5185 Let's talk some more about `println!`. We could have implemented `println!` as
5186 a function, but it would be worse. Why? Well, what macros allow you to do
5187 is write code that generates more code. So when we call `println!` like this:
5191 println!("x is: {}", x);
5194 The `println!` macro does a few things:
5196 1. It parses the string to find any `{}`s
5197 2. It checks that the number of `{}`s matches the number of other arguments.
5198 3. It generates a bunch of Rust code, taking this in mind.
5200 What this means is that you get type checking at compile time, because
5201 Rust will generate code that takes all of the types into account. If
5202 `println!` was a function, it could still do this type checking, but it
5203 would happen at run time rather than compile time.
5205 We can check this out using a special flag to `rustc`. This code, in a file
5211 println!("x is: {:s}", x);
5215 Can have its macros expanded like this: `rustc print.rs --pretty=expanded`, will
5216 give us this huge result:
5222 #[phase(plugin, link)]
5223 extern crate std = "std";
5224 extern crate rt = "native";
5225 use std::prelude::*;
5232 static __STATIC_FMTSTR: [::std::fmt::rt::Piece<'static>, ..2u] =
5233 [::std::fmt::rt::String("x is: "),
5234 ::std::fmt::rt::Argument(::std::fmt::rt::Argument{position:
5235 ::std::fmt::rt::ArgumentNext,
5237 ::std::fmt::rt::FormatSpec{fill:
5240 ::std::fmt::rt::AlignUnknown,
5244 ::std::fmt::rt::CountImplied,
5246 ::std::fmt::rt::CountImplied,},})];
5248 &[::std::fmt::argument(::std::fmt::secret_string, __arg0)];
5251 ::std::fmt::Arguments::new(__STATIC_FMTSTR, __args_vec)
5253 ::std::io::stdio::println_args(&__args)
5259 Intense. Here's a trimmed down version that's a bit easier to read:
5266 static __STATIC_FMTSTR: =
5269 position: ArgumentNext,
5270 format: FormatSpec {
5272 align: AlignUnknown,
5274 precision: CountImplied,
5275 width: CountImplied,
5279 let __args_vec = &[argument(secret_string, __arg0)];
5280 let __args = unsafe { Arguments::new(__STATIC_FMTSTR, __args_vec) };
5282 println_args(&__args)
5288 Whew! This isn't too terrible. You can see that we still `let x = 5i`,
5289 but then things get a little bit hairy. Three more bindings get set: a
5290 static format string, an argument vector, and the arguments. We then
5291 invoke the `println_args` function with the generated arguments.
5293 This is the code (well, the full version) that Rust actually compiles. You can
5294 see all of the extra information that's here. We get all of the type safety and
5295 options that it provides, but at compile time, and without needing to type all
5296 of this out. This is how macros are powerful. Without them, you would need to
5297 type all of this by hand to get a type checked `println`.
5299 For more on macros, please consult [the Macros Guide](guide-macros.html).
5300 Macros are a very advanced and still slightly experimental feature, but don't
5301 require a deep understanding to call, since they look just like functions. The
5302 Guide can help you if you want to write your own.
5306 Finally, there's one more Rust concept that you should be aware of: `unsafe`.
5307 There are two circumstances where Rust's safety provisions don't work well.
5308 The first is when interfacing with C code, and the second is when building
5309 certain kinds of abstractions.
5311 Rust has support for FFI (which you can read about in the [FFI
5312 Guide](guide-ffi.html)), but can't guarantee that the C code will be safe.
5313 Therefore, Rust marks such functions with the `unsafe`
5314 keyword, which indicates that the function may not behave properly.
5316 Second, if you'd like to create some sort of shared-memory data structure, Rust
5317 won't allow it, because memory must be owned by a single owner. However, if
5318 you're planning on making access to that shared memory safe, such as with a
5319 mutex, _you_ know that it's safe, but Rust can't know. Writing an `unsafe`
5320 block allows you to ask the compiler to trust you. In this case, the _internal_
5321 implementation of the mutex is considered unsafe, but the _external_ interface
5322 we present is safe. This allows it to be effectively used in normal Rust, while
5323 being able to implement functionality that the compiler can't double check for
5326 Doesn't an escape hatch undermine the safety of the entire system? Well, if
5327 Rust code segfaults, it _must_ be because of unsafe code somewhere. By
5328 annotating exactly where that is, you have a significantly smaller area to
5331 We haven't even talked about any examples here, and that's because I want to
5332 emphasize that you should not be writing unsafe code unless you know exactly
5333 what you're doing. The vast majority of Rust developers will only interact with
5334 it when doing FFI, and advanced library authors may use it to build certain
5335 kinds of abstraction.
5339 We covered a lot of ground here. When you've mastered everything in this Guide,
5340 you will have a firm grasp of basic Rust development. There's a whole lot more
5341 out there, we've just covered the surface. There's tons of topics that you can
5342 dig deeper into, and we've built specialized guides for many of them. To learn
5343 more, dig into the [full documentation
5344 index](http://doc.rust-lang.org/index.html).