]> git.proxmox.com Git - rustc.git/blame - src/doc/book/src/ch01-03-hello-cargo.md
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / doc / book / src / ch01-03-hello-cargo.md
CommitLineData
13cf67c4
XL
1## Hello, Cargo!
2
3Cargo is Rust’s build system and package manager. Most Rustaceans use this tool
4to manage their Rust projects because Cargo handles a lot of tasks for you,
5such as building your code, downloading the libraries your code depends on, and
6building those libraries. (We call libraries your code needs *dependencies*.)
7
8The simplest Rust programs, like the one we’ve written so far, don’t have any
e74abb32
XL
9dependencies. So if we had built the “Hello, world!” project with Cargo, it
10would only use the part of Cargo that handles building your code. As you write
11more complex Rust programs, you’ll add dependencies, and if you start a project
13cf67c4
XL
12using Cargo, adding dependencies will be much easier to do.
13
14Because the vast majority of Rust projects use Cargo, the rest of this book
15assumes that you’re using Cargo too. Cargo comes installed with Rust if you
dc9dc135
XL
16used the official installers discussed in the
17[“Installation”][installation]<!-- ignore --> section. If you installed Rust
18through some other means, check whether Cargo is installed by entering the
19following into your terminal:
13cf67c4 20
f035d41b 21```console
13cf67c4
XL
22$ cargo --version
23```
24
25If you see a version number, you have it! If you see an error, such as `command
26not found`, look at the documentation for your method of installation to
27determine how to install Cargo separately.
28
29### Creating a Project with Cargo
30
31Let’s create a new project using Cargo and look at how it differs from our
e74abb32 32original “Hello, world!” project. Navigate back to your *projects* directory (or
13cf67c4
XL
33wherever you decided to store your code). Then, on any operating system, run
34the following:
35
f035d41b 36```console
13cf67c4
XL
37$ cargo new hello_cargo
38$ cd hello_cargo
39```
40
41The first command creates a new directory called *hello_cargo*. We’ve named
42our project *hello_cargo*, and Cargo creates its files in a directory of the
43same name.
44
45Go into the *hello_cargo* directory and list the files. You’ll see that Cargo
46has generated two files and one directory for us: a *Cargo.toml* file and a
74b04a01
XL
47*src* directory with a *main.rs* file inside.
48
49It has also initialized a new Git repository along with a *.gitignore* file.
50Git files won’t be generated if you run `cargo new` within an existing Git
51repository; you can override this behavior by using `cargo new --vcs=git`.
13cf67c4
XL
52
53> Note: Git is a common version control system. You can change `cargo new` to
54> use a different version control system or no version control system by using
55> the `--vcs` flag. Run `cargo new --help` to see the available options.
56
57Open *Cargo.toml* in your text editor of choice. It should look similar to the
58code in Listing 1-2.
59
60<span class="filename">Filename: Cargo.toml</span>
61
62```toml
63[package]
64name = "hello_cargo"
65version = "0.1.0"
66authors = ["Your Name <you@example.com>"]
67edition = "2018"
68
69[dependencies]
70```
71
72<span class="caption">Listing 1-2: Contents of *Cargo.toml* generated by `cargo
73new`</span>
74
3dfed10e
XL
75This file is in the [*TOML*](https://toml.io)<!-- ignore --> (*Tom’s Obvious,
76Minimal Language*) format, which is Cargo’s configuration format.
13cf67c4
XL
77
78The first line, `[package]`, is a section heading that indicates that the
79following statements are configuring a package. As we add more information to
80this file, we’ll add other sections.
81
82The next four lines set the configuration information Cargo needs to compile
9fa01778
XL
83your program: the name, the version, who wrote it, and the edition of Rust to
84use. Cargo gets your name and email information from your environment, so if
85that information is not correct, fix the information now and then save the
86file. We’ll talk about the `edition` key in Appendix E.
13cf67c4
XL
87
88The last line, `[dependencies]`, is the start of a section for you to list any
89of your project’s dependencies. In Rust, packages of code are referred to as
90*crates*. We won’t need any other crates for this project, but we will in the
91first project in Chapter 2, so we’ll use this dependencies section then.
92
93Now open *src/main.rs* and take a look:
94
95<span class="filename">Filename: src/main.rs</span>
96
97```rust
98fn main() {
99 println!("Hello, world!");
100}
101```
102
e74abb32
XL
103Cargo has generated a “Hello, world!” program for you, just like the one we
104wrote in Listing 1-1! So far, the differences between our previous project and
105the project Cargo generates are that Cargo placed the code in the *src*
106directory, and we have a *Cargo.toml* configuration file in the top directory.
13cf67c4
XL
107
108Cargo expects your source files to live inside the *src* directory. The
109top-level project directory is just for README files, license information,
110configuration files, and anything else not related to your code. Using Cargo
111helps you organize your projects. There’s a place for everything, and
112everything is in its place.
113
e74abb32
XL
114If you started a project that doesn’t use Cargo, as we did with the “Hello,
115world!” project, you can convert it to a project that does use Cargo. Move the
13cf67c4
XL
116project code into the *src* directory and create an appropriate *Cargo.toml*
117file.
118
119### Building and Running a Cargo Project
120
e74abb32 121Now let’s look at what’s different when we build and run the “Hello, world!”
13cf67c4
XL
122program with Cargo! From your *hello_cargo* directory, build your project by
123entering the following command:
124
f035d41b 125```console
13cf67c4
XL
126$ cargo build
127 Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
128 Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
129```
130
131This command creates an executable file in *target/debug/hello_cargo* (or
132*target\debug\hello_cargo.exe* on Windows) rather than in your current
133directory. You can run the executable with this command:
134
f035d41b 135```console
13cf67c4
XL
136$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
137Hello, world!
138```
139
140If all goes well, `Hello, world!` should print to the terminal. Running `cargo
141build` for the first time also causes Cargo to create a new file at the top
142level: *Cargo.lock*. This file keeps track of the exact versions of
143dependencies in your project. This project doesn’t have dependencies, so the
144file is a bit sparse. You won’t ever need to change this file manually; Cargo
145manages its contents for you.
146
147We just built a project with `cargo build` and ran it with
148`./target/debug/hello_cargo`, but we can also use `cargo run` to compile the
149code and then run the resulting executable all in one command:
150
f035d41b 151```console
13cf67c4
XL
152$ cargo run
153 Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
154 Running `target/debug/hello_cargo`
155Hello, world!
156```
157
158Notice that this time we didn’t see output indicating that Cargo was compiling
159`hello_cargo`. Cargo figured out that the files hadn’t changed, so it just ran
160the binary. If you had modified your source code, Cargo would have rebuilt the
161project before running it, and you would have seen this output:
162
f035d41b 163```console
13cf67c4
XL
164$ cargo run
165 Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
166 Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
167 Running `target/debug/hello_cargo`
168Hello, world!
169```
170
171Cargo also provides a command called `cargo check`. This command quickly checks
172your code to make sure it compiles but doesn’t produce an executable:
173
f035d41b 174```console
13cf67c4
XL
175$ cargo check
176 Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
177 Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
178```
179
180Why would you not want an executable? Often, `cargo check` is much faster than
181`cargo build`, because it skips the step of producing an executable. If you’re
182continually checking your work while writing the code, using `cargo check` will
183speed up the process! As such, many Rustaceans run `cargo check` periodically
184as they write their program to make sure it compiles. Then they run `cargo
185build` when they’re ready to use the executable.
186
187Let’s recap what we’ve learned so far about Cargo:
188
f035d41b 189* We can build a project using `cargo build`.
13cf67c4 190* We can build and run a project in one step using `cargo run`.
6a06907d
XL
191* We can build a project without producing a binary to check for errors using
192 `cargo check`.
13cf67c4
XL
193* Instead of saving the result of the build in the same directory as our code,
194 Cargo stores it in the *target/debug* directory.
195
196An additional advantage of using Cargo is that the commands are the same no
197matter which operating system you’re working on. So, at this point, we’ll no
198longer provide specific instructions for Linux and macOS versus Windows.
199
200### Building for Release
201
202When your project is finally ready for release, you can use `cargo build
203--release` to compile it with optimizations. This command will create an
204executable in *target/release* instead of *target/debug*. The optimizations
205make your Rust code run faster, but turning them on lengthens the time it takes
206for your program to compile. This is why there are two different profiles: one
207for development, when you want to rebuild quickly and often, and another for
208building the final program you’ll give to a user that won’t be rebuilt
209repeatedly and that will run as fast as possible. If you’re benchmarking your
210code’s running time, be sure to run `cargo build --release` and benchmark with
211the executable in *target/release*.
212
213### Cargo as Convention
214
215With simple projects, Cargo doesn’t provide a lot of value over just using
216`rustc`, but it will prove its worth as your programs become more intricate.
217With complex projects composed of multiple crates, it’s much easier to let
218Cargo coordinate the build.
219
220Even though the `hello_cargo` project is simple, it now uses much of the real
221tooling you’ll use in the rest of your Rust career. In fact, to work on any
222existing projects, you can use the following commands to check out the code
223using Git, change to that project’s directory, and build:
224
f035d41b 225```console
13cf67c4
XL
226$ git clone someurl.com/someproject
227$ cd someproject
228$ cargo build
229```
230
231For more information about Cargo, check out [its documentation].
232
233[its documentation]: https://doc.rust-lang.org/cargo/
234
235## Summary
236
237You’re already off to a great start on your Rust journey! In this chapter,
238you’ve learned how to:
239
240* Install the latest stable version of Rust using `rustup`
241* Update to a newer Rust version
242* Open locally installed documentation
e74abb32 243* Write and run a “Hello, world!” program using `rustc` directly
13cf67c4
XL
244* Create and run a new project using the conventions of Cargo
245
246This is a great time to build a more substantial program to get used to reading
247and writing Rust code. So, in Chapter 2, we’ll build a guessing game program.
248If you would rather start by learning how common programming concepts work in
249Rust, see Chapter 3 and then return to Chapter 2.
9fa01778
XL
250
251[installation]: ch01-01-installation.html#installation