Cargo
Cargo is a build system (turns Rust code into executable binaries) and a
package manager (downloads and compiles project’s dependencies). It’s
analogical to node’s npm
.
cargo new
creates a new project from a standard template. There’s a
Cargo.toml
file and the src/
directory.
Toml file
The Cargo.toml
file contains the project’s metadata (like npm’s
project.json
). After building the project, Cargo.lock
is created as well,
which works like project-lock.json
of npm. It specifies the exact version
numbers of all the dependencies. This way, future builds are reliable. If we
want to update some crates, ignoring pinned versions from Cargo.lock
, we can
run cargo update
. It will update the versions (respecting SemVer), and it will
also update Cargo.lock
with the new versions.
Running
cargo run
does the following:
- compiles the code in debug mode (for maximal error information) using
cargo build
- executes the binary
The binaries are produced in /target/debug/
or target/release/
.
Release Profiles
Rust apps have two profiles:
- dev (used with
cargo build
) - good defaults for development - release (used with
cargo build --release
) - good defaults for release builds
These profiles can be customized in the Cargo.toml
file. Example:
The dev
profile has 0 optimizations (because we want it to compile fast even
though the code runs slower).
Other commands
cargo build
- downloads dependencies and compiles the code into an executable binary. It uses the “rustc” compiler behind the scenes.cargo check
- checks if the code compiles, without building the binary. It’s faster thancargo build
.cargo doc
- builds HTML documentation for every dependency in the current project.cargo init
- initiates a Rust project with pre-existing files in it.cargo create
would create a project from scratch.cargo add
- adds crates. This subcommand needs to be installed first withcargo install cargo-edit
.
Crates
Packages are called crates. The open-source ones are shared at https://crates.io.
Binary crates
Binary crates might be installed with cargo install some-crate
. They will be
installed in the $HOME/.cargo/bin
directory.