Skip to content

Rust - Package Manager

Cargo is Rust’s official build tool and package manager. It handles a wide range of tasks, making Rust development streamlined and professional. Cargo is your primary interface for building, testing, and managing project dependencies.

CommandDescription
cargo new <name>Creates a new binary (executable) Rust project in a directory named <name>.
cargo new <name> --libCreates a new library (shareable code) Rust project.
cargo runCompiles and runs your binary crate.
cargo buildCompiles the current project without running it.
cargo build --releaseCompiles the project with optimizations for performance.
cargo checkQuickly checks your code for errors without producing an executable, which is much faster than a full build.
cargo testRuns all tests in your project.
cargo fmtAutomatically formats your code according to the official Rust style guidelines.
cargo clippyA powerful linter that catches common mistakes and suggests improvements to your code.
cargo updateUpdates your dependencies to the latest allowed versions according to Cargo.toml.
cargo cleanRemoves the target directory, which contains all build artifacts.

Let’s build a classic number guessing game. This project will demonstrate how to create a new project, add an external dependency, and write modern, idiomatic Rust code.

Open your terminal and run:

cargo new guessing_game

Cargo generates a standard project structure for you:

guessing_game/
├── Cargo.toml
└── src/
└── main.rs
  • Cargo.toml: The manifest file. It contains project metadata and a list of dependencies.
  • src/main.rs: The source code for your main application binary.

We need to generate a random number. The Rust standard library doesn’t include a random number generator, but we can easily add one from crates.io, the official Rust package registry. The most popular crate for this is rand.

Open your Cargo.toml file and add rand under the [dependencies] section. You can find the latest version on crates.io.

[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021" # Ensure you are using a modern Rust edition
[dependencies]
rand = "0.8" # Use a recent version of the rand crate

Now, replace the content of src/main.rs with the game logic. This code demonstrates importing a crate, handling user input, parsing strings, and using a loop with match for control flow.

use std::io;
use std::cmp::Ordering;
use rand::Rng; // Import the Rng trait from the rand crate
fn main() {
println!("Guess the number!");
// Generate a secret number between 1 and 100
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
// Convert the string to a number, handling invalid input
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please type a number!");
continue; // Skip to the next loop iteration
}
};
println!("You guessed: {}", guess);
// Compare the guess to the secret number
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break; // Exit the loop
}
}
}
}

Navigate to your project directory (guessing_game) in the terminal and run:

cargo run

The first time you run this, Cargo will download and compile rand and its dependencies. Then, it will compile and run your game.

After the first build, you’ll notice a new file: Cargo.lock. This file records the exact versions of all dependencies used in your project. This ensures that every developer on your team, as well as your production build server, uses the same dependency versions, guaranteeing reproducible builds.