]> git.proxmox.com Git - rustc.git/blob - src/doc/book/getting-started.md
5aae693ad6b54a48ba878f4b6d812350501e3118
[rustc.git] / src / doc / book / getting-started.md
1 % Getting Started
2
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.
6
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.
12
13 # Installing Rust
14
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.
18
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].
24
25 [platform-support]: https://forge.rust-lang.org/platform-support.html
26
27 ## Installing Rust
28
29 All you need to do on Unix systems like Linux and macOS is open a
30 terminal and type this:
31
32 ```bash
33 $ curl https://sh.rustup.rs -sSf | sh
34 ```
35
36 It will download a script, and start the installation. If everything
37 goes well, you’ll see this appear:
38
39 ```text
40 Rust is installed now. Great!
41 ```
42
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.
46
47 For other installation options and information, visit the [install]
48 page of the Rust website.
49
50 [rustup-init.exe]: https://win.rustup.rs
51 [install]: https://www.rust-lang.org/install.html
52
53 ## Uninstalling
54
55 Uninstalling Rust is as easy as installing it:
56
57 ```bash
58 $ rustup self uninstall
59 ```
60
61 ## Troubleshooting
62
63 If we've got Rust installed, we can open up a shell, and type this:
64
65 ```bash
66 $ rustc --version
67 ```
68
69 You should see the version number, commit hash, and commit date.
70
71 If you do, Rust has been installed successfully! Congrats!
72
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.
82
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.
92
93 [msvbt]: http://landinghub.visualstudio.com/visual-cpp-build-tools
94
95 If you are still stuck, there are a number of places where we can get
96 help. The easiest is
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].
103
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
109
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!
112
113 # Hello, world!
114
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
118 that tradition.
119
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.
124
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
132 > specific setup.
133
134 [SolidOak]: https://github.com/oakes/SolidOak
135 [various editors]: https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md
136
137 ## Creating a Project File
138
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:
143
144 ```bash
145 $ mkdir ~/projects
146 $ cd ~/projects
147 $ mkdir hello_world
148 $ cd hello_world
149 ```
150
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.
153
154 ## Writing and Running a Rust Program
155
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*.
160
161 Now, make a new file and call it *main.rs*. Open the file and type
162 the following code:
163
164 ```rust
165 fn main() {
166 println!("Hello, world!");
167 }
168 ```
169
170 Save the file, and go back to your terminal window. On Linux or OSX, enter the
171 following commands:
172
173 ```bash
174 $ rustc main.rs
175 $ ./main
176 Hello, world!
177 ```
178
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.
183
184 ## Anatomy of a Rust Program
185
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:
188
189 ```rust
190 fn main() {
191
192 }
193 ```
194
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
200 entirely.
201
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
205 space in between.
206
207 Inside the `main()` function:
208
209 ```rust
210 println!("Hello, world!");
211 ```
212
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.
216
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
222 a normal function.
223
224
225 [macro]: macros.html
226
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!
231
232 [statically allocated]: the-stack-and-the-heap.html
233
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 `;`.
238
239 [expression-oriented language]: glossary.html#expression-oriented-language
240
241 ## Compiling and Running Are Separate Steps
242
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.
245
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
248 file, like this:
249
250 ```bash
251 $ rustc main.rs
252 ```
253
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:
258
259 ```bash
260 $ ls
261 main main.rs
262 ```
263
264 On Windows, you'd enter:
265
266 ```bash
267 $ dir
268 main.exe
269 main.rs
270 ```
271
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:
275
276 ```bash
277 $ ./main # or .\main.exe on Windows
278 ```
279
280 If *main.rs* were your "Hello, world!" program, this would print `Hello,
281 world!` to your terminal.
282
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.
291
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
296 programs.
297
298 # Hello, Cargo!
299
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
304 them.
305
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.
310
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:
315
316 ```bash
317 $ cargo --version
318 ```
319
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.
323
324 ## Converting to Cargo
325
326 Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
327 to do three things:
328
329 1. Put your source file in the right directory.
330 2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere
331 else).
332 3. Make a Cargo configuration file.
333
334 Let's get started!
335
336 ### Creating a Source Directory and Removing the Old Executable
337
338 First, go back to your terminal, move to your *hello_world* directory, and
339 enter the following commands:
340
341 ```bash
342 $ mkdir src
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
345 ```
346
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.
352
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
355 Windows.
356
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.
361
362 ### Creating a Configuration File
363
364 Next, create a new file inside your *hello_world* directory, and call it
365 `Cargo.toml`.
366
367 Make sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do
368 with the configuration file.
369
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.
373
374 [TOML]: https://github.com/toml-lang/toml
375
376 Inside this file, type the following information:
377
378 ```toml
379 [package]
380
381 name = "hello_world"
382 version = "0.0.1"
383 authors = [ "Your name <you@example.com>" ]
384 ```
385
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.
389
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.
392
393 Once you've added this information to the *Cargo.toml* file, save it to finish
394 creating the configuration file.
395
396 ## Building and Running a Cargo Project
397
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
400 following commands:
401
402 ```bash
403 $ cargo build
404 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
405 $ ./target/debug/hello_world
406 Hello, world!
407 ```
408
409 Bam! If all goes well, `Hello, world!` should print to the terminal once more.
410
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:
414
415 ```bash
416 $ cargo run
417 Running `target/debug/hello_world`
418 Hello, world!
419 ```
420
421 The `run` command comes in handy when you need to rapidly iterate on a
422 project.
423
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:
428
429 ```bash
430 $ cargo run
431 Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
432 Running `target/debug/hello_world`
433 Hello, world!
434 ```
435
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.
438
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.
445
446 ### Building for Release
447
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.
453
454 ### What Is That `Cargo.lock`?
455
456 Running `cargo build` also causes Cargo to create a new file called
457 *Cargo.lock*, which looks like this:
458
459 ```toml
460 [root]
461 name = "hello_world"
462 version = "0.0.1"
463 ```
464
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.
469
470 That’s it! If you've been following along, you should have successfully built
471 `hello_world` with Cargo.
472
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:
476
477 ```bash
478 $ git clone someurl.com/foo
479 $ cd foo
480 $ cargo build
481 ```
482
483 ## Making A New Cargo Project the Easy Way
484
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.
488
489 To start a new project with Cargo, enter `cargo new` at the command line:
490
491 ```bash
492 $ cargo new hello_world --bin
493 ```
494
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).
498
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.
502
503 This output is all you need to get started. First, open `Cargo.toml`. It should
504 look something like this:
505
506 ```toml
507 [package]
508
509 name = "hello_world"
510 version = "0.1.0"
511 authors = ["Your Name <you@example.com>"]
512
513 [dependencies]
514 ```
515
516 Do not worry about the `[dependencies]` line, we will come back to it later.
517
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.
521
522 Here’s what should be in `src/main.rs`:
523
524 ```rust
525 fn main() {
526 println!("Hello, world!");
527 }
528 ```
529
530 Cargo has generated a "Hello World!" for you, and you’re ready to start coding!
531
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.
534
535 [Cargo guide]: http://doc.crates.io/guide.html
536
537 # Closing Thoughts
538
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.
542
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.
548
549 [guessinggame]: guessing-game.html
550 [syntax]: syntax-and-semantics.html