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:
在创建的目录结构中:
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命令: