Welcome to the Rust Tutorials series! Today, we'll dive into the Cargo Package Manager - a powerful tool that simplifies the process of managing and building Rust projects. Whether you're a beginner or an intermediate learner, this tutorial will help you understand the concept from the ground up. Let's get started!
Cargo is the default package manager for Rust projects. Its main purpose is to manage dependencies, build your project, and ensure everything runs smoothly.
To use Cargo, first, make sure you have Rust installed on your machine. If you haven't done so yet, follow our Rust Installation Guide to get started.
To create a new Rust project, open your terminal, and run the following command:
cargo new my_first_projectThis command will create a new directory named my_first_project with a basic Rust project structure.
The newly created project will have the following structure:
my_first_project/
āāā Cargo.toml
āāā src/
ā āāā main.rs
āāā target/
Cargo.toml: The project's configuration file that includes the project's name, version, dependencies, and build settings.src/: The source directory containing your Rust code files.target/: The directory where compiled binary files are stored.To build your project, navigate to the project directory and run:
cargo buildAfter successful build, you'll find the compiled binary in the target/debug/ directory.
Cargo makes it easy to add dependencies to your project. To add a new dependency, open the Cargo.toml file and modify the [dependencies] section as follows:
[dependencies]
# Add the name of the library hereSave the file and run:
cargo updateThis command will download and install the specified library and update your Cargo.toml file accordingly.
Let's use the rand library, which provides random number generation functionality.
First, add the dependency to your Cargo.toml file:
[dependencies]
rand = "0.8"Then, use the library in your Rust code:
// src/main.rs
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let number = rng.gen_range(1..101);
println!("Number generated: {}", number);
}Save the file and run:
cargo buildNow you've successfully built and run a project using a dependency!
What is Cargo's main purpose in Rust projects?
That's it for today's tutorial on Cargo Package Manager! In the next lesson, we'll dive deeper into the Rust language and explore more concepts. Stay tuned! š