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.
7 We’ll be showing off a number of commands using a terminal, and those lines all
8 start with `$`. You don't need to type in the `$`s, they are there to indicate
9 the start of each command. We’ll see many tutorials and examples around the web
10 that follow this convention: `$` for commands run as our regular user, and `#`
11 for commands we should be running as an administrator.
15 The first step to using Rust is to install it. Generally speaking, you’ll need
16 an Internet connection to run the commands in this section, as we’ll be
17 downloading Rust from the Internet.
19 The Rust compiler runs on, and compiles to, a great number of platforms, but is
20 best supported on Linux, Mac, and Windows, on the x86 and x86-64 CPU
21 architecture. There are official builds of the Rust compiler and standard
22 library for these platforms and more. [For full details on Rust platform support
23 see the website][platform-support].
25 [platform-support]: https://forge.rust-lang.org/platform-support.html
29 All you need to do on Unix systems like Linux and macOS is open a
30 terminal and type this:
33 $ curl https://sh.rustup.rs -sSf | sh
36 It will download a script, and start the installation. If everything
37 goes well, you’ll see this appear:
40 Rust is installed now. Great!
43 Installing on Windows is nearly as easy: download and run
44 [rustup-init.exe]. It will start the installation in a console and
45 present the above message on success.
47 For other installation options and information, visit the [install]
48 page of the Rust website.
50 [rustup-init.exe]: https://win.rustup.rs
51 [install]: https://www.rust-lang.org/install.html
55 Uninstalling Rust is as easy as installing it:
58 $ rustup self uninstall
63 If we've got Rust installed, we can open up a shell, and type this:
69 You should see the version number, commit hash, and commit date.
71 If you do, Rust has been installed successfully! Congrats!
73 If you don't, that probably means that the `PATH` environment variable
74 doesn't include Cargo's binary directory, `~/.cargo/bin` on Unix, or
75 `%USERPROFILE%\.cargo\bin` on Windows. This is the directory where
76 Rust development tools live, and most Rust developers keep it in their
77 `PATH` environment variable, which makes it possible to run `rustc` on
78 the command line. Due to differences in operating systems, command
79 shells, and bugs in installation, you may need to restart your shell,
80 log out of the system, or configure `PATH` manually as appropriate for
81 your operating environment.
83 Rust does not do its own linking, and so you’ll need to have a linker
84 installed. Doing so will depend on your specific system. For
85 Linux-based systems, Rust will attempt to call `cc` for linking. On
86 `windows-msvc` (Rust built on Windows with Microsoft Visual Studio),
87 this depends on having [Microsoft Visual C++ Build Tools][msvbt]
88 installed. These do not need to be in `%PATH%` as `rustc` will find
89 them automatically. In general, if you have your linker in a
90 non-traditional location you can call `rustc
91 linker=/path/to/cc`, where `/path/to/cc` should point to your linker path.
93 [msvbt]: http://landinghub.visualstudio.com/visual-cpp-build-tools
95 If you are still stuck, there are a number of places where we can get
97 [the #rust-beginners IRC channel on irc.mozilla.org][irc-beginners]
98 and for general discussion
99 [the #rust IRC channel on irc.mozilla.org][irc], which we
100 can access through [Mibbit][mibbit]. Then we'll be chatting with other
101 Rustaceans (a silly nickname we call ourselves) who can help us out. Other great
102 resources include [the user’s forum][users] and [Stack Overflow][stackoverflow].
104 [irc-beginners]: irc://irc.mozilla.org/#rust-beginners
105 [irc]: irc://irc.mozilla.org/#rust
106 [mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-beginners,%23rust
107 [users]: https://users.rust-lang.org/
108 [stackoverflow]: http://stackoverflow.com/questions/tagged/rust
110 This installer also installs a copy of the documentation locally, so we can
111 read it offline. It's only a `rustup doc` away!
115 Now that you have Rust installed, we'll help you write your first Rust program.
116 It's traditional when learning a new language to write a little program to
117 print the text “Hello, world!” to the screen, and in this section, we'll follow
120 The nice thing about starting with such a simple program is that you can
121 quickly verify that your compiler is installed, and that it's working properly.
122 Printing information to the screen is also a pretty common thing to do, so
123 practicing it early on is good.
125 > Note: This book assumes basic familiarity with the command line. Rust itself
126 > makes no specific demands about your editing, tooling, or where your code
127 > lives, so if you prefer an IDE to the command line, that's an option. You may
128 > want to check out [SolidOak], which was built specifically with Rust in mind.
129 > There are a number of extensions in development by the community, and the
130 > Rust team ships plugins for [various editors]. Configuring your editor or
131 > IDE is out of the scope of this tutorial, so check the documentation for your
134 [SolidOak]: https://github.com/oakes/SolidOak
135 [various editors]: https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md
137 ## Creating a Project File
139 First, make a file to put your Rust code in. Rust doesn't care where your code
140 lives, but for this book, I suggest making a *projects* directory in your home
141 directory, and keeping all your projects there. Open a terminal and enter the
142 following commands to make a directory for this particular project:
151 > Note: If you’re on Windows and not using PowerShell, the `~` may not work.
152 > Consult the documentation for your shell for more details.
154 ## Writing and Running a Rust Program
156 We need to create a source file for our Rust program. Rust files always end
157 in a *.rs* extension. If you are using more than one word in your filename,
158 use an underscore to separate them; for example, you would use
159 *my_program.rs* rather than *myprogram.rs*.
161 Now, make a new file and call it *main.rs*. Open the file and type
166 println!("Hello, world!");
170 Save the file, and go back to your terminal window. On Linux or OSX, enter the
179 In Windows, replace `main` with `main.exe`. Regardless of your operating
180 system, you should see the string `Hello, world!` print to the terminal. If you
181 did, then congratulations! You've officially written a Rust program. That makes
182 you a Rust programmer! Welcome.
184 ## Anatomy of a Rust Program
186 Now, let’s go over what just happened in your "Hello, world!" program in
187 detail. Here's the first piece of the puzzle:
195 These lines define a *function* in Rust. The `main` function is special: it's
196 the beginning of every Rust program. The first line says, “I’m declaring a
197 function named `main` that takes no arguments and returns nothing.” If there
198 were arguments, they would go inside the parentheses (`(` and `)`), and because
199 we aren’t returning anything from this function, we can omit the return type
202 Also note that the function body is wrapped in curly braces (`{` and `}`). Rust
203 requires these around all function bodies. It's considered good style to put
204 the opening curly brace on the same line as the function declaration, with one
207 Inside the `main()` function:
210 println!("Hello, world!");
213 This line does all of the work in this little program: it prints text to the
214 screen. There are a number of details that are important here. The first is
215 that it’s indented with four spaces, not tabs.
217 The second important part is the `println!()` line. This is calling a Rust
218 *[macro]*, which is how metaprogramming is done in Rust. If it were calling a
219 function instead, it would look like this: `println()` (without the !). We'll
220 discuss Rust macros in more detail later, but for now you only need to
221 know that when you see a `!` that means that you’re calling a macro instead of
227 Next is `"Hello, world!"` which is a *string*. Strings are a surprisingly
228 complicated topic in a systems programming language, and this is a *[statically
229 allocated]* string. We pass this string as an argument to `println!`, which
230 prints the string to the screen. Easy enough!
232 [statically allocated]: the-stack-and-the-heap.html
234 The line ends with a semicolon (`;`). Rust is an *[expression-oriented
235 language]*, which means that most things are expressions, rather than
236 statements. The `;` indicates that this expression is over, and the next one is
237 ready to begin. Most lines of Rust code end with a `;`.
239 [expression-oriented language]: glossary.html#expression-oriented-language
241 ## Compiling and Running Are Separate Steps
243 In "Writing and Running a Rust Program", we showed you how to run a newly
244 created program. We'll break that process down and examine each step now.
246 Before running a Rust program, you have to compile it. You can use the Rust
247 compiler by entering the `rustc` command and passing it the name of your source
254 If you come from a C or C++ background, you'll notice that this is similar to
255 `gcc` or `clang`. After compiling successfully, Rust should output a binary
256 executable, which you can see on Linux or OSX by entering the `ls` command in
257 your shell as follows:
264 On Windows, you'd enter:
272 This shows we have two files: the source code, with an `.rs` extension, and the
273 executable (`main.exe` on Windows, `main` everywhere else). All that's left to
274 do from here is run the `main` or `main.exe` file, like this:
277 $ ./main # or .\main.exe on Windows
280 If *main.rs* were your "Hello, world!" program, this would print `Hello,
281 world!` to your terminal.
283 If you come from a dynamic language like Ruby, Python, or JavaScript, you may
284 not be used to compiling and running a program being separate steps. Rust is an
285 *ahead-of-time compiled* language, which means that you can compile a program,
286 give it to someone else, and they can run it even without Rust installed. If
287 you give someone a `.rb` or `.py` or `.js` file, on the other hand, they need
288 to have a Ruby, Python, or JavaScript implementation installed (respectively),
289 but you only need one command to both compile and run your program. Everything
290 is a tradeoff in language design.
292 Just compiling with `rustc` is fine for simple programs, but as your project
293 grows, you'll want to be able to manage all of the options your project has,
294 and make it easy to share your code with other people and projects. Next, I'll
295 introduce you to a tool called Cargo, which will help you write real-world Rust
300 Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
301 manage their Rust projects. Cargo manages three things: building your code,
302 downloading the libraries your code depends on, and building those libraries.
303 We call libraries your code needs ‘dependencies’ since your code depends on
306 The simplest Rust programs don’t have any dependencies, so right now, you'd
307 only use the first part of its functionality. As you write more complex Rust
308 programs, you’ll want to add dependencies, and if you start off using Cargo,
309 that will be a lot easier to do.
311 As the vast, vast majority of Rust projects use Cargo, we will assume that
312 you’re using it for the rest of the book. Cargo comes installed with Rust
313 itself, if you used the official installers. If you installed Rust through some
314 other means, you can check if you have Cargo installed by typing:
320 Into a terminal. If you see a version number, great! If you see an error like
321 ‘`command not found`’, then you should look at the documentation for the system
322 in which you installed Rust, to determine if Cargo is separate.
324 ## Converting to Cargo
326 Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
329 1. Put your source file in the right directory.
330 2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere
332 3. Make a Cargo configuration file.
336 ### Creating a Source Directory and Removing the Old Executable
338 First, go back to your terminal, move to your *hello_world* directory, and
339 enter the following commands:
343 $ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows
344 $ rm main # or 'del main.exe' on Windows
347 Cargo expects your source files to live inside a *src* directory, so do that
348 first. This leaves the top-level project directory (in this case,
349 *hello_world*) for READMEs, license information, and anything else not related
350 to your code. In this way, using Cargo helps you keep your projects nice and
351 tidy. There's a place for everything, and everything is in its place.
353 Now, move *main.rs* into the *src* directory, and delete the compiled file you
354 created with `rustc`. As usual, replace `main` with `main.exe` if you're on
357 This example retains `main.rs` as the source filename because it's creating an
358 executable. If you wanted to make a library instead, you'd name the file
359 `lib.rs`. This convention is used by Cargo to successfully compile your
360 projects, but it can be overridden if you wish.
362 ### Creating a Configuration File
364 Next, create a new file inside your *hello_world* directory, and call it
367 Make sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do
368 with the configuration file.
370 This file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is
371 similar to INI, but has some extra goodies, and is used as Cargo’s
372 configuration format.
374 [TOML]: https://github.com/toml-lang/toml
376 Inside this file, type the following information:
383 authors = [ "Your name <you@example.com>" ]
386 The first line, `[package]`, indicates that the following statements are
387 configuring a package. As we add more information to this file, we’ll add other
388 sections, but for now, we only have the package configuration.
390 The other three lines set the three bits of configuration that Cargo needs to
391 know to compile your program: its name, what version it is, and who wrote it.
393 Once you've added this information to the *Cargo.toml* file, save it to finish
394 creating the configuration file.
396 ## Building and Running a Cargo Project
398 With your *Cargo.toml* file in place in your project's root directory, you
399 should be ready to build and run your Hello World program! To do so, enter the
404 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
405 $ ./target/debug/hello_world
409 Bam! If all goes well, `Hello, world!` should print to the terminal once more.
411 You just built a project with `cargo build` and ran it with
412 `./target/debug/hello_world`, but you can actually do both in one step with
413 `cargo run` as follows:
417 Running `target/debug/hello_world`
421 The `run` command comes in handy when you need to rapidly iterate on a
424 Notice that this example didn’t re-build the project. Cargo figured out that
425 the file hasn’t changed, and so it just ran the binary. If you'd modified your
426 source code, Cargo would have rebuilt the project before running it, and you
427 would have seen something like this:
431 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
432 Running `target/debug/hello_world`
436 Cargo checks to see if any of your project’s files have been modified, and only
437 rebuilds your project if they’ve changed since the last time you built it.
439 With simple projects, Cargo doesn't bring a whole lot over just using `rustc`,
440 but it will become useful in the future. This is especially true when you start
441 using crates; these are synonymous with a ‘library’ or ‘package’ in other
442 programming languages. For complex projects composed of multiple crates, it’s
443 much easier to let Cargo coordinate the build. Using Cargo, you can run `cargo
444 build`, and it should work the right way.
446 ### Building for Release
448 When your project is ready for release, you can use `cargo build
449 --release` to compile your project with optimizations. These optimizations make
450 your Rust code run faster, but turning them on makes your program take longer
451 to compile. This is why there are two different profiles, one for development,
452 and one for building the final program you’ll give to a user.
454 ### What Is That `Cargo.lock`?
456 Running `cargo build` also causes Cargo to create a new file called
457 *Cargo.lock*, which looks like this:
465 Cargo uses the *Cargo.lock* file to keep track of dependencies in your
466 application. This is the Hello World project's *Cargo.lock* file. This project
467 doesn't have dependencies, so the file is a bit sparse. Realistically, you
468 won't ever need to touch this file yourself; just let Cargo handle it.
470 That’s it! If you've been following along, you should have successfully built
471 `hello_world` with Cargo.
473 Even though the project is simple, it now uses much of the real tooling you’ll
474 use for the rest of your Rust career. In fact, you can expect to start
475 virtually all Rust projects with some variation on the following commands:
478 $ git clone someurl.com/foo
483 ## Making A New Cargo Project the Easy Way
485 You don’t have to go through that previous process every time you want to start
486 a new project! Cargo can quickly make a bare-bones project directory that you
487 can start developing in right away.
489 To start a new project with Cargo, enter `cargo new` at the command line:
492 $ cargo new hello_world --bin
495 This command passes `--bin` because the goal is to get straight to making an
496 executable application, as opposed to a library. Executables are often called
497 *binaries* (as in `/usr/bin`, if you’re on a Unix system).
499 Cargo has generated two files and one directory for us: a `Cargo.toml` and a
500 *src* directory with a *main.rs* file inside. These should look familiar,
501 they’re exactly what we created by hand, above.
503 This output is all you need to get started. First, open `Cargo.toml`. It should
504 look something like this:
511 authors = ["Your Name <you@example.com>"]
516 Do not worry about the `[dependencies]` line, we will come back to it later.
518 Cargo has populated *Cargo.toml* with reasonable defaults based on the arguments
519 you gave it and your `git` global configuration. You may notice that Cargo has
520 also initialized the `hello_world` directory as a `git` repository.
522 Here’s what should be in `src/main.rs`:
526 println!("Hello, world!");
530 Cargo has generated a "Hello World!" for you, and you’re ready to start coding!
532 > Note: If you want to look at Cargo in more detail, check out the official [Cargo
533 guide], which covers all of its features.
535 [Cargo guide]: http://doc.crates.io/guide.html
539 This chapter covered the basics that will serve you well through the rest of
540 this book, and the rest of your time with Rust. Now that you’ve got the tools
541 down, we'll cover more about the Rust language itself.
543 You have two options: Dive into a project with ‘[Tutorial: Guessing Game][guessinggame]’, or
544 start from the bottom and work your way up with ‘[Syntax and
545 Semantics][syntax]’. More experienced systems programmers will probably prefer
546 ‘Tutorial: Guessing Game’, while those from dynamic backgrounds may enjoy either. Different
547 people learn differently! Choose whatever’s right for you.
549 [guessinggame]: guessing-game.html
550 [syntax]: syntax-and-semantics.html