你好,Cargo!
Hello, Cargo!
Cargo 是 Rust 的构建系统和包管理器。大多数 Rust 开发者使用此工具来管理他们的 Rust 项目,因为 Cargo 为你处理了许多任务,例如构建代码、下载代码依赖的库以及构建这些库。(我们将代码需要的库称为“依赖” [dependencies]。)
Cargo is Rust’s build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries. (We call the libraries that your code needs dependencies.)
最简单的 Rust 程序,比如我们目前写的这个,没有任何依赖。如果我们用 Cargo 构建 “Hello, world!” 项目,它只会使用 Cargo 处理构建代码的部分。随着你编写更复杂的 Rust 程序,你会添加依赖项,如果你使用 Cargo 开始一个项目,添加依赖项将会变得容易得多。
The simplest Rust programs, like the one we’ve written so far, don’t have any dependencies. If we had built the “Hello, world!” project with Cargo, it would only use the part of Cargo that handles building your code. As you write more complex Rust programs, you’ll add dependencies, and if you start a project using Cargo, adding dependencies will be much easier to do.
由于绝大多数 Rust 项目都使用 Cargo,本书的其余部分都假设你也使用 Cargo。如果你使用了 “安装” 章节中讨论的官方安装程序,那么 Cargo 会随 Rust 一起安装。如果你通过其他方式安装了 Rust,请在终端输入以下命令检查是否安装了 Cargo:
Because the vast majority of Rust projects use Cargo, the rest of this book assumes that you’re using Cargo too. Cargo comes installed with Rust if you used the official installers discussed in the “Installation” section. If you installed Rust through some other means, check whether Cargo is installed by entering the following in your terminal:
$ cargo --version
如果你看到版本号,说明你已经安装了它!如果你看到错误,例如 command not found,请查看你的安装方法的文档,以确定如何单独安装 Cargo。
If you see a version number, you have it! If you see an error, such as command not found, look at the documentation for your method of installation to
determine how to install Cargo separately.
使用 Cargo 创建项目
Creating a Project with Cargo
让我们使用 Cargo 创建一个新项目,看看它与我们最初的 “Hello, world!” 项目有何不同。导航回到你的 projects 目录(或者你决定存储代码的任何地方)。然后,在任何操作系统上运行以下命令:
Let’s create a new project using Cargo and look at how it differs from our original “Hello, world!” project. Navigate back to your projects directory (or wherever you decided to store your code). Then, on any operating system, run the following:
$ cargo new hello_cargo
$ cd hello_cargo
第一条命令创建了一个名为 hello_cargo 的新目录和项目。我们将项目命名为 hello_cargo,Cargo 会在同名目录中创建其文件。
The first command creates a new directory and project called hello_cargo. We’ve named our project hello_cargo, and Cargo creates its files in a directory of the same name.
进入 hello_cargo 目录并列出文件。你会看到 Cargo 为我们生成了两个文件和一个目录:一个 Cargo.toml 文件和一个包含 main.rs 文件的 src 目录。
Go into the hello_cargo directory and list the files. You’ll see that Cargo has generated two files and one directory for us: a Cargo.toml file and a src directory with a main.rs file inside.
它还初始化了一个新的 Git 仓库以及一个 .gitignore 文件。如果你在现有的 Git 仓库中运行 cargo new,则不会生成 Git 文件;你可以通过使用 cargo new --vcs=git 来覆盖此行为。
It has also initialized a new Git repository along with a .gitignore file.
Git files won’t be generated if you run cargo new within an existing Git
repository; you can override this behavior by using cargo new --vcs=git.
注意:Git 是一种常用的版本控制系统。你可以通过使用
--vcs标志将cargo new更改为使用不同的版本控制系统或不使用版本控制系统。运行cargo new --help查看可用选项。
Note: Git is a common version control system. You can change
cargo newto use a different version control system or no version control system by using the--vcsflag. Runcargo new --helpto see the available options.
在你选择的文本编辑器中打开 Cargo.toml。它应该看起来类似于示例 1-2 中的代码。
Open Cargo.toml in your text editor of choice. It should look similar to the code in Listing 1-2.
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"
[dependencies]
此文件采用 TOML (Tom’s Obvious, Minimal Language,Tom 的显而易见的、极简的语言) 格式,这是 Cargo 的配置格式。
This file is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format.
第一行 [package] 是一个部分标题,表示接下来的语句正在配置一个包。随着我们向该文件添加更多信息,我们将添加其他部分。
The first line, [package], is a section heading that indicates that the
following statements are configuring a package. As we add more information to
this file, we’ll add other sections.
接下来的三行设置了 Cargo 编译程序所需的配置信息:名称、版本和要使用的 Rust 版本 (edition)。我们将在 附录 E 中讨论 edition 键。
The next three lines set the configuration information Cargo needs to compile
your program: the name, the version, and the edition of Rust to use. We’ll talk
about the edition key in Appendix E.
最后一行 [dependencies] 是供你列出项目任何依赖项的部分的开始。在 Rust 中,代码包被称为 crates。这个项目我们不需要任何其他的 crate,但在第 2 章的第一个项目中会需要,所以届时我们将使用这个依赖部分。
The last line, [dependencies], is the start of a section for you to list any
of your project’s dependencies. In Rust, packages of code are referred to as
crates. We won’t need any other crates for this project, but we will in the
first project in Chapter 2, so we’ll use this dependencies section then.
现在打开 src/main.rs 看看:
Now open src/main.rs and take a look:
文件名:src/main.rs Filename: src/main.rs
fn main() {
println!("Hello, world!");
}
Cargo 为你生成了一个 “Hello, world!” 程序,就像我们在示例 1-1 中编写的一样!到目前为止,我们的项目与 Cargo 生成的项目之间的区别在于 Cargo 将代码放在了 src 目录中,并且我们在顶层目录中有一个 Cargo.toml 配置文件。
Cargo has generated a “Hello, world!” program for you, just like the one we wrote in Listing 1-1! So far, the differences between our project and the project Cargo generated are that Cargo placed the code in the src directory, and we have a Cargo.toml configuration file in the top directory.
Cargo 期望你的源文件位于 src 目录内。顶级项目目录仅用于存放 README 文件、许可信息、配置文件以及与代码无关的其他任何内容。使用 Cargo 有助于你组织项目。每件东西都有它的位置,并且每件东西都在它的位置上。
Cargo expects your source files to live inside the src directory. The top-level project directory is just for README files, license information, configuration files, and anything else not related to your code. Using Cargo helps you organize your projects. There’s a place for everything, and everything is in its place.
如果你启动了一个没有使用 Cargo 的项目(就像我们对 “Hello, world!” 项目所做的那样),你可以将其转换为使用 Cargo 的项目。将项目代码移动到 src 目录并创建一个适当的 Cargo.toml 文件。获取该 Cargo.toml 文件的一种简单方法是运行 cargo init,它会自动为你创建。
If you started a project that doesn’t use Cargo, as we did with the “Hello,
world!” project, you can convert it to a project that does use Cargo. Move the
project code into the src directory and create an appropriate Cargo.toml
file. One easy way to get that Cargo.toml file is to run cargo init, which
will create it for you automatically.
构建并运行 Cargo 项目
Building and Running a Cargo Project
现在让我们看看在使用 Cargo 构建和运行 “Hello, world!” 程序时有什么不同!在你的 hello_cargo 目录下,通过输入以下命令来构建你的项目:
Now let’s look at what’s different when we build and run the “Hello, world!” program with Cargo! From your hello_cargo directory, build your project by entering the following command:
$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
此命令会在 target/debug/hello_cargo(或者 Windows 上的 target\debug\hello_cargo.exe)中创建一个可执行文件,而不是在当前目录中。因为默认构建是调试构建 (debug build),Cargo 将二进制文件放在名为 debug 的目录中。你可以使用此命令运行可执行文件:
This command creates an executable file in target/debug/hello_cargo (or target\debug\hello_cargo.exe on Windows) rather than in your current directory. Because the default build is a debug build, Cargo puts the binary in a directory named debug. You can run the executable with this command:
$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!
如果一切顺利,Hello, world! 应该会打印到终端。第一次运行 cargo build 还会导致 Cargo 在顶层创建一个新文件:Cargo.lock。此文件用于跟踪项目中依赖项的确切版本。这个项目没有依赖项,所以该文件内容比较稀疏。你永远不需要手动更改此文件;Cargo 会为你管理其内容。
If all goes well, Hello, world! should print to the terminal. Running cargo build for the first time also causes Cargo to create a new file at the top
level: Cargo.lock. This file keeps track of the exact versions of
dependencies in your project. This project doesn’t have dependencies, so the
file is a bit sparse. You won’t ever need to change this file manually; Cargo
manages its contents for you.
我们刚刚用 cargo build 构建了一个项目并用 ./target/debug/hello_cargo 运行了它,但我们也可以使用 cargo run 在一条命令中编译代码并运行生成的可执行文件:
We just built a project with cargo build and ran it with
./target/debug/hello_cargo, but we can also use cargo run to compile the
code and then run the resultant executable all in one command:
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/hello_cargo`
Hello, world!
使用 cargo run 比记住运行 cargo build 然后使用二进制文件的完整路径更方便,因此大多数开发者使用 cargo run。
Using cargo run is more convenient than having to remember to run cargo build and then use the whole path to the binary, so most developers use cargo run.
请注意,这次我们没有看到表明 Cargo 正在编译 hello_cargo 的输出。Cargo 发现文件没有变化,所以它没有重新构建,而是直接运行了二进制文件。如果你修改了源代码,Cargo 会在运行之前重新构建项目,你将会看到如下输出:
Notice that this time we didn’t see output indicating that Cargo was compiling
hello_cargo. Cargo figured out that the files hadn’t changed, so it didn’t
rebuild but just ran the binary. If you had modified your source code, Cargo
would have rebuilt the project before running it, and you would have seen this
output:
$ cargo run
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
Running `target/debug/hello_cargo`
Hello, world!
Cargo 还提供了一个名为 cargo check 的命令。此命令可以快速检查代码以确保其可以编译,但不会产生可执行文件:
Cargo also provides a command called cargo check. This command quickly checks
your code to make sure it compiles but doesn’t produce an executable:
$ cargo check
Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
为什么你会不想要可执行文件呢?通常,cargo check 比 cargo build 快得多,因为它跳过了生成可执行文件的步骤。如果你在编写代码时不断检查你的工作,使用 cargo check 将加快让你知道项目是否仍在编译的过程!因此,许多 Rust 开发者在编写程序时会定期运行 cargo check 以确保其能够编译。然后,当他们准备好使用可执行文件时,再运行 cargo build。
Why would you not want an executable? Often, cargo check is much faster than
cargo build because it skips the step of producing an executable. If you’re
continually checking your work while writing the code, using cargo check will
speed up the process of letting you know if your project is still compiling! As
such, many Rustaceans run cargo check periodically as they write their
program to make sure it compiles. Then, they run cargo build when they’re
ready to use the executable.
让我们回顾一下到目前为止我们学到的关于 Cargo 的知识:
Let’s recap what we’ve learned so far about Cargo:
-
我们可以使用
cargo new创建一个项目。 -
我们可以使用
cargo build构建一个项目。 -
我们可以使用
cargo run在一个步骤中构建并运行项目。 -
我们可以使用
cargo check在不产生二进制文件的情况下构建项目以检查错误。 -
Cargo 不会将构建结果保存在与代码相同的目录中,而是将其存储在 target/debug 目录中。
-
We can create a project using
cargo new. -
We can build a project using
cargo build. -
We can build and run a project in one step using
cargo run. -
We can build a project without producing a binary to check for errors using
cargo check. -
Instead of saving the result of the build in the same directory as our code, Cargo stores it in the target/debug directory.
使用 Cargo 的另一个优点是,无论你使用的是哪种操作系统,命令都是相同的。因此,从现在起,我们不再为 Linux 和 macOS 还是 Windows 提供特定说明。
An additional advantage of using Cargo is that the commands are the same no matter which operating system you’re working on. So, at this point, we’ll no longer provide specific instructions for Linux and macOS versus Windows.
发布构建
Building for Release
当你的项目最终准备好发布时,你可以使用 cargo build --release 来通过优化进行编译。此命令将在 target/release 而不是 target/debug 中创建一个可执行文件。这些优化使你的 Rust 代码运行得更快,但启用它们会延长程序编译所需的时间。这就是为什么有两种不同的配置文件:一种用于开发,当你希望快速且频繁地重新构建时;另一种用于构建你将提供给用户的最终程序,它不会被反复重新构建,并且将运行得尽可能快。如果你正在对代码的运行时间进行基准测试 (benchmarking),请务必运行 cargo build --release 并使用 target/release 中的可执行文件进行基准测试。
When your project is finally ready for release, you can use cargo build --release to compile it with optimizations. This command will create an
executable in target/release instead of target/debug. The optimizations
make your Rust code run faster, but turning them on lengthens the time it takes
for your program to compile. This is why there are two different profiles: one
for development, when you want to rebuild quickly and often, and another for
building the final program you’ll give to a user that won’t be rebuilt
repeatedly and that will run as fast as possible. If you’re benchmarking your
code’s running time, be sure to run cargo build --release and benchmark with
the executable in target/release.
利用 Cargo 的约定
Leveraging Cargo’s Conventions
对于简单的项目,Cargo 相比于直接使用 rustc 并没有提供太大的价值,但随着你的程序变得越来越复杂,它将证明其价值。一旦程序发展到多个文件或需要依赖项,让 Cargo 协调构建就会容易得多。
With simple projects, Cargo doesn’t provide a lot of value over just using
rustc, but it will prove its worth as your programs become more intricate.
Once programs grow to multiple files or need a dependency, it’s much easier to
let Cargo coordinate the build.
即使 hello_cargo 项目很简单,它现在也使用了你在 Rust 职业生涯的剩余时间里将使用的许多真实工具。事实上,要在任何现有项目上工作,你可以使用以下命令通过 Git 检出代码,进入该项目目录并构建:
Even though the hello_cargo project is simple, it now uses much of the real
tooling you’ll use in the rest of your Rust career. In fact, to work on any
existing projects, you can use the following commands to check out the code
using Git, change to that project’s directory, and build:
$ git clone example.org/someproject
$ cd someproject
$ cargo build
有关 Cargo 的更多信息,请查看 其文档。
For more information about Cargo, check out its documentation.
总结
Summary
你的 Rust 之旅已经有了一个很好的开始!在本章中,你学习了如何:
You’re already off to a great start on your Rust journey! In this chapter, you learned how to:
-
使用
rustup安装最新的 Rust 稳定版本。 -
更新到较新的 Rust 版本。
-
打开本地安装的文档。
-
直接使用
rustc编写并运行 “Hello, world!” 程序。 -
使用 Cargo 的约定创建并运行一个新项目。
-
Install the latest stable version of Rust using
rustup. -
Update to a newer Rust version.
-
Open locally installed documentation.
-
Write and run a “Hello, world!” program using
rustcdirectly. -
Create and run a new project using the conventions of Cargo.
现在是构建一个更充实的程序以适应阅读和编写 Rust 代码的好时机。因此,在第 2 章中,我们将构建一个猜数字游戏程序。如果你更愿意先学习常见的编程概念在 Rust 中是如何工作的,请参阅第 3 章,然后再返回第 2 章。
This is a great time to build a more substantial program to get used to reading and writing Rust code. So, in Chapter 2, we’ll build a guessing game program. If you would rather start by learning how common programming concepts work in Rust, see Chapter 3 and then return to Chapter 2.