02-Cargo 入门第一步

用 Cargo 创建、构建与运行第一个包

译文 · 基于 The Cargo Book

Cargo 入门第一步

原文链接: https://doc.rust-lang.org/cargo/getting-started/first-steps.html

本节让你快速感受一下 cargo 命令行工具。我们会演示它如何为我们生成一个新的包(package)、如何编译包内的 crate,以及如何运行生成的程序。

要用 Cargo 开始一个新包,使用 cargo new:

1
$ cargo new hello_world

Cargo 默认使用 --bin 来创建二进制程序。若要创建库,则应传入 --lib。

来看看 Cargo 为我们生成了什么:

1
2
3
4
5
6
7
8
$ cd hello_world
$ tree .
.
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files

这些就足以开始了。首先看看 Cargo.toml:

1
2
3
4
5
6
[package]
name = "hello_world"
version = "0.1.0"
edition = "2024"

[dependencies]

这称为清单(manifest),其中包含 Cargo 编译你的包所需的全部元数据。

src/main.rs 中的内容如下:

1
2
3
fn main() {
    println!("Hello, world!");
}

Cargo 为我们生成了一个 “hello world” 程序,也就是一个二进制 crate。来编译它:

1
2
$ cargo build
   Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)

然后运行它:

1
2
$ ./target/debug/hello_world
Hello, world!

也可以用 cargo run 一步完成编译并运行:

1
2
3
4
$ cargo run
     Fresh hello_world v0.1.0 (file:///path/to/package/hello_world)
   Running `target/hello_world`
Hello, world!

进一步了解

关于使用 Cargo 的更多细节,请参阅 Cargo 指南

最后修改 August 11, 2026: 更新 (70a5af133)