]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/getting-started.md
Fixes as per @brson's review
[rust.git] / src / doc / trpl / getting-started.md
1 % Getting Started
2
3 This first section 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.
6
7 # Installing Rust
8
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 chapter, as we’ll be
11 downloading Rust from the internet.
12
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.
18
19 ## Platform support
20
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.
24
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.
28
29 ### Tier 1
30
31 Tier 1 platforms can be thought of as "guaranteed to build and work".
32 Specifically they will each satisfy the following requirements:
33
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
36   tests passing.
37 * Official release artifacts are provided for the platform.
38 * Documentation for how to use and how to build the platform is available.
39
40 |  Target                       | std |rustc|cargo| notes                      |
41 |-------------------------------|-----|-----|-----|----------------------------|
42 | `x86_64-pc-windows-msvc`      |  ✓  |  ✓  |  ✓  | 64-bit MSVC (Windows 7+)   |
43 | `i686-pc-windows-gnu`         |  ✓  |  ✓  |  ✓  | 32-bit MinGW (Windows 7+)  |
44 | `x86_64-pc-windows-gnu`       |  ✓  |  ✓  |  ✓  | 64-bit MinGW (Windows 7+)  |
45 | `i686-apple-darwin`           |  ✓  |  ✓  |  ✓  | 32-bit OSX (10.7+, Lion+)  |
46 | `x86_64-apple-darwin`         |  ✓  |  ✓  |  ✓  | 64-bit OSX (10.7+, Lion+)  |
47 | `i686-unknown-linux-gnu`      |  ✓  |  ✓  |  ✓  | 32-bit Linux (2.6.18+)     |
48 | `x86_64-unknown-linux-gnu`    |  ✓  |  ✓  |  ✓  | 64-bit Linux (2.6.18+)     |
49
50 ### Tier 2
51
52 Tier 2 platforms can be thought of as "guaranteed to build". Automated tests
53 are not run so it's not guaranteed to produce a working build, but platforms
54 often work to quite a good degree and patches are always welcome! Specifically,
55 these platforms are required to have each of the following:
56
57 * Automated building is set up, but may not be running tests.
58 * Landing changes to the `rust-lang/rust` repository's master branch is gated on
59   platforms **building**. Note that this means for some platforms only the
60   standard library is compiled, but for others the full bootstrap is run.
61 * Official release artifacts are provided for the platform.
62
63 |  Target                       | std |rustc|cargo| notes                      |
64 |-------------------------------|-----|-----|-----|----------------------------|
65 | `i686-pc-windows-msvc`        |  ✓  |  ✓  |  ✓  | 32-bit MSVC (Windows 7+)   |
66
67 ### Tier 3
68
69 Tier 3 platforms are those which Rust has support for, but landing changes is
70 not gated on the platform either building or passing tests. Working builds for
71 these platforms may be spotty as their reliability is often defined in terms of
72 community contributions. Additionally, release artifacts and installers are not
73 provided, but there may be community infrastructure producing these in
74 unofficial locations.
75
76 |  Target                       | std |rustc|cargo| notes                      |
77 |-------------------------------|-----|-----|-----|----------------------------|
78 | `x86_64-unknown-linux-musl`   |  ✓  |     |     | 64-bit Linux with MUSL     |
79 | `arm-linux-androideabi`       |  ✓  |     |     | ARM Android                |
80 | `i686-linux-android`          |  ✓  |     |     | 32-bit x86 Android         |
81 | `aarch64-linux-android`       |  ✓  |     |     | ARM64 Android              |
82 | `arm-unknown-linux-gnueabi`   |  ✓  |  ✓  |     | ARM Linux (2.6.18+)        |
83 | `arm-unknown-linux-gnueabihf` |  ✓  |  ✓  |     | ARM Linux (2.6.18+)        |
84 | `aarch64-unknown-linux-gnu`   |  ✓  |     |     | ARM64 Linux (2.6.18+)      |
85 | `mips-unknown-linux-gnu`      |  ✓  |     |     | MIPS Linux (2.6.18+)       |
86 | `mipsel-unknown-linux-gnu`    |  ✓  |     |     | MIPS (LE) Linux (2.6.18+)  |
87 | `powerpc-unknown-linux-gnu`   |  ✓  |     |     | PowerPC Linux (2.6.18+)    |
88 | `i386-apple-ios`              |  ✓  |     |     | 32-bit x86 iOS             |
89 | `x86_64-apple-ios`            |  ✓  |     |     | 64-bit x86 iOS             |
90 | `armv7-apple-ios`             |  ✓  |     |     | ARM iOS                    |
91 | `armv7s-apple-ios`            |  ✓  |     |     | ARM iOS                    |
92 | `aarch64-apple-ios`           |  ✓  |     |     | ARM64 iOS                  |
93 | `i686-unknown-freebsd`        |  ✓  |  ✓  |     | 32-bit FreeBSD             |
94 | `x86_64-unknown-freebsd`      |  ✓  |  ✓  |     | 64-bit FreeBSD             |
95 | `x86_64-unknown-openbsd`      |  ✓  |  ✓  |     | 64-bit OpenBSD             |
96 | `x86_64-unknown-netbsd`       |  ✓  |  ✓  |     | 64-bit NetBSD              |
97 | `x86_64-unknown-bitrig`       |  ✓  |  ✓  |     | 64-bit Bitrig              |
98 | `x86_64-unknown-dragonfly`    |  ✓  |  ✓  |     | 64-bit DragonFlyBSD        |
99 | `x86_64-rumprun-netbsd`       |  ✓  |     |     | 64-bit NetBSD Rump Kernel  |
100 | `i686-pc-windows-msvc` (XP)   |  ✓  |     |     | Windows XP support         |
101 | `x86_64-pc-windows-msvc` (XP) |  ✓  |     |     | Windows XP support         |
102
103 Note that this table can be expanded over time, this isn't the exhaustive set of
104 tier 3 platforms that will ever be!
105
106 ## Installing on Linux or Mac
107
108 If we're on Linux or a Mac, all we need to do is open a terminal and type this:
109
110 ```bash
111 $ curl -sSf https://static.rust-lang.org/rustup.sh | sh
112 ```
113
114 This will download a script, and stat the installation. If it all goes well,
115 you’ll see this appear:
116
117 ```text
118 Welcome to Rust.
119
120 This script will download the Rust compiler and its package manager, Cargo, and
121 install them to /usr/local. You may install elsewhere by running this script
122 with the --prefix=<path> option.
123
124 The installer will run under ‘sudo’ and may ask you for your password. If you do
125 not want the script to run ‘sudo’ then pass it the --disable-sudo flag.
126
127 You may uninstall later by running /usr/local/lib/rustlib/uninstall.sh,
128 or by running this script again with the --uninstall flag.
129
130 Continue? (y/N) 
131 ```
132
133 From here, press `y` for ‘yes’, and then follow the rest of the prompts.
134
135 ## Installing on Windows
136
137 If you're on Windows, please download the appropriate [installer][install-page].
138
139 [install-page]: https://www.rust-lang.org/install.html
140
141 ## Uninstalling
142
143 Uninstalling Rust is as easy as installing it. On Linux or Mac, just run
144 the uninstall script:
145
146 ```bash
147 $ sudo /usr/local/lib/rustlib/uninstall.sh
148 ```
149
150 If we used the Windows installer, we can re-run the `.msi` and it will give us
151 an uninstall option.
152
153 ## Troubleshooting
154
155 If we've got Rust installed, we can open up a shell, and type this:
156
157 ```bash
158 $ rustc --version
159 ```
160
161 You should see the version number, commit hash, and commit date.
162
163 If you do, Rust has been installed successfully! Congrats!
164
165 If you don't and you're on Windows, check that Rust is in your %PATH% system
166 variable. If it isn't, run the installer again, select "Change" on the "Change,
167 repair, or remove installation" page and ensure "Add to PATH" is installed on
168 the local hard drive.
169
170 If not, there are a number of places where we can get help. The easiest is
171 [the #rust IRC channel on irc.mozilla.org][irc], which we can access through
172 [Mibbit][mibbit]. Click that link, and we'll be chatting with other Rustaceans
173 (a silly nickname we call ourselves) who can help us out. Other great resources
174 include [the user’s forum][users], and [Stack Overflow][stackoverflow].
175
176 [irc]: irc://irc.mozilla.org/#rust
177 [mibbit]: http://chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust
178 [users]: https://users.rust-lang.org/
179 [stackoverflow]: http://stackoverflow.com/questions/tagged/rust
180
181 This installer also installs a copy of the documentation locally, so we can
182 read it offline. On UNIX systems, `/usr/local/share/doc/rust` is the location.
183 On Windows, it's in a `share/doc` directory, inside the directory to which Rust
184 was installed.
185
186 # Hello, world!
187
188 Now that you have Rust installed, we'll help you write your first Rust program.
189 It's traditional when learning a new language to write a little program to
190 print the text “Hello, world!” to the screen, and in this section, we'll follow
191 that tradition. 
192
193 The nice thing about starting with such a simple program is that you can
194 quickly verify that your compiler is installed, and that it's working properly.
195 Printing information to the screen is also just a pretty common thing to do, so
196 practicing it early on is good.
197
198 > Note: This book assumes basic familiarity with the command line. Rust itself
199 > makes no specific demands about your editing, tooling, or where your code
200 > lives, so if you prefer an IDE to the command line, that's an option. You may
201 > want to check out [SolidOak], which was built specifically with Rust in mind.
202 > There are a number of extensions in development by the community, and the
203 > Rust team ships plugins for [various editors]. Configuring your editor or
204 > IDE is out of the scope of this tutorial, so check the documentation for your
205 > specific setup. 
206
207 [SolidOak]: https://github.com/oakes/SolidOak
208 [various editors]: https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md
209
210 ## Creating a Project File
211
212 First, make a file to put your Rust code in. Rust doesn't care where your code
213 lives, but for this book, I suggest making a *projects* directory in your home
214 directory, and keeping all your projects there. Open a terminal and enter the
215 following commands to make a directory for this particular project:
216
217 ```bash
218 $ mkdir ~/projects
219 $ cd ~/projects
220 $ mkdir hello_world
221 $ cd hello_world
222 ```
223
224 > Note: If you’re on Windows and not using PowerShell, the `~` may not work.
225 > Consult the documentation for your shell for more details.
226
227 ## Writing and Running a Rust Program
228
229 Next, make a new source file and call it *main.rs*. Rust files always end
230 in a *.rs* extension. If you’re using more than one word in your filename, use
231 an underscore to separate them; for example, you'd use *hello_world.rs* rather
232 than *helloworld.rs*.
233
234 Now open the *main.rs* file you just created, and type the following code:
235
236 ```rust
237 fn main() {
238     println!("Hello, world!");
239 }
240 ```
241
242 Save the file, and go back to your terminal window. On Linux or OSX, enter the
243 following commands:
244
245 ```bash
246 $ rustc main.rs
247 $ ./main 
248 Hello, world!
249 ```
250
251 In Windows, just replace `main` with `main.exe`. Regardless of your operating
252 system, you should see the string `Hello, world!` print to the terminal. If you
253 did, then congratulations! You've officially written a Rust program. That makes
254 you a Rust programmer! Welcome. 
255
256 ## Anatomy of a Rust Program
257
258 Now, let’s go over what just happened in your "Hello, world!" program in
259 detail. Here's the first piece of the puzzle:
260
261 ```rust
262 fn main() {
263
264 }
265 ```
266
267 These lines define a *function* in Rust. The `main` function is special: it's
268 the beginning of every Rust program. The first line says, “I’m declaring a
269 function named `main` that takes no arguments and returns nothing.” If there
270 were arguments, they would go inside the parentheses (`(` and `)`), and because
271 we aren’t returning anything from this function, we can omit the return type
272 entirely.
273
274 Also note that the function body is wrapped in curly braces (`{` and `}`). Rust
275 requires these around all function bodies. It's considered good style to put
276 the opening curly brace on the same line as the function declaration, with one
277 space in between.
278
279 Inside the `main()` function:
280
281 ```rust
282     println!("Hello, world!");
283 ```
284
285 This line does all of the work in this little program: it prints text to the
286 screen. There are a number of details that are important here. The first is
287 that it’s indented with four spaces, not tabs.
288  
289 The second important part is the `println!()` line. This is calling a Rust
290 *[macro]*, which is how metaprogramming is done in Rust. If it were calling a
291 function instead, it would look like this: `println()` (without the !). We'll
292 discuss Rust macros in more detail later, but for now you just need to
293 know that when you see a `!` that means that you’re calling a macro instead of
294 a normal function. 
295
296
297 [macro]: macros.html
298
299 Next is `"Hello, world!"` which is a *string*. Strings are a surprisingly
300 complicated topic in a systems programming language, and this is a *[statically
301 allocated]* string. We pass this string as an argument to `println!`, which
302 prints the string to the screen. Easy enough!
303
304 [statically allocated]: the-stack-and-the-heap.html
305
306 The line ends with a semicolon (`;`). Rust is an *[expression oriented]*
307 language, which means that most things are expressions, rather than statements.
308 The `;` indicates that this expression is over, and the next one is ready to
309 begin. Most lines of Rust code end with a `;`.
310
311 [expression-oriented language]: glossary.html#expression-oriented-language
312
313 ## Compiling and Running Are Separate Steps
314
315 In "Writing and Running a Rust Program", we showed you how to run a newly
316 created program. We'll break that process down and examine each step now. 
317
318 Before running a Rust program, you have to compile it. You can use the Rust
319 compiler by entering the `rustc` command and passing it the name of your source
320 file, like this:
321
322 ```bash
323 $ rustc main.rs
324 ```
325
326 If you come from a C or C++ background, you'll notice that this is similar to
327 `gcc` or `clang`. After compiling successfully, Rust should output a binary
328 executable, which you can see on Linux or OSX by entering the `ls` command in
329 your shell as follows:
330
331 ```bash
332 $ ls
333 main  main.rs
334 ```
335
336 On Windows, you'd enter:
337
338 ```bash
339 $ dir
340 main.exe  main.rs
341 ```
342
343 This shows we have two files: the source code, with an `.rs` extension, and the
344 executable (`main.exe` on Windows, `main` everywhere else). All that's left to
345 do from here is run the `main` or `main.exe` file, like this:
346
347 ```bash
348 $ ./main  # or main.exe on Windows
349 ```
350
351 If *main.rs* were your "Hello, world!" program, this would print `Hello,
352 world!` to your terminal.
353
354 If you come from a dynamic language like Ruby, Python, or JavaScript, you may
355 not be used to compiling and running a program being separate steps. Rust is an
356 *ahead-of-time compiled* language, which means that you can compile a program,
357 give it to someone else, and they can run it even without Rust installed. If
358 you give someone a `.rb` or `.py` or `.js` file, on the other hand, they need
359 to have a Ruby, Python, or JavaScript implementation installed (respectively),
360 but you only need one command to both compile and run your program. Everything
361 is a tradeoff in language design.
362
363 Just compiling with `rustc` is fine for simple programs, but as your project
364 grows, you'll want to be able to manage all of the options your project has,
365 and make it easy to share your code with other people and projects. Next, I'll
366 introduce you to a tool called Cargo, which will help you write real-world Rust
367 programs.
368
369 # Hello, Cargo!
370
371 Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
372 manage their Rust projects. Cargo manages three things: building your code,
373 downloading the libraries your code depends on, and building those libraries.
374 We call libraries your code needs ‘dependencies’ since your code depends on
375 them.
376
377 The simplest Rust programs don’t have any dependencies, so right now, you'd
378 only use the first part of its functionality. As you write more complex Rust
379 programs, you’ll want to add dependencies, and if you start off using Cargo,
380 that will be a lot easier to do.
381
382 As the vast, vast majority of Rust projects use Cargo, we will assume that
383 you’re using it for the rest of the book. Cargo comes installed with Rust
384 itself, if you used the official installers. If you installed Rust through some
385 other means, you can check if you have Cargo installed by typing:
386
387 ```bash
388 $ cargo --version
389 ```
390
391 Into a terminal. If you see a version number, great! If you see an error like
392 ‘`command not found`’, then you should look at the documentation for the system
393 in which you installed Rust, to determine if Cargo is separate.
394
395 ## Converting to Cargo
396
397 Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
398 to do three things: 
399
400 1. Put your source file in the right directory.
401 2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere else)
402    and make a new one.
403 3. Make a Cargo configuration file.
404
405 Let's get started!
406
407 ### Creating a new Executable and Source Directory
408
409 First, go back to your terminal, move to your *hello_world* directory, and
410 enter the following commands:
411
412 ```bash
413 $ mkdir src
414 $ mv main.rs src/main.rs
415 $ rm main  # or 'del main.exe' on Windows
416 ```
417
418 Cargo expects your source files to live inside a *src* directory, so do that
419 first. This leaves the top-level project directory (in this case,
420 *hello_world*) for READMEs, license information, and anything else not related
421 to your code. In this way, using Cargo helps you keep your projects nice and
422 tidy. There's a place for everything, and everything is in its place. 
423
424 Now, copy *main.rs* to the *src* directory, and delete the compiled file you
425 created with `rustc`. As usual, replace `main` with `main.exe` if you're on
426 Windows.
427
428 This example retains `main.rs` as the source filename because it's creating an
429 executable. If you wanted to make a library instead, you'd name the file
430 `lib.rs`. This convention is used by Cargo to successfully compile your
431 projects, but it can be overridden if you wish. 
432
433 ### Creating a Configuration File
434
435 Next, create a new file inside your *hello_world* directory, and call it
436 `Cargo.toml`.
437
438 Make sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do
439 with the configuration file. 
440
441 This file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is
442 similar to INI, but has some extra goodies, and is used as Cargo’s
443 configuration format.
444
445 [TOML]: https://github.com/toml-lang/toml
446
447 Inside this file, type the following information:
448
449 ```toml
450 [package]
451
452 name = "hello_world"
453 version = "0.0.1"
454 authors = [ "Your name <you@example.com>" ]
455 ```
456
457 The first line, `[package]`, indicates that the following statements are
458 configuring a package. As we add more information to this file, we’ll add other
459 sections, but for now, we just have the package configuration.
460
461 The other three lines set the three bits of configuration that Cargo needs to
462 know to compile your program: its name, what version it is, and who wrote it.
463
464 Once you've added this information to the *Cargo.toml* file, save it to finish
465 creating the configuration file.
466
467 ## Building and Running a Cargo Project 
468
469 With your *Cargo.toml* file in place in your project's root directory, you
470 should be ready to build and run your Hello World program! To do so, enter the
471 following commands:
472
473 ```bash
474 $ cargo build
475    Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
476 $ ./target/debug/hello_world
477 Hello, world!
478 ```
479
480 Bam! If all goes well, `Hello, world!` should print to the terminal once more. 
481
482 You just built a project with `cargo build` and ran it with
483 `./target/debug/hello_world`, but you can actually do both in one step with
484 `cargo run` as follows:
485
486 ```bash
487 $ cargo run
488      Running `target/debug/hello_world`
489 Hello, world!
490 ```
491
492 Notice that this example didn’t re-build the project. Cargo figured out that
493 the file hasn’t changed, and so it just ran the binary. If you'd modified your
494 source code, Cargo would have rebuilt the project before running it, and you
495 would have seen something like this:
496
497 ```bash
498 $ cargo run
499    Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
500      Running `target/debug/hello_world`
501 Hello, world!
502 ```
503
504 Cargo checks to see if any of your project’s files have been modified, and only
505 rebuilds your project if they’ve changed since the last time you built it.
506
507 With simple projects, Cargo doesn't bring a whole lot over just using `rustc`,
508 but it will become useful in future. With complex projects composed of multiple
509 crates, it’s much easier to let Cargo coordinate the build. With Cargo, you can
510 just run `cargo build`, and it should work the right way.
511
512 ## Building for Release
513
514 When your project is finally 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.
519
520 Running this command also causes Cargo to create a new file called
521 *Cargo.lock*, which looks like this:
522
523 ```toml
524 [root]
525 name = "hello_world"
526 version = "0.0.1"
527 ```
528
529 Cargo uses the *Cargo.lock* file to keep track of dependencies in your
530 application. This is the Hello World project's *Cargo.lock* file. This project
531 doesn't have dependencies, so the file is a bit sparse. Realistically, you
532 won't ever need to touch this file yourself; just let Cargo handle it.
533
534 That’s it! If you've been following along, you should have successfully built
535 `hello_world` with Cargo. 
536
537 Even though the project is simple, it now uses much of the real tooling you’ll
538 use for the rest of your Rust career. In fact, you can expect to start
539 virtually all Rust projects with some variation on the following commands:
540
541 ```bash
542 $ git clone someurl.com/foo
543 $ cd foo
544 $ cargo build
545 ```
546
547 ## Making A New Cargo Project the Easy Way
548
549 You don’t have to go through that previous process every time you want to start
550 a new project! Cargo can quickly make a bare-bones project directory that you
551 can start developing in right away.
552
553 To start a new project with Cargo, enter `cargo new` at the command line:
554
555 ```bash
556 $ cargo new hello_world --bin
557 ```
558
559 This command passes `--bin` because the goal is to get straight to making an
560 executable application, as opposed to a library. Executables are often called
561 *binaries* (as in `/usr/bin`, if you’re on a Unix system).
562
563 Cargo has generated two files and one directory for us: a `Cargo.toml` and a
564 *src* directory with a *main.rs* file inside. These should look familliar,
565 they’re exactly what we created by hand, above.
566
567 This output is all you need to get started. First, open `Cargo.toml`. It should
568 look something like this:
569
570 ```toml
571 [package]
572
573 name = "hello_world"
574 version = "0.1.0"
575 authors = ["Your Name <you@example.com>"]
576 ```
577
578 Cargo has populated *Cargo.toml* with reasonable defaults based on the arguments
579 you gave it and your `git` global configuration. You may notice that Cargo has
580 also initialized the `hello_world` directory as a `git` repository.
581
582 Here’s what should be in `src/main.rs`:
583
584 ```rust
585 fn main() {
586     println!("Hello, world!");
587 }
588 ```
589
590 Cargo has generated a "Hello World!" for you, and you’re ready to start coding! 
591
592 > Note: If you want to look at Cargo in more detail, check out the official [Cargo
593 guide], which covers all of its features.
594
595 [Cargo guide]: http://doc.crates.io/guide.html
596
597 # Closing Thoughts
598
599 This chapter covered the basics that will serve you well through the rest of
600 this book, and the rest of your time with Rust. Now that you’ve got the tools
601 down, we'll cover more about the Rust language itself. 
602
603 You have two options: Dive into a project with ‘[Learn Rust][learnrust]’, or
604 start from the bottom and work your way up with ‘[Syntax and
605 Semantics][syntax]’. More experienced systems programmers will probably prefer
606 ‘Learn Rust’, while those from dynamic backgrounds may enjoy either. Different
607 people learn differently! Choose whatever’s right for you.
608
609 [learnrust]: learn-rust.html
610 [syntax]: syntax-and-semantics.html