We dive into Cargo, the powerful and convenient build system and package manager for Rust.
基于Steve Klabnik的《The Rust Programming Language》一书,我们深入了解Cargo,这是Rust强大而方便的构建系统和包管理器。
Cargo is a robust and efficient build system and package manager for Rust, designed to help manage project dependencies and ensure consistent builds across various environments.
Cargo是Rust的一个强大而高效的构建系统和包管理器,旨在帮助管理项目依赖关系,并确保在各种环境中构建一致。
To create a new program with cargo :
要使用cargo创建新程序,请执行以下操作:
$ cargo new main$ cd main$ ls
Directory Structure : 目录结构:
main
└── target└── debug└── release
└── src└── main.rs
├── Cargo.toml
In the created directory structure:
在创建的目录结构中:
main
is the root directory of the program.main
是程序的根目录。Cargo.toml
contains metadata about the project and its dependencies.Cargo.toml
包含关于项目及其依赖项的元数据。src
is a directory containing the source code of the program.src
是包含程序源代码的目录。main.rs
is the main entry point to the program. This is where the main function is defined which is the entry point of the program.main.rs
是程序的主要入口点。这是定义main函数的地方,它是程序的入口点。target
is the directory that stores all the builds or outputs.target
是存储所有构建或输出的目录。
The important files : 重要文件:
The Cargo.toml
file looks like this:Cargo.toml
文件看起来像这样:
[package]
name = "main"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
edition = "2018"
[dependencies]
The [package]
section defines the package name, version, authors, and edition. The [dependencies]
section is where you list your project dependencies.[package]
部分定义了软件包名称、版本、作者和版本。 [dependencies]
部分是您列出项目依赖项的地方。
The main.rs
file looks like this:main.rs
文件看起来像这样:
fn main() {println!("Hello, world!");
}
This is a simple Rust program that prints “Hello, world!” to the console.
这是一个简单的Rust程序,打印“Hello,world!”到控制台
To build and run your program, navigate to the project directory (in this case, main
) and run cargo run
.
要构建并运行程序,请导航到项目目录(在本例中为 main
)并运行 cargo run
。
$ cd main
$ cargo run
This command builds your project and runs the resulting binary.
此命令生成项目并运行生成的二进制文件。
And that’s the basic structure and workflow of a Cargo program in Rust!
这就是Rust中Cargo程序的基本结构和工作流!
Some other useful cargo commands :
其他一些有用的cargo命令:
cargo build
: used to build for testing (Output directory :target/debug
)cargo build
:用于构建测试(输出目录:target/debug
)cargo build --release
: used to build for release (Output directory :target/debug
)cargo build --release
:用于构建发布(输出目录:target/debug
)cargo check
: to check if the program would compile without actually compiling it.cargo check
:检查程序是否可以编译,而无需实际编译。