]> git.proxmox.com Git - rustc.git/blob - src/doc/book/nostarch/chapter01.md
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / book / nostarch / chapter01.md
1 <!-- DO NOT EDIT THIS FILE.
2
3 This file is periodically generated from the content in the `/src/`
4 directory, so all fixes need to be made in `/src/`.
5 -->
6
7 [TOC]
8
9 # Getting Started
10
11 Let’s start your Rust journey! There’s a lot to learn, but every journey starts
12 somewhere. In this chapter, we’ll discuss:
13
14 * Installing Rust on Linux, macOS, and Windows
15 * Writing a program that prints `Hello, world!`
16 * Using `cargo`, Rust’s package manager and build system
17
18 ## Installation
19
20 The first step is to install Rust. We’ll download Rust through `rustup`, a
21 command line tool for managing Rust versions and associated tools. You’ll need
22 an internet connection for the download.
23
24 > Note: If you prefer not to use `rustup` for some reason, please see the
25 > Other Rust Installation Methods page at
26 > *https://forge.rust-lang.org/infra/other-installation-methods.html* for more
27 > options.
28
29 The following steps install the latest stable version of the Rust compiler.
30 Rust’s stability guarantees ensure that all the examples in the book that
31 compile will continue to compile with newer Rust versions. The output might
32 differ slightly between versions, because Rust often improves error messages
33 and warnings. In other words, any newer, stable version of Rust you install
34 using these steps should work as expected with the content of this book.
35
36 > ### Command Line Notation
37 >
38 > In this chapter and throughout the book, we’ll show some commands used in the
39 > terminal. Lines that you should enter in a terminal all start with `$`. You
40 > don’t need to type in the `$` character; it’s the command line prompt shown
41 > to indicate the start of each command. Lines that don’t start with `$`
42 > typically show the output of the previous command. Additionally,
43 > PowerShell-specific examples will use `>` rather than `$`.
44
45 ### Installing `rustup` on Linux or macOS
46
47 If you’re using Linux or macOS, open a terminal and enter the following command:
48
49 ```
50 $ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh
51 ```
52
53 The command downloads a script and starts the installation of the `rustup`
54 tool, which installs the latest stable version of Rust. You might be prompted
55 for your password. If the install is successful, the following line will appear:
56
57 ```
58 Rust is installed now. Great!
59 ```
60
61 You will also need a *linker*, which is a program that Rust uses to join its
62 compiled outputs into one file. It is likely you already have one. If you get
63 linker errors, you should install a C compiler, which will typically include a
64 linker. A C compiler is also useful because some common Rust packages depend on
65 C code and will need a C compiler.
66
67 On macOS, you can get a C compiler by running:
68
69 ```
70 $ xcode-select --install
71 ```
72
73 Linux users should generally install GCC or Clang, according to their
74 distribution’s documentation. For example, if you use Ubuntu, you can install
75 the `build-essential` package.
76
77 ### Installing `rustup` on Windows
78
79 On Windows, go to *https://www.rust-lang.org/tools/install* and follow the
80 instructions for installing Rust. At some point in the installation, you’ll
81 receive a message explaining that you’ll also need the MSVC build tools for
82 Visual Studio 2013 or later.
83 <!-- is this still true: you need 2013 or later? /LC -->
84 <!-- Yup, I have verified /Carol -->
85 To acquire the build tools, you’ll need to
86 install Visual Studio 2022
87 <!-- and is VS 2019 still the right/best version? /LC -->
88 <!-- Just checked, there's now VS 2022! /Carol -->
89 from *https://visualstudio.microsoft.com/downloads/*. When asked which
90 workloads to install, include:
91
92 - “Desktop Development with C++”
93 - The Windows 10 or 11 SDK
94 - The English language pack component, along with any other language pack of
95 your choosing
96
97 <!-- Liz: We do want to recommend the English language pack along with whatever
98 other languages the reader speaks-- otherwise, sometimes error messages are
99 printed strangely
100 https://github.com/rust-lang/rust/issues/35785#issuecomment-735051657 /Carol -->
101
102 The rest of this book uses commands that work in both *cmd.exe* and PowerShell.
103 If there are specific differences, we’ll explain which to use.
104
105 ### Troubleshooting
106
107 To check whether you have Rust installed correctly, open a shell and enter this
108 line:
109
110 ```
111 $ rustc --version
112 ```
113
114 You should see the version number, commit hash, and commit date for the latest
115 stable version that has been released in the following format:
116
117 ```
118 rustc x.y.z (abcabcabc yyyy-mm-dd)
119 ```
120
121 If you see this information, you have installed Rust successfully! If you don’t
122 see this information and you’re on Windows, check that Rust is in your `%PATH%`
123 system variable. If that’s all correct and Rust still isn’t working, there are
124 a number of places you can get help. The easiest is the #beginners channel on
125 the official Rust Discord at *https://discord.gg/rust-lang*. There, you can
126 chat with other Rustaceans (a silly nickname we call ourselves) who can help
127 you out. Other great resources include the Users forum at
128 *https://users.rust-lang.org/* and Stack Overflow at
129 *https://stackoverflow.com/questions/tagged/rust*.
130
131 ### Updating and Uninstalling
132
133 Once Rust is installed via `rustup`, when a new version of Rust is released, updating to the latest version is
134 <!-- do you mean that the reader should immediately update to the latest
135 version, or just that when, at some point, they want to update, it's easy to
136 do? /LC -->
137 <!-- The latter; I've clarified /Carol -->
138 easy. From your shell, run the following update script:
139
140 ```
141 $ rustup update
142 ```
143
144 To uninstall Rust and `rustup`, run the following uninstall script from your
145 shell:
146
147 ```
148 $ rustup self uninstall
149 ```
150
151 ### Local Documentation
152
153 The installation of Rust also includes a local copy of the documentation, so
154 you can read it offline. Run `rustup doc` to open the local documentation in
155 your browser.
156
157 Any time a type or function is provided by the standard library and you’re not
158 sure what it does or how to use it, use the application programming interface
159 (API) documentation to find out!
160
161 ## Hello, World!
162
163 Now that you’ve installed Rust, let’s write your first Rust program. It’s
164 traditional when learning a new language to write a little program that prints
165 the text `Hello, world!` to the screen, so we’ll do the same here!
166
167 > Note: This book assumes basic familiarity with the command line. Rust makes
168 > no specific demands about your editing or tooling or where your code lives, so
169 > if you prefer to use an integrated development environment (IDE) instead of
170 > the command line, feel free to use your favorite IDE. Many IDEs now have some
171 > degree of Rust support; check the IDE’s documentation for details. Recently,
172 > the Rust team has been focusing on enabling great IDE support, and progress
173 > has been made rapidly on that front!
174
175 ### Creating a Project Directory
176
177 You’ll start by making a directory to store your Rust code. It doesn’t matter
178 to Rust where your code lives, but for the exercises and projects in this book,
179 we suggest making a *projects* directory in your home directory and keeping all
180 your projects there.
181
182 Open a terminal and enter the following commands to make a *projects* directory
183 and a directory for the “Hello, world!” project within the *projects* directory.
184
185 For Linux, macOS, and PowerShell on Windows, enter this:
186
187 ```
188 $ mkdir ~/projects
189 $ cd ~/projects
190 $ mkdir hello_world
191 $ cd hello_world
192 ```
193
194 For Windows CMD, enter this:
195
196 ```
197 > mkdir "%USERPROFILE%\projects"
198 > cd /d "%USERPROFILE%\projects"
199 > mkdir hello_world
200 > cd hello_world
201 ```
202
203 ### Writing and Running a Rust Program
204
205 Next, make a new source file and call it *main.rs*. Rust files always end with
206 the *.rs* extension. If you’re using more than one word in your filename, the
207 convention is to use an underscore to separate them. For example, use
208 *hello_world.rs* rather than *helloworld.rs*.
209
210 Now open the *main.rs* file you just created and enter the code in Listing 1-1.
211
212 Filename: main.rs
213
214 ```
215 fn main() {
216 println!("Hello, world!");
217 }
218 ```
219
220 Listing 1-1: A program that prints `Hello, world!`
221
222 Save the file and go back to your terminal window in the
223 *~/projects/hello_world* directory. On Linux or macOS, enter the following
224 commands to compile and run the file:
225 <!-- just to be clear, are we in the projects folder at this point? or a subfolder? /LC -->
226 <!-- In the hello_world subfolder, as that's where we left the terminal in the
227 "Creating a project directory" section. I've added the path here for clarity
228 /Carol -->
229
230 ```
231 $ rustc main.rs
232 $ ./main
233 Hello, world!
234 ```
235
236 On Windows, enter the command `.\main.exe` instead of `./main`:
237
238 ```
239 > rustc main.rs
240 > .\main.exe
241 Hello, world!
242 ```
243
244 Regardless of your operating system, the string `Hello, world!` should print to
245 the terminal. If you don’t see this output, refer back to the “Troubleshooting”
246 part of the Installation section for ways to get help.
247
248 If `Hello, world!` did print, congratulations! You’ve officially written a Rust
249 program. That makes you a Rust programmer—welcome!
250
251 ### Anatomy of a Rust Program
252
253 Let’s review this “Hello, world!” program in detail. Here’s the first piece of
254 the puzzle:
255
256 ```
257 fn main() {
258
259 }
260 ```
261
262 These lines define a function named `main`. The `main` function is special: it
263 is always the first code that runs in every executable Rust program. Here, the
264 first line declares a function named `main` that has no parameters and returns
265 nothing. If there were parameters, they would go inside the parentheses `()`.
266
267 The function body is wrapped in `{}`. Rust requires curly brackets around all
268 function bodies. It’s good style to place the opening curly bracket on the same
269 line as the function declaration, adding one space in between.
270
271 > Note: If you want to stick to a standard style across Rust projects, you can
272 > use an automatic formatter tool called `rustfmt` to format your code in a
273 > particular style (more on `rustfmt` in Appendix D). The Rust team has
274 > included this tool with the standard Rust distribution, like `rustc`, so it
275 > should already be installed on your computer!
276
277 The body of the the `main` function holds the following code:
278
279 ```
280 println!("Hello, world!");
281 ```
282
283 This line does all the work in this little program: it prints text to the
284 screen. There are four important details to notice here.
285
286 First, Rust style is to indent with four spaces, not a tab.
287
288 Second, `println!` calls a Rust macro. If it had called a function instead, it
289 would be entered as `println` (without the `!`). We’ll discuss Rust macros in
290 more detail in Chapter 19. For now, you just need to know that using a `!`
291 means that you’re calling a macro instead of a normal function, and that macros
292 don’t always follow the same rules as functions.
293
294 Third, you see the `"Hello, world!"` string. We pass this string as an argument
295 to `println!`, and the string is printed to the screen.
296
297 Fourth, we end the line with a semicolon (`;`), which indicates that this
298 expression is over and the next one is ready to begin. Most lines of Rust code
299 end with a semicolon.
300
301 ### Compiling and Running Are Separate Steps
302
303 You’ve just run a newly created program, so let’s examine each step in the
304 process.
305
306 Before running a Rust program, you must compile it using the Rust compiler by
307 entering the `rustc` command and passing it the name of your source file, like
308 this:
309
310 ```
311 $ rustc main.rs
312 ```
313
314 If you have a C or C++ background, you’ll notice that this is similar to `gcc`
315 or `clang`. After compiling successfully, Rust outputs a binary executable.
316
317 On Linux, macOS, and PowerShell on Windows, you can see the executable by
318 entering the `ls` command in your shell. On Linux and macOS, you’ll see two
319 files. With PowerShell on Windows, you’ll see the same three files that you
320 would see using CMD.
321
322 ```
323 $ ls
324 main main.rs
325 ```
326
327 With CMD on Windows, you would enter the following:
328
329 ```
330 > dir /B %= the /B option says to only show the file names =%
331 main.exe
332 main.pdb
333 main.rs
334 ```
335
336 This shows the source code file with the *.rs* extension, the executable file
337 (*main.exe* on Windows, but *main* on all other platforms), and, when using
338 Windows, a file containing debugging information with the *.pdb* extension.
339 From here, you run the *main* or *main.exe* file, like this:
340
341 ```
342 $ ./main # or .\main.exe on Windows
343 ```
344
345 If your *main.rs* is your “Hello, world!” program, this line prints `Hello,
346 world!` to your terminal.
347
348 If you’re more familiar with a dynamic language, such as Ruby, Python, or
349 JavaScript, you might not be used to compiling and running a program as
350 separate steps. Rust is an *ahead-of-time compiled* language, meaning you can
351 compile a program and give the executable to someone else, and they can run it
352 even without having Rust installed. If you give someone a *.rb*, *.py*, or
353 *.js* file, they need to have a Ruby, Python, or JavaScript implementation
354 installed (respectively). But in those languages, you only need one command to
355 compile and run your program. Everything is a trade-off in language design.
356
357 Just compiling with `rustc` is fine for simple programs, but as your project
358 grows, you’ll want to manage all the options and make it easy to share your
359 code. Next, we’ll introduce you to the Cargo tool, which will help you write
360 real-world Rust programs.
361
362 ## Hello, Cargo!
363
364 Cargo is Rust’s build system and package manager. Most Rustaceans use this tool
365 to manage their Rust projects because Cargo handles a lot of tasks for you,
366 such as building your code, downloading the libraries your code depends on, and
367 building those libraries. (We call the libraries that your code needs
368 *dependencies*.)
369
370 The simplest Rust programs, like the one we’ve written so far, don’t have any
371 dependencies. If we had built the “Hello, world!” project with Cargo, it would
372 only use the part of Cargo that handles building your code. As you write more
373 complex Rust programs, you’ll add dependencies, and if you start a project
374 using Cargo, adding dependencies will be much easier to do.
375
376 Because the vast majority of Rust projects use Cargo, the rest of this book
377 assumes that you’re using Cargo too. Cargo comes installed with Rust if you
378 used the official installers discussed in the “Installation” section. If you
379 installed Rust through some other means, check whether Cargo is installed by
380 entering the following into your terminal:
381
382 ```
383 $ cargo --version
384 ```
385
386 If you see a version number, you have it! If you see an error, such as `command
387 not found`, look at the documentation for your method of installation to
388 determine how to install Cargo separately.
389
390 ### Creating a Project with Cargo
391
392 Let’s create a new project using Cargo and look at how it differs from our
393 original “Hello, world!” project. Navigate back to your *projects* directory (or
394 wherever you decided to store your code). Then, on any operating system, run
395 the following:
396
397 ```
398 $ cargo new hello_cargo
399 $ cd hello_cargo
400 ```
401
402 The first command creates a new directory and project called *hello_cargo*.
403 We’ve named our project *hello_cargo*, and Cargo creates its files in a
404 directory of the same name.
405
406 Go into the *hello_cargo* directory and list the files. You’ll see that Cargo
407 has generated two files and one directory for us: a *Cargo.toml* file and a
408 *src* directory with a *main.rs* file inside.
409
410 It has also initialized a new Git repository along with a *.gitignore* file.
411 Git files won’t be generated if you run `cargo new` within an existing Git
412 repository; you can override this behavior by using `cargo new --vcs=git`.
413
414 > Note: Git is a common version control system. You can change `cargo new` to
415 > use a different version control system or no version control system by using
416 > the `--vcs` flag. Run `cargo new --help` to see the available options.
417
418 Open *Cargo.toml* in your text editor of choice. It should look similar to the
419 code in Listing 1-2.
420
421 Filename: Cargo.toml
422
423 ```
424 [package]
425 name = "hello_cargo"
426 version = "0.1.0"
427 edition = "2021"
428
429 [dependencies]
430 ```
431
432 Listing 1-2: Contents of *Cargo.toml* generated by `cargo new`
433
434 This file is in the *TOML* (*Tom’s Obvious, Minimal Language*) format, which is
435 Cargo’s configuration format.
436
437 The first line, `[package]`, is a section heading that indicates that the
438 following statements are configuring a package. As we add more information to
439 this file, we’ll add other sections.
440
441 The next three lines set the configuration information Cargo needs to compile
442 your program: the name, the version, and the edition of Rust to use. We’ll talk
443 about the `edition` key in Appendix E.
444
445 The last line, `[dependencies]`, is the start of a section for you to list any
446 of your project’s dependencies. In Rust, packages of code are referred to as
447 *crates*. We won’t need any other crates for this project, but we will in the
448 first project in Chapter 2, so we’ll use this dependencies section then.
449
450 Now open *src/main.rs* and take a look:
451
452 Filename: src/main.rs
453
454 ```
455 fn main() {
456 println!("Hello, world!");
457 }
458 ```
459
460 Cargo has generated a “Hello, world!” program for you, just like the one we
461 wrote in Listing 1-1! So far, the differences between our project and the
462 project Cargo generated are that Cargo placed the code in the *src* directory,
463 and we have a *Cargo.toml* configuration file in the top directory.
464
465 Cargo expects your source files to live inside the *src* directory. The
466 top-level project directory is just for README files, license information,
467 configuration files, and anything else not related to your code. Using Cargo
468 helps you organize your projects. There’s a place for everything, and
469 everything is in its place.
470
471 If you started a project that doesn’t use Cargo, as we did with the “Hello,
472 world!” project, you can convert it to a project that does use Cargo. Move the
473 project code into the *src* directory and create an appropriate *Cargo.toml*
474 file.
475
476 ### Building and Running a Cargo Project
477
478 Now let’s look at what’s different when we build and run the “Hello, world!”
479 program with Cargo! From your *hello_cargo* directory, build your project by
480 entering the following command:
481
482 ```
483 $ cargo build
484 Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
485 Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
486 ```
487
488 This command creates an executable file in *target/debug/hello_cargo* (or
489 *target\debug\hello_cargo.exe* on Windows) rather than in your current
490 <!-- why does it put it in a debug folder? Interesting to know, because it seems
491 laborious to have to enter the whole path to run the executable /LC -->
492 <!-- Because `build` uses debug settings by default, and the compiler tries to
493 make it clear that this isn't a release build by storing it in the `debug`
494 path. Most people use `cargo run` instead, which is what we show in a few
495 paragraphs. We talk about building for release mode in the next section; do you
496 think it needs to be mentioned here too? I think it would be somewhat
497 distracting and repetitive to get into that right here... /Carol -->
498 directory. You can run the executable with this command:
499
500 ```
501 $ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
502 Hello, world!
503 ```
504
505 If all goes well, `Hello, world!` should print to the terminal. Running `cargo
506 build` for the first time also causes Cargo to create a new file at the top
507 level: *Cargo.lock*. This file keeps track of the exact versions of
508 dependencies in your project. This project doesn’t have dependencies, so the
509 file is a bit sparse. You won’t ever need to change this file manually; Cargo
510 manages its contents for you.
511
512 We just built a project with `cargo build` and ran it with
513 `./target/debug/hello_cargo`, but we can also use `cargo run` to compile the
514 code and then run the resulting executable all in one command:
515
516 ```
517 $ cargo run
518 Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
519 Running `target/debug/hello_cargo`
520 Hello, world!
521 ```
522
523 Using `cargo run` is more convenient than having to remember to run `cargo
524 build` and then use the whole path to the binary, so most developers use `cargo
525 run`.
526 <!-- Liz: I added this note here to address the above comment about
527 laboriousness. The idea was to show `cargo build`, talk about where the result
528 of that ends up, then show that `cargo run` does those two steps in one command.
529 Do you think that works or does this section need to be reordered somehow?
530 /Carol -->
531
532 Notice that this time we didn’t see output indicating that Cargo was compiling
533 `hello_cargo`. Cargo figured out that the files hadn’t changed, so it didn’t
534 rebuild but just ran the binary. If you had modified your source code, Cargo
535 would have rebuilt the project before running it, and you would have seen this
536 output:
537
538 ```
539 $ cargo run
540 Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
541 Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
542 Running `target/debug/hello_cargo`
543 Hello, world!
544 ```
545
546 Cargo also provides a command called `cargo check`. This command quickly checks
547 your code to make sure it compiles but doesn’t produce an executable:
548
549 ```
550 $ cargo check
551 Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
552 Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
553 ```
554
555 Why would you not want an executable? Often, `cargo check` is much faster than
556 `cargo build`, because it skips the step of producing an executable. If you’re
557 continually checking your work while writing the code, using `cargo check` will
558 speed up the process of letting you know if your project is still compiling! As
559 such, many Rustaceans run `cargo check` periodically as they write their
560 program to make sure it compiles. Then they run `cargo build` when they’re
561 ready to use the executable.
562
563 Let’s recap what we’ve learned so far about Cargo:
564
565 * We can create a project using `cargo new`.
566 * We can build a project using `cargo build`.
567 * We can build and run a project in one step using `cargo run`.
568 * We can build a project without producing a binary to check for errors using
569 `cargo check`.
570 * Instead of saving the result of the build in the same directory as our code,
571 Cargo stores it in the *target/debug* directory.
572
573 An additional advantage of using Cargo is that the commands are the same no
574 matter which operating system you’re working on. So, at this point, we’ll no
575 longer provide specific instructions for Linux and macOS versus Windows.
576
577 ### Building for Release
578
579 When your project is finally ready for release, you can use `cargo build
580 --release` to compile it with optimizations. This command will create an
581 executable in *target/release* instead of *target/debug*. The optimizations
582 make your Rust code run faster, but turning them on lengthens the time it takes
583 for your program to compile. This is why there are two different profiles: one
584 for development, when you want to rebuild quickly and often, and another for
585 building the final program you’ll give to a user that won’t be rebuilt
586 repeatedly and that will run as fast as possible. If you’re benchmarking your
587 code’s running time, be sure to run `cargo build --release` and benchmark with
588 the executable in *target/release*.
589
590 ### Cargo as Convention
591
592 With simple projects, Cargo doesn’t provide a lot of value over just using
593 `rustc`, but it will prove its worth as your programs become more intricate.
594 With complex projects composed of multiple crates, it’s much easier to let
595 Cargo coordinate the build.
596
597 Even though the `hello_cargo` project is simple, it now uses much of the real
598 tooling you’ll use in the rest of your Rust career. In fact, to work on any
599 existing projects, you can use the following commands to check out the code
600 using Git, change to that project’s directory, and build:
601
602 ```
603 $ git clone example.org/someproject
604 $ cd someproject
605 $ cargo build
606 ```
607
608 For more information about Cargo, check out its documentation at *https://doc.rust-lang.org/cargo/*.
609
610 ## Summary
611
612 You’re already off to a great start on your Rust journey! In this chapter,
613 you’ve learned how to:
614
615 * Install the latest stable version of Rust using `rustup`
616 * Update to a newer Rust version
617 * Open locally installed documentation
618 * Write and run a “Hello, world!” program using `rustc` directly
619 * Create and run a new project using the conventions of Cargo
620
621 This is a great time to build a more substantial program to get used to reading
622 and writing Rust code. So, in Chapter 2, we’ll build a guessing game program.
623 If you would rather start by learning how common programming concepts work in
624 Rust, see Chapter 3 and then return to Chapter 2.