Properties2
TypeConcept
Note createdFeb 17, 2025

Cargo is the Rust package manager. It downloads your package dependencies, compiles the package, makes distributable packages and uploads them to https://crates.io, the community’s package registry.

Basic commands

To create a new project using Cargo, run:

cargo new project_name

This will create a new project directory (named project_name), containing the bare-bones structure for a binary application: a src directory containing an entry-point file (main.rs) and a Cargo.toml manifest file.

Compiling using Cargo

Most of the times, when trying to compile a complete project, it is a good idea to delegate the use of rustc to Cargo. To do so, navigate to a Cargo project and run:

cargo build [--release]

To generate the binaries in the ./target directory. There, you can find different directories for different configurations like debug, release, etc. When using the --release flag, Cargo will compile the code with optimizations. It will run faster, but will take longer compile.

It is also important to note that there is a shorthand to both compile and run the code using:

cargo run
Link to original

Using crates

When programming in Rust, we can use third-party packages (called crates within the context of Cargo) by specifying the dependencies in the our Cargo.toml file (within the [dependencies] section).

By default, Cargo handles Semantic Versioning, which makes the specification rand = "0.8.5" equivalent to rand = "^0.8.5"; that is, all versions over 0.8.5 but lower than 0.9.0 (since no breaking changes should be introduced in minor-version bumps).

The dependencies fetched by cargo come from https://crates.io, the default crate registry.

When compiling using Cargo, a lock-file is generated (Cargo.lock), which freezes all the dependencies until it is explicitly updated. This file can be used to ensure reproducible builds. To update it, simply run cargo update