4.2 Introduction to Cargo
Rather than using rustc
directly for each file, most Rust developers rely on Cargo, Rust’s package manager and build system. Cargo simplifies various aspects of project management, including compiling code, running tests, handling dependencies, and building for different configurations. With Cargo, developers seldom need to interact with rustc
directly, as Cargo automates most of the tasks.
4.2.1 Creating a New Project with Cargo
To create a new Rust project using Cargo, you can run the following command:
cargo new my_project
This command creates a new directory called my_project
with the following structure:
my_project
├── Cargo.toml
└── src
└── main.rs
- Cargo.toml: This manifest file contains project metadata, including the project name, version, and dependencies.
- src/main.rs: This is where your Rust code resides. Cargo automatically sets up this structure, so you can begin coding immediately.
4.2.2 Compiling and Running a Program with Cargo
Once your project is set up, you can compile it with the following command:
cargo build
This will compile the project and store the resulting binary in the target/debug
directory. If you want to build your project for release with optimizations, you can use the following command:
cargo build --release
To compile and run your program in a single step, you can use:
cargo run
This command both compiles your project and executes the resulting binary, providing a streamlined workflow during development.
4.2.3 Managing Dependencies
One of Cargo's key features is managing project dependencies. Dependencies are defined in the Cargo.toml
file. For instance, to add the rand
crate (a popular library for generating random numbers), you would include the following in your Cargo.toml
file:
[dependencies]
rand = "0.8"
When you run cargo build
, Cargo will automatically download and compile the rand
crate and any other dependencies specified, including all of their transitive dependencies.
You can also add a dependency using the cargo add
command, which updates Cargo.toml
for you:
cargo add rand
4.2.4 The Role of Cargo.toml
The Cargo.toml file is essential to every Cargo project. It contains key information about the project, including:
- [package]: Defines metadata such as the project name, version, and authors.
- [dependencies]: Specifies the external crates that your project relies on.
- [dev-dependencies]: Lists dependencies needed only during development and testing.
Cargo uses this file to manage the build process and ensure that the correct versions of dependencies are included during compilation.