3 This first chapter of the book will get us going with Rust and its tooling.
4 First, we’ll install Rust. Then, the classic ‘Hello World’ program. Finally,
5 we’ll talk about Cargo, Rust’s build system and package manager.
9 The first step to using Rust is to install it. Generally speaking, you’ll need
10 an Internet connection to run the commands in this section, as we’ll be
11 downloading Rust from the internet.
13 We’ll be showing off a number of commands using a terminal, and those lines all
14 start with `$`. We don't need to type in the `$`s, they are there to indicate
15 the start of each command. We’ll see many tutorials and examples around the web
16 that follow this convention: `$` for commands run as our regular user, and `#`
17 for commands we should be running as an administrator.
21 The Rust compiler runs on, and compiles to, a great number of platforms, though
22 not all platforms are equally supported. Rust's support levels are organized
23 into three tiers, each with a different set of guarantees.
25 Platforms are identified by their "target triple" which is the string to inform
26 the compiler what kind of output should be produced. The columns below indicate
27 whether the corresponding component works on the specified platform.
31 Tier 1 platforms can be thought of as "guaranteed to build and work".
32 Specifically they will each satisfy the following requirements:
34 * Automated testing is set up to run tests for the platform.
35 * Landing changes to the `rust-lang/rust` repository's master branch is gated on
37 * Official release artifacts are provided for the platform.
38 * Documentation for how to use and how to build the platform is available.
40 | Target | std |rustc|cargo| notes |
41 |-------------------------------|-----|-----|-----|----------------------------|
42 | `i686-pc-windows-msvc` | ✓ | ✓ | ✓ | 32-bit MSVC (Windows 7+) |
43 | `x86_64-pc-windows-msvc` | ✓ | ✓ | ✓ | 64-bit MSVC (Windows 7+) |
44 | `i686-pc-windows-gnu` | ✓ | ✓ | ✓ | 32-bit MinGW (Windows 7+) |
45 | `x86_64-pc-windows-gnu` | ✓ | ✓ | ✓ | 64-bit MinGW (Windows 7+) |
46 | `i686-apple-darwin` | ✓ | ✓ | ✓ | 32-bit OSX (10.7+, Lion+) |
47 | `x86_64-apple-darwin` | ✓ | ✓ | ✓ | 64-bit OSX (10.7+, Lion+) |
48 | `i686-unknown-linux-gnu` | ✓ | ✓ | ✓ | 32-bit Linux (2.6.18+) |
49 | `x86_64-unknown-linux-gnu` | ✓ | ✓ | ✓ | 64-bit Linux (2.6.18+) |
53 Tier 2 platforms can be thought of as "guaranteed to build". Automated tests
54 are not run so it's not guaranteed to produce a working build, but platforms
55 often work to quite a good degree and patches are always welcome! Specifically,
56 these platforms are required to have each of the following:
58 * Automated building is set up, but may not be running tests.
59 * Landing changes to the `rust-lang/rust` repository's master branch is gated on
60 platforms **building**. Note that this means for some platforms only the
61 standard library is compiled, but for others the full bootstrap is run.
62 * Official release artifacts are provided for the platform.
64 | Target | std |rustc|cargo| notes |
65 |-------------------------------|-----|-----|-----|----------------------------|
66 | `x86_64-unknown-linux-musl` | ✓ | | | 64-bit Linux with MUSL |
67 | `arm-linux-androideabi` | ✓ | | | ARM Android |
68 | `arm-unknown-linux-gnueabi` | ✓ | ✓ | | ARM Linux (2.6.18+) |
69 | `arm-unknown-linux-gnueabihf` | ✓ | ✓ | | ARM Linux (2.6.18+) |
70 | `aarch64-unknown-linux-gnu` | ✓ | | | ARM64 Linux (2.6.18+) |
71 | `mips-unknown-linux-gnu` | ✓ | | | MIPS Linux (2.6.18+) |
72 | `mipsel-unknown-linux-gnu` | ✓ | | | MIPS (LE) Linux (2.6.18+) |
76 Tier 3 platforms are those which Rust has support for, but landing changes is
77 not gated on the platform either building or passing tests. Working builds for
78 these platforms may be spotty as their reliability is often defined in terms of
79 community contributions. Additionally, release artifacts and installers are not
80 provided, but there may be community infrastructure producing these in
83 | Target | std |rustc|cargo| notes |
84 |-------------------------------|-----|-----|-----|----------------------------|
85 | `i686-linux-android` | ✓ | | | 32-bit x86 Android |
86 | `aarch64-linux-android` | ✓ | | | ARM64 Android |
87 | `powerpc-unknown-linux-gnu` | ✓ | | | PowerPC Linux (2.6.18+) |
88 | `powerpc64-unknown-linux-gnu` | ✓ | | | PPC64 Linux (2.6.18+) |
89 |`powerpc64le-unknown-linux-gnu`| ✓ | | | PPC64LE Linux (2.6.18+) |
90 |`armv7-unknown-linux-gnueabihf`| ✓ | | | ARMv7 Linux (2.6.18+) |
91 | `i386-apple-ios` | ✓ | | | 32-bit x86 iOS |
92 | `x86_64-apple-ios` | ✓ | | | 64-bit x86 iOS |
93 | `armv7-apple-ios` | ✓ | | | ARM iOS |
94 | `armv7s-apple-ios` | ✓ | | | ARM iOS |
95 | `aarch64-apple-ios` | ✓ | | | ARM64 iOS |
96 | `i686-unknown-freebsd` | ✓ | ✓ | ✓ | 32-bit FreeBSD |
97 | `x86_64-unknown-freebsd` | ✓ | ✓ | ✓ | 64-bit FreeBSD |
98 | `x86_64-unknown-openbsd` | ✓ | ✓ | | 64-bit OpenBSD |
99 | `x86_64-unknown-netbsd` | ✓ | ✓ | | 64-bit NetBSD |
100 | `x86_64-unknown-bitrig` | ✓ | ✓ | | 64-bit Bitrig |
101 | `x86_64-unknown-dragonfly` | ✓ | ✓ | | 64-bit DragonFlyBSD |
102 | `x86_64-rumprun-netbsd` | ✓ | | | 64-bit NetBSD Rump Kernel |
103 | `x86_64-sun-solaris` | ✓ | ✓ | | 64-bit Solaris/SunOS |
104 | `i686-pc-windows-msvc` (XP) | ✓ | | | Windows XP support |
105 | `x86_64-pc-windows-msvc` (XP) | ✓ | | | Windows XP support |
107 Note that this table can be expanded over time, this isn't the exhaustive set of
108 tier 3 platforms that will ever be!
110 ## Installing on Linux or Mac
112 If we're on Linux or a Mac, all we need to do is open a terminal and type this:
115 $ curl -sSf https://static.rust-lang.org/rustup.sh | sh
118 This will download a script, and start the installation. If it all goes well,
119 you’ll see this appear:
122 Rust is ready to roll.
125 From here, press `y` for ‘yes’, and then follow the rest of the prompts.
127 ## Installing on Windows
129 If you're on Windows, please download the appropriate [installer][install-page].
131 [install-page]: https://www.rust-lang.org/install.html
135 Uninstalling Rust is as easy as installing it. On Linux or Mac, run
136 the uninstall script:
139 $ sudo /usr/local/lib/rustlib/uninstall.sh
142 If we used the Windows installer, we can re-run the `.msi` and it will give us
147 If we've got Rust installed, we can open up a shell, and type this:
153 You should see the version number, commit hash, and commit date.
155 If you do, Rust has been installed successfully! Congrats!
157 If you don't and you're on Windows, check that Rust is in your %PATH% system
158 variable. If it isn't, run the installer again, select "Change" on the "Change,
159 repair, or remove installation" page and ensure "Add to PATH" is installed on
160 the local hard drive.
162 Rust does not do its own linking, and so you’ll need to have a linker
163 installed. Doing so will depend on your specific system, consult its
164 documentation for more details.
166 If not, there are a number of places where we can get help. The easiest is
167 [the #rust-beginners IRC channel on irc.mozilla.org][irc-beginners] and for
168 general discussion [the #rust IRC channel on irc.mozilla.org][irc], which we
169 can access through [Mibbit][mibbit]. Then we'll be chatting with other
170 Rustaceans (a silly nickname we call ourselves) who can help us out. Other great
171 resources include [the user’s forum][users] and [Stack Overflow][stackoverflow].
173 [irc-beginners]: irc://irc.mozilla.org/#rust-beginners
174 [irc]: irc://irc.mozilla.org/#rust
175 [mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-beginners,%23rust
176 [users]: https://users.rust-lang.org/
177 [stackoverflow]: http://stackoverflow.com/questions/tagged/rust
179 This installer also installs a copy of the documentation locally, so we can
180 read it offline. On UNIX systems, `/usr/local/share/doc/rust` is the location.
181 On Windows, it's in a `share/doc` directory, inside the directory to which Rust
186 Now that you have Rust installed, we'll help you write your first Rust program.
187 It's traditional when learning a new language to write a little program to
188 print the text “Hello, world!” to the screen, and in this section, we'll follow
191 The nice thing about starting with such a simple program is that you can
192 quickly verify that your compiler is installed, and that it's working properly.
193 Printing information to the screen is also a pretty common thing to do, so
194 practicing it early on is good.
196 > Note: This book assumes basic familiarity with the command line. Rust itself
197 > makes no specific demands about your editing, tooling, or where your code
198 > lives, so if you prefer an IDE to the command line, that's an option. You may
199 > want to check out [SolidOak], which was built specifically with Rust in mind.
200 > There are a number of extensions in development by the community, and the
201 > Rust team ships plugins for [various editors]. Configuring your editor or
202 > IDE is out of the scope of this tutorial, so check the documentation for your
205 [SolidOak]: https://github.com/oakes/SolidOak
206 [various editors]: https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md
208 ## Creating a Project File
210 First, make a file to put your Rust code in. Rust doesn't care where your code
211 lives, but for this book, I suggest making a *projects* directory in your home
212 directory, and keeping all your projects there. Open a terminal and enter the
213 following commands to make a directory for this particular project:
222 > Note: If you’re on Windows and not using PowerShell, the `~` may not work.
223 > Consult the documentation for your shell for more details.
225 ## Writing and Running a Rust Program
227 Next, make a new source file and call it *main.rs*. Rust files always end
228 in a *.rs* extension. If you’re using more than one word in your filename, use
229 an underscore to separate them; for example, you'd use *hello_world.rs* rather
230 than *helloworld.rs*.
232 Now open the *main.rs* file you just created, and type the following code:
236 println!("Hello, world!");
240 Save the file, and go back to your terminal window. On Linux or OSX, enter the
249 In Windows, replace `main` with `main.exe`. Regardless of your operating
250 system, you should see the string `Hello, world!` print to the terminal. If you
251 did, then congratulations! You've officially written a Rust program. That makes
252 you a Rust programmer! Welcome.
254 ## Anatomy of a Rust Program
256 Now, let’s go over what just happened in your "Hello, world!" program in
257 detail. Here's the first piece of the puzzle:
265 These lines define a *function* in Rust. The `main` function is special: it's
266 the beginning of every Rust program. The first line says, “I’m declaring a
267 function named `main` that takes no arguments and returns nothing.” If there
268 were arguments, they would go inside the parentheses (`(` and `)`), and because
269 we aren’t returning anything from this function, we can omit the return type
272 Also note that the function body is wrapped in curly braces (`{` and `}`). Rust
273 requires these around all function bodies. It's considered good style to put
274 the opening curly brace on the same line as the function declaration, with one
277 Inside the `main()` function:
280 println!("Hello, world!");
283 This line does all of the work in this little program: it prints text to the
284 screen. There are a number of details that are important here. The first is
285 that it’s indented with four spaces, not tabs.
287 The second important part is the `println!()` line. This is calling a Rust
288 *[macro]*, which is how metaprogramming is done in Rust. If it were calling a
289 function instead, it would look like this: `println()` (without the !). We'll
290 discuss Rust macros in more detail later, but for now you only need to
291 know that when you see a `!` that means that you’re calling a macro instead of
297 Next is `"Hello, world!"` which is a *string*. Strings are a surprisingly
298 complicated topic in a systems programming language, and this is a *[statically
299 allocated]* string. We pass this string as an argument to `println!`, which
300 prints the string to the screen. Easy enough!
302 [statically allocated]: the-stack-and-the-heap.html
304 The line ends with a semicolon (`;`). Rust is an *[expression-oriented
305 language]*, which means that most things are expressions, rather than
306 statements. The `;` indicates that this expression is over, and the next one is
307 ready to begin. Most lines of Rust code end with a `;`.
309 [expression-oriented language]: glossary.html#expression-oriented-language
311 ## Compiling and Running Are Separate Steps
313 In "Writing and Running a Rust Program", we showed you how to run a newly
314 created program. We'll break that process down and examine each step now.
316 Before running a Rust program, you have to compile it. You can use the Rust
317 compiler by entering the `rustc` command and passing it the name of your source
324 If you come from a C or C++ background, you'll notice that this is similar to
325 `gcc` or `clang`. After compiling successfully, Rust should output a binary
326 executable, which you can see on Linux or OSX by entering the `ls` command in
327 your shell as follows:
334 On Windows, you'd enter:
341 This shows we have two files: the source code, with an `.rs` extension, and the
342 executable (`main.exe` on Windows, `main` everywhere else). All that's left to
343 do from here is run the `main` or `main.exe` file, like this:
346 $ ./main # or main.exe on Windows
349 If *main.rs* were your "Hello, world!" program, this would print `Hello,
350 world!` to your terminal.
352 If you come from a dynamic language like Ruby, Python, or JavaScript, you may
353 not be used to compiling and running a program being separate steps. Rust is an
354 *ahead-of-time compiled* language, which means that you can compile a program,
355 give it to someone else, and they can run it even without Rust installed. If
356 you give someone a `.rb` or `.py` or `.js` file, on the other hand, they need
357 to have a Ruby, Python, or JavaScript implementation installed (respectively),
358 but you only need one command to both compile and run your program. Everything
359 is a tradeoff in language design.
361 Just compiling with `rustc` is fine for simple programs, but as your project
362 grows, you'll want to be able to manage all of the options your project has,
363 and make it easy to share your code with other people and projects. Next, I'll
364 introduce you to a tool called Cargo, which will help you write real-world Rust
369 Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
370 manage their Rust projects. Cargo manages three things: building your code,
371 downloading the libraries your code depends on, and building those libraries.
372 We call libraries your code needs ‘dependencies’ since your code depends on
375 The simplest Rust programs don’t have any dependencies, so right now, you'd
376 only use the first part of its functionality. As you write more complex Rust
377 programs, you’ll want to add dependencies, and if you start off using Cargo,
378 that will be a lot easier to do.
380 As the vast, vast majority of Rust projects use Cargo, we will assume that
381 you’re using it for the rest of the book. Cargo comes installed with Rust
382 itself, if you used the official installers. If you installed Rust through some
383 other means, you can check if you have Cargo installed by typing:
389 Into a terminal. If you see a version number, great! If you see an error like
390 ‘`command not found`’, then you should look at the documentation for the system
391 in which you installed Rust, to determine if Cargo is separate.
393 ## Converting to Cargo
395 Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
398 1. Put your source file in the right directory.
399 2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere else)
401 3. Make a Cargo configuration file.
405 ### Creating a new Executable and Source Directory
407 First, go back to your terminal, move to your *hello_world* directory, and
408 enter the following commands:
412 $ mv main.rs src/main.rs
413 $ rm main # or 'del main.exe' on Windows
416 Cargo expects your source files to live inside a *src* directory, so do that
417 first. This leaves the top-level project directory (in this case,
418 *hello_world*) for READMEs, license information, and anything else not related
419 to your code. In this way, using Cargo helps you keep your projects nice and
420 tidy. There's a place for everything, and everything is in its place.
422 Now, move *main.rs* into the *src* directory, and delete the compiled file you
423 created with `rustc`. As usual, replace `main` with `main.exe` if you're on
426 This example retains `main.rs` as the source filename because it's creating an
427 executable. If you wanted to make a library instead, you'd name the file
428 `lib.rs`. This convention is used by Cargo to successfully compile your
429 projects, but it can be overridden if you wish.
431 ### Creating a Configuration File
433 Next, create a new file inside your *hello_world* directory, and call it
436 Make sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do
437 with the configuration file.
439 This file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is
440 similar to INI, but has some extra goodies, and is used as Cargo’s
441 configuration format.
443 [TOML]: https://github.com/toml-lang/toml
445 Inside this file, type the following information:
452 authors = [ "Your name <you@example.com>" ]
455 The first line, `[package]`, indicates that the following statements are
456 configuring a package. As we add more information to this file, we’ll add other
457 sections, but for now, we only have the package configuration.
459 The other three lines set the three bits of configuration that Cargo needs to
460 know to compile your program: its name, what version it is, and who wrote it.
462 Once you've added this information to the *Cargo.toml* file, save it to finish
463 creating the configuration file.
465 ## Building and Running a Cargo Project
467 With your *Cargo.toml* file in place in your project's root directory, you
468 should be ready to build and run your Hello World program! To do so, enter the
473 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
474 $ ./target/debug/hello_world
478 Bam! If all goes well, `Hello, world!` should print to the terminal once more.
480 You just built a project with `cargo build` and ran it with
481 `./target/debug/hello_world`, but you can actually do both in one step with
482 `cargo run` as follows:
486 Running `target/debug/hello_world`
490 Notice that this example didn’t re-build the project. Cargo figured out that
491 the file hasn’t changed, and so it just ran the binary. If you'd modified your
492 source code, Cargo would have rebuilt the project before running it, and you
493 would have seen something like this:
497 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
498 Running `target/debug/hello_world`
502 Cargo checks to see if any of your project’s files have been modified, and only
503 rebuilds your project if they’ve changed since the last time you built it.
505 With simple projects, Cargo doesn't bring a whole lot over just using `rustc`,
506 but it will become useful in the future. This is especially true when you start
507 using crates; these are synonymous with a ‘library’ or ‘package’ in other
508 programming languages. For complex projects composed of multiple crates, it’s
509 much easier to let Cargo coordinate the build. Using Cargo, you can run `cargo
510 build`, and it should work the right way.
512 ### Building for Release
514 When your project is ready for release, you can use `cargo build
515 --release` to compile your project with optimizations. These optimizations make
516 your Rust code run faster, but turning them on makes your program take longer
517 to compile. This is why there are two different profiles, one for development,
518 and one for building the final program you’ll give to a user.
520 ### What Is That `Cargo.lock`?
522 Running `cargo build` also causes Cargo to create a new file called
523 *Cargo.lock*, which looks like this:
531 Cargo uses the *Cargo.lock* file to keep track of dependencies in your
532 application. This is the Hello World project's *Cargo.lock* file. This project
533 doesn't have dependencies, so the file is a bit sparse. Realistically, you
534 won't ever need to touch this file yourself; just let Cargo handle it.
536 That’s it! If you've been following along, you should have successfully built
537 `hello_world` with Cargo.
539 Even though the project is simple, it now uses much of the real tooling you’ll
540 use for the rest of your Rust career. In fact, you can expect to start
541 virtually all Rust projects with some variation on the following commands:
544 $ git clone someurl.com/foo
549 ## Making A New Cargo Project the Easy Way
551 You don’t have to go through that previous process every time you want to start
552 a new project! Cargo can quickly make a bare-bones project directory that you
553 can start developing in right away.
555 To start a new project with Cargo, enter `cargo new` at the command line:
558 $ cargo new hello_world --bin
561 This command passes `--bin` because the goal is to get straight to making an
562 executable application, as opposed to a library. Executables are often called
563 *binaries* (as in `/usr/bin`, if you’re on a Unix system).
565 Cargo has generated two files and one directory for us: a `Cargo.toml` and a
566 *src* directory with a *main.rs* file inside. These should look familiar,
567 they’re exactly what we created by hand, above.
569 This output is all you need to get started. First, open `Cargo.toml`. It should
570 look something like this:
577 authors = ["Your Name <you@example.com>"]
580 Cargo has populated *Cargo.toml* with reasonable defaults based on the arguments
581 you gave it and your `git` global configuration. You may notice that Cargo has
582 also initialized the `hello_world` directory as a `git` repository.
584 Here’s what should be in `src/main.rs`:
588 println!("Hello, world!");
592 Cargo has generated a "Hello World!" for you, and you’re ready to start coding!
594 > Note: If you want to look at Cargo in more detail, check out the official [Cargo
595 guide], which covers all of its features.
597 [Cargo guide]: http://doc.crates.io/guide.html
601 This chapter covered the basics that will serve you well through the rest of
602 this book, and the rest of your time with Rust. Now that you’ve got the tools
603 down, we'll cover more about the Rust language itself.
605 You have two options: Dive into a project with ‘[Tutorial: Guessing Game][guessinggame]’, or
606 start from the bottom and work your way up with ‘[Syntax and
607 Semantics][syntax]’. More experienced systems programmers will probably prefer
608 ‘Tutorial: Guessing Game’, while those from dynamic backgrounds may enjoy either. Different
609 people learn differently! Choose whatever’s right for you.
611 [guessinggame]: guessing-game.html
612 [syntax]: syntax-and-semantics.html