The official package manager for Rust. The cargo
CLI contains various tools
for working with Rust and its bundled tools like rustc
and rustfmt
.
Overview of the most common commands:
cargo new <name>
creates a new binary projectcargo new --lib <name>
creates a new library projectcargo install <crate>
installs a dependency from Crates.iocargo fmt
formats source codecargo fix
fixes source code based on compiler hintscargo test
runs testscargo run
runs a binary,src/main.rs
by defaultcargo build
builds the development versioncargo build --release
builds the production versioncargo doc
generates documentationcargo publish
publishes a library
The Cargo.toml
file contains cargo
configuration, like the crate name,
dependencies, language version.
For a binary, run cargo new <name>
, which generates:
src/
main.rs
Cargo.lock
Cargo.toml
For a library, run cargo new --lib <name>
, which generates:
src/
lib.rs
Cargo.lock
Cargo.toml
Can also have CLI in src/main.rs
.
The Cargo.toml
file specifies the project's version and dependencies. The
common convention is following SemVer for versioning.
Specifying a verion number as a crate version downloads the library from Crates.io. Fetching a specific Git repository or a _ file path_:
[package]
name = "yolo"
version = "4.2.0"
authors = ["oreqizer"]
[dependencies]
clap = "^2.27.1" # from crates.io
slap = { version = "^1.3.37", registry = "kratos.io" } # from custom registry
rand = { git = "https://github.com/rust-lang-nursery/rand" } # from online repo
swag = { path = "../swag" } # from a path in the local filesystem
A library project can be published to Crates.io by running
cargo publish
.
In addition to the main src/main.rs
binary, other binaries can be specified in
the bin
folder:
src/
bin/
stuff1.rs
stuff2.rs
...
Cargo.lock
Cargo.toml
In order to work with these binaries instad of src/main.rs
, the --bin
flag
can be specified like cargo run --bin stuff1
The build.rs
can be created to run a script before the build begins, such as
code generation or native code.
The file name can be adjusted in Cargo.toml
:
[package]
build = "build.rs"
Growing projects can be assembled in the form of workspaces. Specifying
workspaces is done by creating a root Cargo.toml
file:
[workspace]
members = [
# ...
]
In this folder, create members by cargo run
and add their names to
the members
array in root Cargo.toml
. The structure looks something like:
app/
src/
main.rs
Cargo.lock
Cargo.toml
utils/
src/
lib.rs
Cargo.lock
Cargo.toml
Cargo.toml
The root Cargo.toml
:
[workspace]
members = [
"app",
"utils",
]
To import utils
into app
, specify a relative path
in app/Cargo.toml
:
[depencencies]
utils = { path = "../utils" }
Commands are meant to be run directly in the root of the project, such as
cargo test
or cargo build
.
Some commands like cargo run
require the -p
flag that specifies which
project to run the command on, like cargo run -p app
.