Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


x-i18n: generated_at: “2026-03-01T09:26:46Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 61369f359b84b646fc3773eb569a26bc18ba6edb4cf2be06a84472c7054c0e39 source_path: ch01-03-hello-cargo.md workflow: 16

你好,Cargo! (Hello, Cargo!)

Hello, Cargo!

Cargo 是 Rust 的构建系统和包管理器。大多数 Rust 开发人员 (Rustaceans) 使用这个工具来管理他们的 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
$ 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)

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
$ 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 new to use a different version control system or no version control system by using the --vcs flag. Run cargo new --help to 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]
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2024"

[dependencies]

此文件采用 TOML (Tom’s Obvious, Minimal Language) 格式,这是 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 版本。我们将在 附录 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。这个项目不需要任何其他 crates,但在第 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)

Filename: src/main.rs

fn main() {
    println!("Hello, world!");
}
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)

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
$ 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)中创建一个可执行文件,而不是在当前目录中。因为默认构建是调试构建,所以 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 # 或在 Windows 上为 .\target\debug\hello_cargo.exe
Hello, world!
$ ./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
    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 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
   Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs

为什么你不需要可执行文件呢?通常,cargo checkcargo build 快得多,因为它跳过了生成可执行文件的步骤。如果你在编写代码时不断检查你的工作,使用 cargo check 将加快让你知道项目是否仍在编译的过程!因此,许多 Rust 开发人员 (Rustaceans) 在编写程序时会定期运行 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)

Building for Release

当你的项目终于准备好发布时,你可以使用 cargo build --release 来通过优化进行编译。此命令将在 target/release 而不是 target/debug 中创建一个可执行文件。优化使你的 Rust 代码运行得更快,但开启优化会延长程序编译所需的时间。这就是为什么有两种不同的配置文件:一种用于开发,当你想要快速且频繁地重新构建时;另一种用于构建最终提供给用户的程序,该程序不会被重复重新构建且运行速度尽可能快。如果你正在对代码的运行时间进行基准测试,请务必运行 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)

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
$ git clone example.org/someproject
$ cd someproject
$ cargo build

有关 Cargo 的更多信息,请查看 其文档

For more information about Cargo, check out its documentation.

总结 (Summary)

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 rustc directly.

  • 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.